1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "x86-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62 "x86-experimental-vector-widening-legalization", cl::init(false),
63 cl::desc("Enable an experimental vector type legalization through widening "
64 "rather than promotion."),
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68 "x86-experimental-vector-shuffle-lowering", cl::init(false),
69 cl::desc("Enable an experimental vector shuffle lowering code path."),
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77 SelectionDAG &DAG, SDLoc dl,
78 unsigned vectorWidth) {
79 assert((vectorWidth == 128 || vectorWidth == 256) &&
80 "Unsupported vector width");
81 EVT VT = Vec.getValueType();
82 EVT ElVT = VT.getVectorElementType();
83 unsigned Factor = VT.getSizeInBits()/vectorWidth;
84 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85 VT.getVectorNumElements()/Factor);
87 // Extract from UNDEF is UNDEF.
88 if (Vec.getOpcode() == ISD::UNDEF)
89 return DAG.getUNDEF(ResultVT);
91 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
92 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
94 // This is the index of the first element of the vectorWidth-bit chunk
96 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
99 // If the input is a buildvector just emit a smaller one.
100 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
105 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119 SelectionDAG &DAG, SDLoc dl) {
120 assert((Vec.getValueType().is256BitVector() ||
121 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127 SelectionDAG &DAG, SDLoc dl) {
128 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133 unsigned IdxVal, SelectionDAG &DAG,
134 SDLoc dl, unsigned vectorWidth) {
135 assert((vectorWidth == 128 || vectorWidth == 256) &&
136 "Unsupported vector width");
137 // Inserting UNDEF is Result
138 if (Vec.getOpcode() == ISD::UNDEF)
140 EVT VT = Vec.getValueType();
141 EVT ElVT = VT.getVectorElementType();
142 EVT ResultVT = Result.getValueType();
144 // Insert the relevant vectorWidth bits.
145 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
147 // This is the index of the first element of the vectorWidth-bit chunk
149 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
152 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
156 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference. Idx is an index in the 128 bits
160 /// we want. It need not be aligned to a 128-bit bounday. That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163 unsigned IdxVal, SelectionDAG &DAG,
165 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170 unsigned IdxVal, SelectionDAG &DAG,
172 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181 unsigned NumElems, SelectionDAG &DAG,
183 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188 unsigned NumElems, SelectionDAG &DAG,
190 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195 if (TT.isOSBinFormatMachO()) {
196 if (TT.getArch() == Triple::x86_64)
197 return new X86_64MachoTargetObjectFile();
198 return new TargetLoweringObjectFileMachO();
202 return new X86LinuxTargetObjectFile();
203 if (TT.isOSBinFormatELF())
204 return new TargetLoweringObjectFileELF();
205 if (TT.isKnownWindowsMSVCEnvironment())
206 return new X86WindowsTargetObjectFile();
207 if (TT.isOSBinFormatCOFF())
208 return new TargetLoweringObjectFileCOFF();
209 llvm_unreachable("unknown subtarget type");
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216 Subtarget = &TM.getSubtarget<X86Subtarget>();
217 X86ScalarSSEf64 = Subtarget->hasSSE2();
218 X86ScalarSSEf32 = Subtarget->hasSSE1();
219 TD = getDataLayout();
221 resetOperationActions();
224 void X86TargetLowering::resetOperationActions() {
225 const TargetMachine &TM = getTargetMachine();
226 static bool FirstTimeThrough = true;
228 // If none of the target options have changed, then we don't need to reset the
229 // operation actions.
230 if (!FirstTimeThrough && TO == TM.Options) return;
232 if (!FirstTimeThrough) {
233 // Reinitialize the actions.
235 FirstTimeThrough = false;
240 // Set up the TargetLowering object.
241 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
243 // X86 is weird, it always uses i8 for shift amounts and setcc results.
244 setBooleanContents(ZeroOrOneBooleanContent);
245 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
248 // For 64-bit since we have so many registers use the ILP scheduler, for
249 // 32-bit code use the register pressure specific scheduling.
250 // For Atom, always use ILP scheduling.
251 if (Subtarget->isAtom())
252 setSchedulingPreference(Sched::ILP);
253 else if (Subtarget->is64Bit())
254 setSchedulingPreference(Sched::ILP);
256 setSchedulingPreference(Sched::RegPressure);
257 const X86RegisterInfo *RegInfo =
258 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
259 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
261 // Bypass expensive divides on Atom when compiling with O2
262 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263 addBypassSlowDiv(32, 8);
264 if (Subtarget->is64Bit())
265 addBypassSlowDiv(64, 16);
268 if (Subtarget->isTargetKnownWindowsMSVC()) {
269 // Setup Windows compiler runtime calls.
270 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272 setLibcallName(RTLIB::SREM_I64, "_allrem");
273 setLibcallName(RTLIB::UREM_I64, "_aullrem");
274 setLibcallName(RTLIB::MUL_I64, "_allmul");
275 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
281 // The _ftol2 runtime function has an unusual calling conv, which
282 // is modeled by a special pseudo-instruction.
283 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
289 if (Subtarget->isTargetDarwin()) {
290 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291 setUseUnderscoreSetJmp(false);
292 setUseUnderscoreLongJmp(false);
293 } else if (Subtarget->isTargetWindowsGNU()) {
294 // MS runtime is weird: it exports _setjmp, but longjmp!
295 setUseUnderscoreSetJmp(true);
296 setUseUnderscoreLongJmp(false);
298 setUseUnderscoreSetJmp(true);
299 setUseUnderscoreLongJmp(true);
302 // Set up the register classes.
303 addRegisterClass(MVT::i8, &X86::GR8RegClass);
304 addRegisterClass(MVT::i16, &X86::GR16RegClass);
305 addRegisterClass(MVT::i32, &X86::GR32RegClass);
306 if (Subtarget->is64Bit())
307 addRegisterClass(MVT::i64, &X86::GR64RegClass);
309 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
311 // We don't accept any truncstore of integer registers.
312 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
319 // SETOEQ and SETUNE require checking two conditions.
320 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
327 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
329 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
330 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
331 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
333 if (Subtarget->is64Bit()) {
334 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
335 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
336 } else if (!TM.Options.UseSoftFloat) {
337 // We have an algorithm for SSE2->double, and we turn this into a
338 // 64-bit FILD followed by conditional FADD for other targets.
339 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
340 // We have an algorithm for SSE2, and we turn this into a 64-bit
341 // FILD for other targets.
342 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
345 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
347 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
350 if (!TM.Options.UseSoftFloat) {
351 // SSE has no i16 to fp conversion, only i32
352 if (X86ScalarSSEf32) {
353 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
354 // f32 and f64 cases are Legal, f80 case is not
355 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
357 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
358 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
361 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
362 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
365 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
366 // are Legal, f80 is custom lowered.
367 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
368 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
370 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
372 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
373 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
375 if (X86ScalarSSEf32) {
376 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
377 // f32 and f64 cases are Legal, f80 case is not
378 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
380 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
381 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
384 // Handle FP_TO_UINT by promoting the destination to a larger signed
386 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
387 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
388 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
390 if (Subtarget->is64Bit()) {
391 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
392 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
393 } else if (!TM.Options.UseSoftFloat) {
394 // Since AVX is a superset of SSE3, only check for SSE here.
395 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396 // Expand FP_TO_UINT into a select.
397 // FIXME: We would like to use a Custom expander here eventually to do
398 // the optimal thing for SSE vs. the default expansion in the legalizer.
399 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
401 // With SSE3 we can use fisttpll to convert to a signed i64; without
402 // SSE, we're stuck with a fistpll.
403 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
406 if (isTargetFTOL()) {
407 // Use the _ftol2 runtime function, which has a pseudo-instruction
408 // to handle its weird calling convention.
409 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
412 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413 if (!X86ScalarSSEf64) {
414 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
415 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
416 if (Subtarget->is64Bit()) {
417 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
418 // Without SSE, i64->f64 goes through memory.
419 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
423 // Scalar integer divide and remainder are lowered to use operations that
424 // produce two results, to match the available instructions. This exposes
425 // the two-result form to trivial CSE, which is able to combine x/y and x%y
426 // into a single instruction.
428 // Scalar integer multiply-high is also lowered to use two-result
429 // operations, to match the available instructions. However, plain multiply
430 // (low) operations are left as Legal, as there are single-result
431 // instructions for this in x86. Using the two-result multiply instructions
432 // when both high and low results are needed must be arranged by dagcombine.
433 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
435 setOperationAction(ISD::MULHS, VT, Expand);
436 setOperationAction(ISD::MULHU, VT, Expand);
437 setOperationAction(ISD::SDIV, VT, Expand);
438 setOperationAction(ISD::UDIV, VT, Expand);
439 setOperationAction(ISD::SREM, VT, Expand);
440 setOperationAction(ISD::UREM, VT, Expand);
442 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443 setOperationAction(ISD::ADDC, VT, Custom);
444 setOperationAction(ISD::ADDE, VT, Custom);
445 setOperationAction(ISD::SUBC, VT, Custom);
446 setOperationAction(ISD::SUBE, VT, Custom);
449 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
450 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
451 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
452 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
453 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
454 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
455 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
456 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
457 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
458 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
459 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
460 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
461 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
462 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
463 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
464 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
468 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
469 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
470 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
471 setOperationAction(ISD::FREM , MVT::f32 , Expand);
472 setOperationAction(ISD::FREM , MVT::f64 , Expand);
473 setOperationAction(ISD::FREM , MVT::f80 , Expand);
474 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
476 // Promote the i8 variants and force them on up to i32 which has a shorter
478 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
481 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
482 if (Subtarget->hasBMI()) {
483 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
484 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
485 if (Subtarget->is64Bit())
486 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
488 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
489 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
490 if (Subtarget->is64Bit())
491 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
494 if (Subtarget->hasLZCNT()) {
495 // When promoting the i8 variants, force them to i32 for a shorter
497 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
498 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
499 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
500 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
501 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
502 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
503 if (Subtarget->is64Bit())
504 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
506 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
507 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
508 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
509 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
510 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
511 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
512 if (Subtarget->is64Bit()) {
513 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
514 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
518 // Special handling for half-precision floating point conversions.
519 // If we don't have F16C support, then lower half float conversions
520 // into library calls.
521 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
526 // There's never any support for operations beyond MVT::f32.
527 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
532 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
537 if (Subtarget->hasPOPCNT()) {
538 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
540 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
541 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
542 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
543 if (Subtarget->is64Bit())
544 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
547 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
549 if (!Subtarget->hasMOVBE())
550 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
552 // These should be promoted to a larger select which is supported.
553 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
554 // X86 wants to expand cmov itself.
555 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
556 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
557 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
558 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
559 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
560 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
561 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
562 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
563 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
564 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
565 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
566 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
567 if (Subtarget->is64Bit()) {
568 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
569 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
571 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
572 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574 // support continuation, user-level threading, and etc.. As a result, no
575 // other SjLj exception interfaces are implemented and please don't build
576 // your own exception handling based on them.
577 // LLVM/Clang supports zero-cost DWARF exception handling.
578 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
582 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
583 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
584 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
585 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
586 if (Subtarget->is64Bit())
587 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
589 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
590 if (Subtarget->is64Bit()) {
591 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
592 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
593 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
594 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
595 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
597 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
599 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
600 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
601 if (Subtarget->is64Bit()) {
602 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
603 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
604 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
607 if (Subtarget->hasSSE1())
608 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
610 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
612 // Expand certain atomics
613 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
615 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
620 if (Subtarget->hasCmpxchg16b()) {
621 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
624 // FIXME - use subtarget debug flags
625 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
630 if (Subtarget->is64Bit()) {
631 setExceptionPointerRegister(X86::RAX);
632 setExceptionSelectorRegister(X86::RDX);
634 setExceptionPointerRegister(X86::EAX);
635 setExceptionSelectorRegister(X86::EDX);
637 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
640 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
643 setOperationAction(ISD::TRAP, MVT::Other, Legal);
644 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
646 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647 setOperationAction(ISD::VASTART , MVT::Other, Custom);
648 setOperationAction(ISD::VAEND , MVT::Other, Expand);
649 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650 // TargetInfo::X86_64ABIBuiltinVaList
651 setOperationAction(ISD::VAARG , MVT::Other, Custom);
652 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
654 // TargetInfo::CharPtrBuiltinVaList
655 setOperationAction(ISD::VAARG , MVT::Other, Expand);
656 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
659 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
660 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
662 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
663 MVT::i64 : MVT::i32, Custom);
665 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666 // f32 and f64 use SSE.
667 // Set up the FP register classes.
668 addRegisterClass(MVT::f32, &X86::FR32RegClass);
669 addRegisterClass(MVT::f64, &X86::FR64RegClass);
671 // Use ANDPD to simulate FABS.
672 setOperationAction(ISD::FABS , MVT::f64, Custom);
673 setOperationAction(ISD::FABS , MVT::f32, Custom);
675 // Use XORP to simulate FNEG.
676 setOperationAction(ISD::FNEG , MVT::f64, Custom);
677 setOperationAction(ISD::FNEG , MVT::f32, Custom);
679 // Use ANDPD and ORPD to simulate FCOPYSIGN.
680 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
683 // Lower this to FGETSIGNx86 plus an AND.
684 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
687 // We don't support sin/cos/fmod
688 setOperationAction(ISD::FSIN , MVT::f64, Expand);
689 setOperationAction(ISD::FCOS , MVT::f64, Expand);
690 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691 setOperationAction(ISD::FSIN , MVT::f32, Expand);
692 setOperationAction(ISD::FCOS , MVT::f32, Expand);
693 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
695 // Expand FP immediates into loads from the stack, except for the special
697 addLegalFPImmediate(APFloat(+0.0)); // xorpd
698 addLegalFPImmediate(APFloat(+0.0f)); // xorps
699 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700 // Use SSE for f32, x87 for f64.
701 // Set up the FP register classes.
702 addRegisterClass(MVT::f32, &X86::FR32RegClass);
703 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
705 // Use ANDPS to simulate FABS.
706 setOperationAction(ISD::FABS , MVT::f32, Custom);
708 // Use XORP to simulate FNEG.
709 setOperationAction(ISD::FNEG , MVT::f32, Custom);
711 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
713 // Use ANDPS and ORPS to simulate FCOPYSIGN.
714 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
717 // We don't support sin/cos/fmod
718 setOperationAction(ISD::FSIN , MVT::f32, Expand);
719 setOperationAction(ISD::FCOS , MVT::f32, Expand);
720 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
722 // Special cases we handle for FP constants.
723 addLegalFPImmediate(APFloat(+0.0f)); // xorps
724 addLegalFPImmediate(APFloat(+0.0)); // FLD0
725 addLegalFPImmediate(APFloat(+1.0)); // FLD1
726 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
729 if (!TM.Options.UnsafeFPMath) {
730 setOperationAction(ISD::FSIN , MVT::f64, Expand);
731 setOperationAction(ISD::FCOS , MVT::f64, Expand);
732 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
734 } else if (!TM.Options.UseSoftFloat) {
735 // f32 and f64 in x87.
736 // Set up the FP register classes.
737 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
740 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
741 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
742 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
745 if (!TM.Options.UnsafeFPMath) {
746 setOperationAction(ISD::FSIN , MVT::f64, Expand);
747 setOperationAction(ISD::FSIN , MVT::f32, Expand);
748 setOperationAction(ISD::FCOS , MVT::f64, Expand);
749 setOperationAction(ISD::FCOS , MVT::f32, Expand);
750 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
753 addLegalFPImmediate(APFloat(+0.0)); // FLD0
754 addLegalFPImmediate(APFloat(+1.0)); // FLD1
755 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
763 // We don't support FMA.
764 setOperationAction(ISD::FMA, MVT::f64, Expand);
765 setOperationAction(ISD::FMA, MVT::f32, Expand);
767 // Long double always uses X87.
768 if (!TM.Options.UseSoftFloat) {
769 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
771 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
773 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774 addLegalFPImmediate(TmpFlt); // FLD0
776 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
779 APFloat TmpFlt2(+1.0);
780 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
782 addLegalFPImmediate(TmpFlt2); // FLD1
783 TmpFlt2.changeSign();
784 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
787 if (!TM.Options.UnsafeFPMath) {
788 setOperationAction(ISD::FSIN , MVT::f80, Expand);
789 setOperationAction(ISD::FCOS , MVT::f80, Expand);
790 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
793 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
795 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796 setOperationAction(ISD::FRINT, MVT::f80, Expand);
797 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798 setOperationAction(ISD::FMA, MVT::f80, Expand);
801 // Always use a library call for pow.
802 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
803 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
804 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
806 setOperationAction(ISD::FLOG, MVT::f80, Expand);
807 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809 setOperationAction(ISD::FEXP, MVT::f80, Expand);
810 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
812 // First set operation action for all vector types to either promote
813 // (for widening) or expand (for scalarization). Then we will selectively
814 // turn on ones that can be effectively codegen'd.
815 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817 MVT VT = (MVT::SimpleValueType)i;
818 setOperationAction(ISD::ADD , VT, Expand);
819 setOperationAction(ISD::SUB , VT, Expand);
820 setOperationAction(ISD::FADD, VT, Expand);
821 setOperationAction(ISD::FNEG, VT, Expand);
822 setOperationAction(ISD::FSUB, VT, Expand);
823 setOperationAction(ISD::MUL , VT, Expand);
824 setOperationAction(ISD::FMUL, VT, Expand);
825 setOperationAction(ISD::SDIV, VT, Expand);
826 setOperationAction(ISD::UDIV, VT, Expand);
827 setOperationAction(ISD::FDIV, VT, Expand);
828 setOperationAction(ISD::SREM, VT, Expand);
829 setOperationAction(ISD::UREM, VT, Expand);
830 setOperationAction(ISD::LOAD, VT, Expand);
831 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836 setOperationAction(ISD::FABS, VT, Expand);
837 setOperationAction(ISD::FSIN, VT, Expand);
838 setOperationAction(ISD::FSINCOS, VT, Expand);
839 setOperationAction(ISD::FCOS, VT, Expand);
840 setOperationAction(ISD::FSINCOS, VT, Expand);
841 setOperationAction(ISD::FREM, VT, Expand);
842 setOperationAction(ISD::FMA, VT, Expand);
843 setOperationAction(ISD::FPOWI, VT, Expand);
844 setOperationAction(ISD::FSQRT, VT, Expand);
845 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846 setOperationAction(ISD::FFLOOR, VT, Expand);
847 setOperationAction(ISD::FCEIL, VT, Expand);
848 setOperationAction(ISD::FTRUNC, VT, Expand);
849 setOperationAction(ISD::FRINT, VT, Expand);
850 setOperationAction(ISD::FNEARBYINT, VT, Expand);
851 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852 setOperationAction(ISD::MULHS, VT, Expand);
853 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854 setOperationAction(ISD::MULHU, VT, Expand);
855 setOperationAction(ISD::SDIVREM, VT, Expand);
856 setOperationAction(ISD::UDIVREM, VT, Expand);
857 setOperationAction(ISD::FPOW, VT, Expand);
858 setOperationAction(ISD::CTPOP, VT, Expand);
859 setOperationAction(ISD::CTTZ, VT, Expand);
860 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861 setOperationAction(ISD::CTLZ, VT, Expand);
862 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863 setOperationAction(ISD::SHL, VT, Expand);
864 setOperationAction(ISD::SRA, VT, Expand);
865 setOperationAction(ISD::SRL, VT, Expand);
866 setOperationAction(ISD::ROTL, VT, Expand);
867 setOperationAction(ISD::ROTR, VT, Expand);
868 setOperationAction(ISD::BSWAP, VT, Expand);
869 setOperationAction(ISD::SETCC, VT, Expand);
870 setOperationAction(ISD::FLOG, VT, Expand);
871 setOperationAction(ISD::FLOG2, VT, Expand);
872 setOperationAction(ISD::FLOG10, VT, Expand);
873 setOperationAction(ISD::FEXP, VT, Expand);
874 setOperationAction(ISD::FEXP2, VT, Expand);
875 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880 setOperationAction(ISD::TRUNCATE, VT, Expand);
881 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884 setOperationAction(ISD::VSELECT, VT, Expand);
885 setOperationAction(ISD::SELECT_CC, VT, Expand);
886 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888 setTruncStoreAction(VT,
889 (MVT::SimpleValueType)InnerVT, Expand);
890 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
893 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894 // we have to deal with them whether we ask for Expansion or not. Setting
895 // Expand causes its own optimisation problems though, so leave them legal.
896 if (VT.getVectorElementType() == MVT::i1)
897 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
900 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901 // with -msoft-float, disable use of MMX as well.
902 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904 // No operations on x86mmx supported, everything uses intrinsics.
907 // MMX-sized vectors (other than x86mmx) are expected to be expanded
908 // into smaller operations.
909 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
910 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
911 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
912 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
913 setOperationAction(ISD::AND, MVT::v8i8, Expand);
914 setOperationAction(ISD::AND, MVT::v4i16, Expand);
915 setOperationAction(ISD::AND, MVT::v2i32, Expand);
916 setOperationAction(ISD::AND, MVT::v1i64, Expand);
917 setOperationAction(ISD::OR, MVT::v8i8, Expand);
918 setOperationAction(ISD::OR, MVT::v4i16, Expand);
919 setOperationAction(ISD::OR, MVT::v2i32, Expand);
920 setOperationAction(ISD::OR, MVT::v1i64, Expand);
921 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
922 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
923 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
924 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
925 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
926 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
927 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
928 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
929 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
930 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
931 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
932 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
933 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
934 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
935 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
936 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
937 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
939 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
942 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
943 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
944 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
945 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
946 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
947 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
948 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
949 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
950 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
951 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
952 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
956 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
959 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
960 // registers cannot be used even for integer operations.
961 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
966 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
967 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
968 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
969 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
970 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
971 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
972 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
973 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
974 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
975 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
976 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
977 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
978 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
979 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
980 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
981 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
982 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
983 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
984 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
985 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
986 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
987 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
989 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
990 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
991 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
992 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
994 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
995 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
998 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1000 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002 MVT VT = (MVT::SimpleValueType)i;
1003 // Do not attempt to custom lower non-power-of-2 vectors
1004 if (!isPowerOf2_32(VT.getVectorNumElements()))
1006 // Do not attempt to custom lower non-128-bit vectors
1007 if (!VT.is128BitVector())
1009 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1010 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1014 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1015 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1016 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1017 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1018 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1019 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1021 if (Subtarget->is64Bit()) {
1022 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1023 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1026 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1027 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1028 MVT VT = (MVT::SimpleValueType)i;
1030 // Do not attempt to promote non-128-bit vectors
1031 if (!VT.is128BitVector())
1034 setOperationAction(ISD::AND, VT, Promote);
1035 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1036 setOperationAction(ISD::OR, VT, Promote);
1037 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1038 setOperationAction(ISD::XOR, VT, Promote);
1039 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1040 setOperationAction(ISD::LOAD, VT, Promote);
1041 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1042 setOperationAction(ISD::SELECT, VT, Promote);
1043 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1046 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1048 // Custom lower v2i64 and v2f64 selects.
1049 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1050 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1051 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1052 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1054 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1055 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1057 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1058 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1059 // As there is no 64-bit GPR available, we need build a special custom
1060 // sequence to convert from v2i32 to v2f32.
1061 if (!Subtarget->is64Bit())
1062 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1064 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1065 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1067 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1069 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1070 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1071 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1074 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1075 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1076 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1077 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1078 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1079 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1080 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1081 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1082 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1083 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1084 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1086 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1087 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1088 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1089 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1090 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1091 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1092 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1093 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1094 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1095 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1097 // FIXME: Do we need to handle scalar-to-vector here?
1098 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1100 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1101 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1102 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1103 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1104 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1105 // There is no BLENDI for byte vectors. We don't need to custom lower
1106 // some vselects for now.
1107 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1109 // i8 and i16 vectors are custom , because the source register and source
1110 // source memory operand types are not the same width. f32 vectors are
1111 // custom since the immediate controlling the insert encodes additional
1113 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1114 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1115 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1116 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1118 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1119 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1120 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1121 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1123 // FIXME: these should be Legal but thats only for the case where
1124 // the index is constant. For now custom expand to deal with that.
1125 if (Subtarget->is64Bit()) {
1126 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1127 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1131 if (Subtarget->hasSSE2()) {
1132 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1133 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1135 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1136 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1138 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1139 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1141 // In the customized shift lowering, the legal cases in AVX2 will be
1143 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1144 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1146 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1147 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1149 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1152 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1153 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1154 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1155 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1156 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1157 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1158 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1160 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1161 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1162 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1164 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1165 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1166 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1167 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1168 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1169 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1170 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1171 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1172 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1173 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1174 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1175 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1177 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1178 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1179 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1180 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1181 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1182 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1183 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1184 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1185 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1186 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1187 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1188 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1190 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1191 // even though v8i16 is a legal type.
1192 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1193 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1194 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1196 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1197 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1198 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1200 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1201 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1203 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1205 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1206 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1208 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1209 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1211 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1212 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1214 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1215 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1216 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1217 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1219 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1220 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1221 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1223 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1224 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1225 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1226 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1228 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1229 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1230 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1231 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1232 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1233 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1234 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1235 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1236 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1237 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1238 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1239 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1241 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1242 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1243 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1244 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1245 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1246 setOperationAction(ISD::FMA, MVT::f32, Legal);
1247 setOperationAction(ISD::FMA, MVT::f64, Legal);
1250 if (Subtarget->hasInt256()) {
1251 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1252 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1253 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1254 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1256 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1257 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1258 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1259 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1261 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1262 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1263 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1264 // Don't lower v32i8 because there is no 128-bit byte mul
1266 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1267 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1268 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1269 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1271 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1272 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1274 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1275 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1276 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1277 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1279 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1280 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1281 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1282 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1284 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1285 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1286 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1287 // Don't lower v32i8 because there is no 128-bit byte mul
1290 // In the customized shift lowering, the legal cases in AVX2 will be
1292 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1293 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1295 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1296 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1298 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1300 // Custom lower several nodes for 256-bit types.
1301 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1302 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1303 MVT VT = (MVT::SimpleValueType)i;
1305 // Extract subvector is special because the value type
1306 // (result) is 128-bit but the source is 256-bit wide.
1307 if (VT.is128BitVector())
1308 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1310 // Do not attempt to custom lower other non-256-bit vectors
1311 if (!VT.is256BitVector())
1314 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1315 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1316 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1317 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1318 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1319 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1320 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1323 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1324 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1325 MVT VT = (MVT::SimpleValueType)i;
1327 // Do not attempt to promote non-256-bit vectors
1328 if (!VT.is256BitVector())
1331 setOperationAction(ISD::AND, VT, Promote);
1332 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1333 setOperationAction(ISD::OR, VT, Promote);
1334 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1335 setOperationAction(ISD::XOR, VT, Promote);
1336 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1337 setOperationAction(ISD::LOAD, VT, Promote);
1338 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1339 setOperationAction(ISD::SELECT, VT, Promote);
1340 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1344 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1345 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1346 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1347 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1348 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1350 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1351 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1352 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1354 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1355 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1356 setOperationAction(ISD::XOR, MVT::i1, Legal);
1357 setOperationAction(ISD::OR, MVT::i1, Legal);
1358 setOperationAction(ISD::AND, MVT::i1, Legal);
1359 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1360 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1361 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1362 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1363 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1364 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1366 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1367 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1368 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1369 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1370 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1371 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1373 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1374 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1375 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1376 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1377 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1378 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1379 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1380 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1382 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1383 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1384 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1385 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1386 if (Subtarget->is64Bit()) {
1387 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1388 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1389 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1390 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1392 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1393 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1394 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1395 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1396 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1397 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1398 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1399 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1400 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1401 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1403 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1404 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1405 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1406 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1407 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1408 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1409 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1410 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1411 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1412 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1413 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1414 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1415 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1417 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1418 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1419 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1420 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1421 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1422 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1424 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1425 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1427 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1429 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1430 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1431 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1432 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1433 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1434 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1435 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1436 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1437 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1439 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1440 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1442 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1443 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1445 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1447 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1448 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1450 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1451 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1453 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1454 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1456 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1457 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1458 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1459 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1460 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1461 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1463 if (Subtarget->hasCDI()) {
1464 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1465 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1468 // Custom lower several nodes.
1469 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1470 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1471 MVT VT = (MVT::SimpleValueType)i;
1473 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1474 // Extract subvector is special because the value type
1475 // (result) is 256/128-bit but the source is 512-bit wide.
1476 if (VT.is128BitVector() || VT.is256BitVector())
1477 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1479 if (VT.getVectorElementType() == MVT::i1)
1480 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1482 // Do not attempt to custom lower other non-512-bit vectors
1483 if (!VT.is512BitVector())
1486 if ( EltSize >= 32) {
1487 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1488 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1489 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1490 setOperationAction(ISD::VSELECT, VT, Legal);
1491 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1492 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1493 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1496 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1497 MVT VT = (MVT::SimpleValueType)i;
1499 // Do not attempt to promote non-256-bit vectors
1500 if (!VT.is512BitVector())
1503 setOperationAction(ISD::SELECT, VT, Promote);
1504 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1508 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1509 // of this type with custom code.
1510 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1511 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1512 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1516 // We want to custom lower some of our intrinsics.
1517 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1518 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1519 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1520 if (!Subtarget->is64Bit())
1521 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1523 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1524 // handle type legalization for these operations here.
1526 // FIXME: We really should do custom legalization for addition and
1527 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1528 // than generic legalization for 64-bit multiplication-with-overflow, though.
1529 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1530 // Add/Sub/Mul with overflow operations are custom lowered.
1532 setOperationAction(ISD::SADDO, VT, Custom);
1533 setOperationAction(ISD::UADDO, VT, Custom);
1534 setOperationAction(ISD::SSUBO, VT, Custom);
1535 setOperationAction(ISD::USUBO, VT, Custom);
1536 setOperationAction(ISD::SMULO, VT, Custom);
1537 setOperationAction(ISD::UMULO, VT, Custom);
1540 // There are no 8-bit 3-address imul/mul instructions
1541 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1542 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1544 if (!Subtarget->is64Bit()) {
1545 // These libcalls are not available in 32-bit.
1546 setLibcallName(RTLIB::SHL_I128, nullptr);
1547 setLibcallName(RTLIB::SRL_I128, nullptr);
1548 setLibcallName(RTLIB::SRA_I128, nullptr);
1551 // Combine sin / cos into one node or libcall if possible.
1552 if (Subtarget->hasSinCos()) {
1553 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1554 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1555 if (Subtarget->isTargetDarwin()) {
1556 // For MacOSX, we don't want to the normal expansion of a libcall to
1557 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1559 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1560 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1564 if (Subtarget->isTargetWin64()) {
1565 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1566 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1567 setOperationAction(ISD::SREM, MVT::i128, Custom);
1568 setOperationAction(ISD::UREM, MVT::i128, Custom);
1569 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1570 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1573 // We have target-specific dag combine patterns for the following nodes:
1574 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1575 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1576 setTargetDAGCombine(ISD::VSELECT);
1577 setTargetDAGCombine(ISD::SELECT);
1578 setTargetDAGCombine(ISD::SHL);
1579 setTargetDAGCombine(ISD::SRA);
1580 setTargetDAGCombine(ISD::SRL);
1581 setTargetDAGCombine(ISD::OR);
1582 setTargetDAGCombine(ISD::AND);
1583 setTargetDAGCombine(ISD::ADD);
1584 setTargetDAGCombine(ISD::FADD);
1585 setTargetDAGCombine(ISD::FSUB);
1586 setTargetDAGCombine(ISD::FMA);
1587 setTargetDAGCombine(ISD::SUB);
1588 setTargetDAGCombine(ISD::LOAD);
1589 setTargetDAGCombine(ISD::STORE);
1590 setTargetDAGCombine(ISD::ZERO_EXTEND);
1591 setTargetDAGCombine(ISD::ANY_EXTEND);
1592 setTargetDAGCombine(ISD::SIGN_EXTEND);
1593 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1594 setTargetDAGCombine(ISD::TRUNCATE);
1595 setTargetDAGCombine(ISD::SINT_TO_FP);
1596 setTargetDAGCombine(ISD::SETCC);
1597 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1598 setTargetDAGCombine(ISD::BUILD_VECTOR);
1599 if (Subtarget->is64Bit())
1600 setTargetDAGCombine(ISD::MUL);
1601 setTargetDAGCombine(ISD::XOR);
1603 computeRegisterProperties();
1605 // On Darwin, -Os means optimize for size without hurting performance,
1606 // do not reduce the limit.
1607 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1608 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1609 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1610 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1611 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1612 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1613 setPrefLoopAlignment(4); // 2^4 bytes.
1615 // Predictable cmov don't hurt on atom because it's in-order.
1616 PredictableSelectIsExpensive = !Subtarget->isAtom();
1618 setPrefFunctionAlignment(4); // 2^4 bytes.
1621 TargetLoweringBase::LegalizeTypeAction
1622 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1623 if (ExperimentalVectorWideningLegalization &&
1624 VT.getVectorNumElements() != 1 &&
1625 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1626 return TypeWidenVector;
1628 return TargetLoweringBase::getPreferredVectorAction(VT);
1631 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1633 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1635 if (Subtarget->hasAVX512())
1636 switch(VT.getVectorNumElements()) {
1637 case 8: return MVT::v8i1;
1638 case 16: return MVT::v16i1;
1641 return VT.changeVectorElementTypeToInteger();
1644 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1645 /// the desired ByVal argument alignment.
1646 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1649 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1650 if (VTy->getBitWidth() == 128)
1652 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1653 unsigned EltAlign = 0;
1654 getMaxByValAlign(ATy->getElementType(), EltAlign);
1655 if (EltAlign > MaxAlign)
1656 MaxAlign = EltAlign;
1657 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1658 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1659 unsigned EltAlign = 0;
1660 getMaxByValAlign(STy->getElementType(i), EltAlign);
1661 if (EltAlign > MaxAlign)
1662 MaxAlign = EltAlign;
1669 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1670 /// function arguments in the caller parameter area. For X86, aggregates
1671 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1672 /// are at 4-byte boundaries.
1673 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1674 if (Subtarget->is64Bit()) {
1675 // Max of 8 and alignment of type.
1676 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1683 if (Subtarget->hasSSE1())
1684 getMaxByValAlign(Ty, Align);
1688 /// getOptimalMemOpType - Returns the target specific optimal type for load
1689 /// and store operations as a result of memset, memcpy, and memmove
1690 /// lowering. If DstAlign is zero that means it's safe to destination
1691 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1692 /// means there isn't a need to check it against alignment requirement,
1693 /// probably because the source does not need to be loaded. If 'IsMemset' is
1694 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1695 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1696 /// source is constant so it does not need to be loaded.
1697 /// It returns EVT::Other if the type should be determined using generic
1698 /// target-independent logic.
1700 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1701 unsigned DstAlign, unsigned SrcAlign,
1702 bool IsMemset, bool ZeroMemset,
1704 MachineFunction &MF) const {
1705 const Function *F = MF.getFunction();
1706 if ((!IsMemset || ZeroMemset) &&
1707 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1708 Attribute::NoImplicitFloat)) {
1710 (Subtarget->isUnalignedMemAccessFast() ||
1711 ((DstAlign == 0 || DstAlign >= 16) &&
1712 (SrcAlign == 0 || SrcAlign >= 16)))) {
1714 if (Subtarget->hasInt256())
1716 if (Subtarget->hasFp256())
1719 if (Subtarget->hasSSE2())
1721 if (Subtarget->hasSSE1())
1723 } else if (!MemcpyStrSrc && Size >= 8 &&
1724 !Subtarget->is64Bit() &&
1725 Subtarget->hasSSE2()) {
1726 // Do not use f64 to lower memcpy if source is string constant. It's
1727 // better to use i32 to avoid the loads.
1731 if (Subtarget->is64Bit() && Size >= 8)
1736 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1738 return X86ScalarSSEf32;
1739 else if (VT == MVT::f64)
1740 return X86ScalarSSEf64;
1745 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1749 *Fast = Subtarget->isUnalignedMemAccessFast();
1753 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1754 /// current function. The returned value is a member of the
1755 /// MachineJumpTableInfo::JTEntryKind enum.
1756 unsigned X86TargetLowering::getJumpTableEncoding() const {
1757 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1759 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1760 Subtarget->isPICStyleGOT())
1761 return MachineJumpTableInfo::EK_Custom32;
1763 // Otherwise, use the normal jump table encoding heuristics.
1764 return TargetLowering::getJumpTableEncoding();
1768 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1769 const MachineBasicBlock *MBB,
1770 unsigned uid,MCContext &Ctx) const{
1771 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1772 Subtarget->isPICStyleGOT());
1773 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1775 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1776 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1779 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1781 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1782 SelectionDAG &DAG) const {
1783 if (!Subtarget->is64Bit())
1784 // This doesn't have SDLoc associated with it, but is not really the
1785 // same as a Register.
1786 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1790 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1791 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1793 const MCExpr *X86TargetLowering::
1794 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1795 MCContext &Ctx) const {
1796 // X86-64 uses RIP relative addressing based on the jump table label.
1797 if (Subtarget->isPICStyleRIPRel())
1798 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1800 // Otherwise, the reference is relative to the PIC base.
1801 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1804 // FIXME: Why this routine is here? Move to RegInfo!
1805 std::pair<const TargetRegisterClass*, uint8_t>
1806 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1807 const TargetRegisterClass *RRC = nullptr;
1809 switch (VT.SimpleTy) {
1811 return TargetLowering::findRepresentativeClass(VT);
1812 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1813 RRC = Subtarget->is64Bit() ?
1814 (const TargetRegisterClass*)&X86::GR64RegClass :
1815 (const TargetRegisterClass*)&X86::GR32RegClass;
1818 RRC = &X86::VR64RegClass;
1820 case MVT::f32: case MVT::f64:
1821 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1822 case MVT::v4f32: case MVT::v2f64:
1823 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1825 RRC = &X86::VR128RegClass;
1828 return std::make_pair(RRC, Cost);
1831 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1832 unsigned &Offset) const {
1833 if (!Subtarget->isTargetLinux())
1836 if (Subtarget->is64Bit()) {
1837 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1839 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1851 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1852 unsigned DestAS) const {
1853 assert(SrcAS != DestAS && "Expected different address spaces!");
1855 return SrcAS < 256 && DestAS < 256;
1858 //===----------------------------------------------------------------------===//
1859 // Return Value Calling Convention Implementation
1860 //===----------------------------------------------------------------------===//
1862 #include "X86GenCallingConv.inc"
1865 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1866 MachineFunction &MF, bool isVarArg,
1867 const SmallVectorImpl<ISD::OutputArg> &Outs,
1868 LLVMContext &Context) const {
1869 SmallVector<CCValAssign, 16> RVLocs;
1870 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1872 return CCInfo.CheckReturn(Outs, RetCC_X86);
1875 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1876 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1881 X86TargetLowering::LowerReturn(SDValue Chain,
1882 CallingConv::ID CallConv, bool isVarArg,
1883 const SmallVectorImpl<ISD::OutputArg> &Outs,
1884 const SmallVectorImpl<SDValue> &OutVals,
1885 SDLoc dl, SelectionDAG &DAG) const {
1886 MachineFunction &MF = DAG.getMachineFunction();
1887 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1889 SmallVector<CCValAssign, 16> RVLocs;
1890 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1891 RVLocs, *DAG.getContext());
1892 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1895 SmallVector<SDValue, 6> RetOps;
1896 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1897 // Operand #1 = Bytes To Pop
1898 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1901 // Copy the result values into the output registers.
1902 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1903 CCValAssign &VA = RVLocs[i];
1904 assert(VA.isRegLoc() && "Can only return in registers!");
1905 SDValue ValToCopy = OutVals[i];
1906 EVT ValVT = ValToCopy.getValueType();
1908 // Promote values to the appropriate types
1909 if (VA.getLocInfo() == CCValAssign::SExt)
1910 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1911 else if (VA.getLocInfo() == CCValAssign::ZExt)
1912 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1913 else if (VA.getLocInfo() == CCValAssign::AExt)
1914 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1915 else if (VA.getLocInfo() == CCValAssign::BCvt)
1916 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1918 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1919 "Unexpected FP-extend for return value.");
1921 // If this is x86-64, and we disabled SSE, we can't return FP values,
1922 // or SSE or MMX vectors.
1923 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1924 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1925 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1926 report_fatal_error("SSE register return with SSE disabled");
1928 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1929 // llvm-gcc has never done it right and no one has noticed, so this
1930 // should be OK for now.
1931 if (ValVT == MVT::f64 &&
1932 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1933 report_fatal_error("SSE2 register return with SSE2 disabled");
1935 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1936 // the RET instruction and handled by the FP Stackifier.
1937 if (VA.getLocReg() == X86::ST0 ||
1938 VA.getLocReg() == X86::ST1) {
1939 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1940 // change the value to the FP stack register class.
1941 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1942 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1943 RetOps.push_back(ValToCopy);
1944 // Don't emit a copytoreg.
1948 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1949 // which is returned in RAX / RDX.
1950 if (Subtarget->is64Bit()) {
1951 if (ValVT == MVT::x86mmx) {
1952 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1953 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1954 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1956 // If we don't have SSE2 available, convert to v4f32 so the generated
1957 // register is legal.
1958 if (!Subtarget->hasSSE2())
1959 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1964 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1965 Flag = Chain.getValue(1);
1966 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1969 // The x86-64 ABIs require that for returning structs by value we copy
1970 // the sret argument into %rax/%eax (depending on ABI) for the return.
1971 // Win32 requires us to put the sret argument to %eax as well.
1972 // We saved the argument into a virtual register in the entry block,
1973 // so now we copy the value out and into %rax/%eax.
1974 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1975 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1976 MachineFunction &MF = DAG.getMachineFunction();
1977 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1978 unsigned Reg = FuncInfo->getSRetReturnReg();
1980 "SRetReturnReg should have been set in LowerFormalArguments().");
1981 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1984 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1985 X86::RAX : X86::EAX;
1986 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1987 Flag = Chain.getValue(1);
1989 // RAX/EAX now acts like a return value.
1990 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1993 RetOps[0] = Chain; // Update chain.
1995 // Add the flag if we have it.
1997 RetOps.push_back(Flag);
1999 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2002 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2003 if (N->getNumValues() != 1)
2005 if (!N->hasNUsesOfValue(1, 0))
2008 SDValue TCChain = Chain;
2009 SDNode *Copy = *N->use_begin();
2010 if (Copy->getOpcode() == ISD::CopyToReg) {
2011 // If the copy has a glue operand, we conservatively assume it isn't safe to
2012 // perform a tail call.
2013 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2015 TCChain = Copy->getOperand(0);
2016 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2019 bool HasRet = false;
2020 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2022 if (UI->getOpcode() != X86ISD::RET_FLAG)
2035 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2036 ISD::NodeType ExtendKind) const {
2038 // TODO: Is this also valid on 32-bit?
2039 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2040 ReturnMVT = MVT::i8;
2042 ReturnMVT = MVT::i32;
2044 MVT MinVT = getRegisterType(ReturnMVT);
2045 return VT.bitsLT(MinVT) ? MinVT : VT;
2048 /// LowerCallResult - Lower the result values of a call into the
2049 /// appropriate copies out of appropriate physical registers.
2052 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2053 CallingConv::ID CallConv, bool isVarArg,
2054 const SmallVectorImpl<ISD::InputArg> &Ins,
2055 SDLoc dl, SelectionDAG &DAG,
2056 SmallVectorImpl<SDValue> &InVals) const {
2058 // Assign locations to each value returned by this call.
2059 SmallVector<CCValAssign, 16> RVLocs;
2060 bool Is64Bit = Subtarget->is64Bit();
2061 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2062 DAG.getTarget(), RVLocs, *DAG.getContext());
2063 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2065 // Copy all of the result registers out of their specified physreg.
2066 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2067 CCValAssign &VA = RVLocs[i];
2068 EVT CopyVT = VA.getValVT();
2070 // If this is x86-64, and we disabled SSE, we can't return FP values
2071 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2072 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2073 report_fatal_error("SSE register return with SSE disabled");
2078 // If this is a call to a function that returns an fp value on the floating
2079 // point stack, we must guarantee the value is popped from the stack, so
2080 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2081 // if the return value is not used. We use the FpPOP_RETVAL instruction
2083 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2084 // If we prefer to use the value in xmm registers, copy it out as f80 and
2085 // use a truncate to move it from fp stack reg to xmm reg.
2086 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2087 SDValue Ops[] = { Chain, InFlag };
2088 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2089 MVT::Other, MVT::Glue, Ops), 1);
2090 Val = Chain.getValue(0);
2092 // Round the f80 to the right size, which also moves it to the appropriate
2094 if (CopyVT != VA.getValVT())
2095 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2096 // This truncation won't change the value.
2097 DAG.getIntPtrConstant(1));
2099 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2100 CopyVT, InFlag).getValue(1);
2101 Val = Chain.getValue(0);
2103 InFlag = Chain.getValue(2);
2104 InVals.push_back(Val);
2110 //===----------------------------------------------------------------------===//
2111 // C & StdCall & Fast Calling Convention implementation
2112 //===----------------------------------------------------------------------===//
2113 // StdCall calling convention seems to be standard for many Windows' API
2114 // routines and around. It differs from C calling convention just a little:
2115 // callee should clean up the stack, not caller. Symbols should be also
2116 // decorated in some fancy way :) It doesn't support any vector arguments.
2117 // For info on fast calling convention see Fast Calling Convention (tail call)
2118 // implementation LowerX86_32FastCCCallTo.
2120 /// CallIsStructReturn - Determines whether a call uses struct return
2122 enum StructReturnType {
2127 static StructReturnType
2128 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2130 return NotStructReturn;
2132 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2133 if (!Flags.isSRet())
2134 return NotStructReturn;
2135 if (Flags.isInReg())
2136 return RegStructReturn;
2137 return StackStructReturn;
2140 /// ArgsAreStructReturn - Determines whether a function uses struct
2141 /// return semantics.
2142 static StructReturnType
2143 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2145 return NotStructReturn;
2147 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2148 if (!Flags.isSRet())
2149 return NotStructReturn;
2150 if (Flags.isInReg())
2151 return RegStructReturn;
2152 return StackStructReturn;
2155 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2156 /// by "Src" to address "Dst" with size and alignment information specified by
2157 /// the specific parameter attribute. The copy will be passed as a byval
2158 /// function parameter.
2160 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2161 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2163 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2165 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2166 /*isVolatile*/false, /*AlwaysInline=*/true,
2167 MachinePointerInfo(), MachinePointerInfo());
2170 /// IsTailCallConvention - Return true if the calling convention is one that
2171 /// supports tail call optimization.
2172 static bool IsTailCallConvention(CallingConv::ID CC) {
2173 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2174 CC == CallingConv::HiPE);
2177 /// \brief Return true if the calling convention is a C calling convention.
2178 static bool IsCCallConvention(CallingConv::ID CC) {
2179 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2180 CC == CallingConv::X86_64_SysV);
2183 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2184 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2188 CallingConv::ID CalleeCC = CS.getCallingConv();
2189 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2195 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2196 /// a tailcall target by changing its ABI.
2197 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2198 bool GuaranteedTailCallOpt) {
2199 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2203 X86TargetLowering::LowerMemArgument(SDValue Chain,
2204 CallingConv::ID CallConv,
2205 const SmallVectorImpl<ISD::InputArg> &Ins,
2206 SDLoc dl, SelectionDAG &DAG,
2207 const CCValAssign &VA,
2208 MachineFrameInfo *MFI,
2210 // Create the nodes corresponding to a load from this parameter slot.
2211 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2212 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2213 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2214 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2217 // If value is passed by pointer we have address passed instead of the value
2219 if (VA.getLocInfo() == CCValAssign::Indirect)
2220 ValVT = VA.getLocVT();
2222 ValVT = VA.getValVT();
2224 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2225 // changed with more analysis.
2226 // In case of tail call optimization mark all arguments mutable. Since they
2227 // could be overwritten by lowering of arguments in case of a tail call.
2228 if (Flags.isByVal()) {
2229 unsigned Bytes = Flags.getByValSize();
2230 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2231 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2232 return DAG.getFrameIndex(FI, getPointerTy());
2234 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2235 VA.getLocMemOffset(), isImmutable);
2236 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2237 return DAG.getLoad(ValVT, dl, Chain, FIN,
2238 MachinePointerInfo::getFixedStack(FI),
2239 false, false, false, 0);
2244 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2245 CallingConv::ID CallConv,
2247 const SmallVectorImpl<ISD::InputArg> &Ins,
2250 SmallVectorImpl<SDValue> &InVals)
2252 MachineFunction &MF = DAG.getMachineFunction();
2253 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2255 const Function* Fn = MF.getFunction();
2256 if (Fn->hasExternalLinkage() &&
2257 Subtarget->isTargetCygMing() &&
2258 Fn->getName() == "main")
2259 FuncInfo->setForceFramePointer(true);
2261 MachineFrameInfo *MFI = MF.getFrameInfo();
2262 bool Is64Bit = Subtarget->is64Bit();
2263 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2265 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2266 "Var args not supported with calling convention fastcc, ghc or hipe");
2268 // Assign locations to all of the incoming arguments.
2269 SmallVector<CCValAssign, 16> ArgLocs;
2270 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2271 ArgLocs, *DAG.getContext());
2273 // Allocate shadow area for Win64
2275 CCInfo.AllocateStack(32, 8);
2277 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2279 unsigned LastVal = ~0U;
2281 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2282 CCValAssign &VA = ArgLocs[i];
2283 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2285 assert(VA.getValNo() != LastVal &&
2286 "Don't support value assigned to multiple locs yet");
2288 LastVal = VA.getValNo();
2290 if (VA.isRegLoc()) {
2291 EVT RegVT = VA.getLocVT();
2292 const TargetRegisterClass *RC;
2293 if (RegVT == MVT::i32)
2294 RC = &X86::GR32RegClass;
2295 else if (Is64Bit && RegVT == MVT::i64)
2296 RC = &X86::GR64RegClass;
2297 else if (RegVT == MVT::f32)
2298 RC = &X86::FR32RegClass;
2299 else if (RegVT == MVT::f64)
2300 RC = &X86::FR64RegClass;
2301 else if (RegVT.is512BitVector())
2302 RC = &X86::VR512RegClass;
2303 else if (RegVT.is256BitVector())
2304 RC = &X86::VR256RegClass;
2305 else if (RegVT.is128BitVector())
2306 RC = &X86::VR128RegClass;
2307 else if (RegVT == MVT::x86mmx)
2308 RC = &X86::VR64RegClass;
2309 else if (RegVT == MVT::i1)
2310 RC = &X86::VK1RegClass;
2311 else if (RegVT == MVT::v8i1)
2312 RC = &X86::VK8RegClass;
2313 else if (RegVT == MVT::v16i1)
2314 RC = &X86::VK16RegClass;
2316 llvm_unreachable("Unknown argument type!");
2318 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2319 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2321 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2322 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2324 if (VA.getLocInfo() == CCValAssign::SExt)
2325 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2326 DAG.getValueType(VA.getValVT()));
2327 else if (VA.getLocInfo() == CCValAssign::ZExt)
2328 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2329 DAG.getValueType(VA.getValVT()));
2330 else if (VA.getLocInfo() == CCValAssign::BCvt)
2331 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2333 if (VA.isExtInLoc()) {
2334 // Handle MMX values passed in XMM regs.
2335 if (RegVT.isVector())
2336 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2338 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2341 assert(VA.isMemLoc());
2342 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2345 // If value is passed via pointer - do a load.
2346 if (VA.getLocInfo() == CCValAssign::Indirect)
2347 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2348 MachinePointerInfo(), false, false, false, 0);
2350 InVals.push_back(ArgValue);
2353 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2354 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2355 // The x86-64 ABIs require that for returning structs by value we copy
2356 // the sret argument into %rax/%eax (depending on ABI) for the return.
2357 // Win32 requires us to put the sret argument to %eax as well.
2358 // Save the argument into a virtual register so that we can access it
2359 // from the return points.
2360 if (Ins[i].Flags.isSRet()) {
2361 unsigned Reg = FuncInfo->getSRetReturnReg();
2363 MVT PtrTy = getPointerTy();
2364 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2365 FuncInfo->setSRetReturnReg(Reg);
2367 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2368 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2374 unsigned StackSize = CCInfo.getNextStackOffset();
2375 // Align stack specially for tail calls.
2376 if (FuncIsMadeTailCallSafe(CallConv,
2377 MF.getTarget().Options.GuaranteedTailCallOpt))
2378 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2380 // If the function takes variable number of arguments, make a frame index for
2381 // the start of the first vararg value... for expansion of llvm.va_start.
2383 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2384 CallConv != CallingConv::X86_ThisCall)) {
2385 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2388 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2390 // FIXME: We should really autogenerate these arrays
2391 static const MCPhysReg GPR64ArgRegsWin64[] = {
2392 X86::RCX, X86::RDX, X86::R8, X86::R9
2394 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2395 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2397 static const MCPhysReg XMMArgRegs64Bit[] = {
2398 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2399 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2401 const MCPhysReg *GPR64ArgRegs;
2402 unsigned NumXMMRegs = 0;
2405 // The XMM registers which might contain var arg parameters are shadowed
2406 // in their paired GPR. So we only need to save the GPR to their home
2408 TotalNumIntRegs = 4;
2409 GPR64ArgRegs = GPR64ArgRegsWin64;
2411 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2412 GPR64ArgRegs = GPR64ArgRegs64Bit;
2414 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2417 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2420 bool NoImplicitFloatOps = Fn->getAttributes().
2421 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2422 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2423 "SSE register cannot be used when SSE is disabled!");
2424 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2425 NoImplicitFloatOps) &&
2426 "SSE register cannot be used when SSE is disabled!");
2427 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2428 !Subtarget->hasSSE1())
2429 // Kernel mode asks for SSE to be disabled, so don't push them
2431 TotalNumXMMRegs = 0;
2434 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2435 // Get to the caller-allocated home save location. Add 8 to account
2436 // for the return address.
2437 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2438 FuncInfo->setRegSaveFrameIndex(
2439 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2440 // Fixup to set vararg frame on shadow area (4 x i64).
2442 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2444 // For X86-64, if there are vararg parameters that are passed via
2445 // registers, then we must store them to their spots on the stack so
2446 // they may be loaded by deferencing the result of va_next.
2447 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2448 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2449 FuncInfo->setRegSaveFrameIndex(
2450 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2454 // Store the integer parameter registers.
2455 SmallVector<SDValue, 8> MemOps;
2456 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2458 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2459 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2460 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2461 DAG.getIntPtrConstant(Offset));
2462 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2463 &X86::GR64RegClass);
2464 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2466 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2467 MachinePointerInfo::getFixedStack(
2468 FuncInfo->getRegSaveFrameIndex(), Offset),
2470 MemOps.push_back(Store);
2474 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2475 // Now store the XMM (fp + vector) parameter registers.
2476 SmallVector<SDValue, 11> SaveXMMOps;
2477 SaveXMMOps.push_back(Chain);
2479 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2480 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2481 SaveXMMOps.push_back(ALVal);
2483 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2484 FuncInfo->getRegSaveFrameIndex()));
2485 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2486 FuncInfo->getVarArgsFPOffset()));
2488 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2489 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2490 &X86::VR128RegClass);
2491 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2492 SaveXMMOps.push_back(Val);
2494 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2495 MVT::Other, SaveXMMOps));
2498 if (!MemOps.empty())
2499 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2503 // Some CCs need callee pop.
2504 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2505 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2506 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2508 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2509 // If this is an sret function, the return should pop the hidden pointer.
2510 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2511 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2512 argsAreStructReturn(Ins) == StackStructReturn)
2513 FuncInfo->setBytesToPopOnReturn(4);
2517 // RegSaveFrameIndex is X86-64 only.
2518 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2519 if (CallConv == CallingConv::X86_FastCall ||
2520 CallConv == CallingConv::X86_ThisCall)
2521 // fastcc functions can't have varargs.
2522 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2525 FuncInfo->setArgumentStackSize(StackSize);
2531 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2532 SDValue StackPtr, SDValue Arg,
2533 SDLoc dl, SelectionDAG &DAG,
2534 const CCValAssign &VA,
2535 ISD::ArgFlagsTy Flags) const {
2536 unsigned LocMemOffset = VA.getLocMemOffset();
2537 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2538 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2539 if (Flags.isByVal())
2540 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2542 return DAG.getStore(Chain, dl, Arg, PtrOff,
2543 MachinePointerInfo::getStack(LocMemOffset),
2547 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2548 /// optimization is performed and it is required.
2550 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2551 SDValue &OutRetAddr, SDValue Chain,
2552 bool IsTailCall, bool Is64Bit,
2553 int FPDiff, SDLoc dl) const {
2554 // Adjust the Return address stack slot.
2555 EVT VT = getPointerTy();
2556 OutRetAddr = getReturnAddressFrameIndex(DAG);
2558 // Load the "old" Return address.
2559 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2560 false, false, false, 0);
2561 return SDValue(OutRetAddr.getNode(), 1);
2564 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2565 /// optimization is performed and it is required (FPDiff!=0).
2566 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2567 SDValue Chain, SDValue RetAddrFrIdx,
2568 EVT PtrVT, unsigned SlotSize,
2569 int FPDiff, SDLoc dl) {
2570 // Store the return address to the appropriate stack slot.
2571 if (!FPDiff) return Chain;
2572 // Calculate the new stack slot for the return address.
2573 int NewReturnAddrFI =
2574 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2576 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2577 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2578 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2584 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2585 SmallVectorImpl<SDValue> &InVals) const {
2586 SelectionDAG &DAG = CLI.DAG;
2588 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2589 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2590 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2591 SDValue Chain = CLI.Chain;
2592 SDValue Callee = CLI.Callee;
2593 CallingConv::ID CallConv = CLI.CallConv;
2594 bool &isTailCall = CLI.IsTailCall;
2595 bool isVarArg = CLI.IsVarArg;
2597 MachineFunction &MF = DAG.getMachineFunction();
2598 bool Is64Bit = Subtarget->is64Bit();
2599 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2600 StructReturnType SR = callIsStructReturn(Outs);
2601 bool IsSibcall = false;
2603 if (MF.getTarget().Options.DisableTailCalls)
2606 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2608 // Force this to be a tail call. The verifier rules are enough to ensure
2609 // that we can lower this successfully without moving the return address
2612 } else if (isTailCall) {
2613 // Check if it's really possible to do a tail call.
2614 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2615 isVarArg, SR != NotStructReturn,
2616 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2617 Outs, OutVals, Ins, DAG);
2619 // Sibcalls are automatically detected tailcalls which do not require
2621 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2628 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2629 "Var args not supported with calling convention fastcc, ghc or hipe");
2631 // Analyze operands of the call, assigning locations to each operand.
2632 SmallVector<CCValAssign, 16> ArgLocs;
2633 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2634 ArgLocs, *DAG.getContext());
2636 // Allocate shadow area for Win64
2638 CCInfo.AllocateStack(32, 8);
2640 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2642 // Get a count of how many bytes are to be pushed on the stack.
2643 unsigned NumBytes = CCInfo.getNextStackOffset();
2645 // This is a sibcall. The memory operands are available in caller's
2646 // own caller's stack.
2648 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2649 IsTailCallConvention(CallConv))
2650 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2653 if (isTailCall && !IsSibcall && !IsMustTail) {
2654 // Lower arguments at fp - stackoffset + fpdiff.
2655 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2656 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2658 FPDiff = NumBytesCallerPushed - NumBytes;
2660 // Set the delta of movement of the returnaddr stackslot.
2661 // But only set if delta is greater than previous delta.
2662 if (FPDiff < X86Info->getTCReturnAddrDelta())
2663 X86Info->setTCReturnAddrDelta(FPDiff);
2666 unsigned NumBytesToPush = NumBytes;
2667 unsigned NumBytesToPop = NumBytes;
2669 // If we have an inalloca argument, all stack space has already been allocated
2670 // for us and be right at the top of the stack. We don't support multiple
2671 // arguments passed in memory when using inalloca.
2672 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2674 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2675 "an inalloca argument must be the only memory argument");
2679 Chain = DAG.getCALLSEQ_START(
2680 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2682 SDValue RetAddrFrIdx;
2683 // Load return address for tail calls.
2684 if (isTailCall && FPDiff)
2685 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2686 Is64Bit, FPDiff, dl);
2688 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2689 SmallVector<SDValue, 8> MemOpChains;
2692 // Walk the register/memloc assignments, inserting copies/loads. In the case
2693 // of tail call optimization arguments are handle later.
2694 const X86RegisterInfo *RegInfo =
2695 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2696 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2697 // Skip inalloca arguments, they have already been written.
2698 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2699 if (Flags.isInAlloca())
2702 CCValAssign &VA = ArgLocs[i];
2703 EVT RegVT = VA.getLocVT();
2704 SDValue Arg = OutVals[i];
2705 bool isByVal = Flags.isByVal();
2707 // Promote the value if needed.
2708 switch (VA.getLocInfo()) {
2709 default: llvm_unreachable("Unknown loc info!");
2710 case CCValAssign::Full: break;
2711 case CCValAssign::SExt:
2712 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2714 case CCValAssign::ZExt:
2715 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2717 case CCValAssign::AExt:
2718 if (RegVT.is128BitVector()) {
2719 // Special case: passing MMX values in XMM registers.
2720 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2721 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2722 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2724 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2726 case CCValAssign::BCvt:
2727 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2729 case CCValAssign::Indirect: {
2730 // Store the argument.
2731 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2732 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2733 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2734 MachinePointerInfo::getFixedStack(FI),
2741 if (VA.isRegLoc()) {
2742 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2743 if (isVarArg && IsWin64) {
2744 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2745 // shadow reg if callee is a varargs function.
2746 unsigned ShadowReg = 0;
2747 switch (VA.getLocReg()) {
2748 case X86::XMM0: ShadowReg = X86::RCX; break;
2749 case X86::XMM1: ShadowReg = X86::RDX; break;
2750 case X86::XMM2: ShadowReg = X86::R8; break;
2751 case X86::XMM3: ShadowReg = X86::R9; break;
2754 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2756 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2757 assert(VA.isMemLoc());
2758 if (!StackPtr.getNode())
2759 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2761 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2762 dl, DAG, VA, Flags));
2766 if (!MemOpChains.empty())
2767 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2769 if (Subtarget->isPICStyleGOT()) {
2770 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2773 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2774 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2776 // If we are tail calling and generating PIC/GOT style code load the
2777 // address of the callee into ECX. The value in ecx is used as target of
2778 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2779 // for tail calls on PIC/GOT architectures. Normally we would just put the
2780 // address of GOT into ebx and then call target@PLT. But for tail calls
2781 // ebx would be restored (since ebx is callee saved) before jumping to the
2784 // Note: The actual moving to ECX is done further down.
2785 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2786 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2787 !G->getGlobal()->hasProtectedVisibility())
2788 Callee = LowerGlobalAddress(Callee, DAG);
2789 else if (isa<ExternalSymbolSDNode>(Callee))
2790 Callee = LowerExternalSymbol(Callee, DAG);
2794 if (Is64Bit && isVarArg && !IsWin64) {
2795 // From AMD64 ABI document:
2796 // For calls that may call functions that use varargs or stdargs
2797 // (prototype-less calls or calls to functions containing ellipsis (...) in
2798 // the declaration) %al is used as hidden argument to specify the number
2799 // of SSE registers used. The contents of %al do not need to match exactly
2800 // the number of registers, but must be an ubound on the number of SSE
2801 // registers used and is in the range 0 - 8 inclusive.
2803 // Count the number of XMM registers allocated.
2804 static const MCPhysReg XMMArgRegs[] = {
2805 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2806 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2808 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2809 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2810 && "SSE registers cannot be used when SSE is disabled");
2812 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2813 DAG.getConstant(NumXMMRegs, MVT::i8)));
2816 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2817 // don't need this because the eligibility check rejects calls that require
2818 // shuffling arguments passed in memory.
2819 if (!IsSibcall && isTailCall) {
2820 // Force all the incoming stack arguments to be loaded from the stack
2821 // before any new outgoing arguments are stored to the stack, because the
2822 // outgoing stack slots may alias the incoming argument stack slots, and
2823 // the alias isn't otherwise explicit. This is slightly more conservative
2824 // than necessary, because it means that each store effectively depends
2825 // on every argument instead of just those arguments it would clobber.
2826 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2828 SmallVector<SDValue, 8> MemOpChains2;
2831 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2832 CCValAssign &VA = ArgLocs[i];
2835 assert(VA.isMemLoc());
2836 SDValue Arg = OutVals[i];
2837 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2838 // Skip inalloca arguments. They don't require any work.
2839 if (Flags.isInAlloca())
2841 // Create frame index.
2842 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2843 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2844 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2845 FIN = DAG.getFrameIndex(FI, getPointerTy());
2847 if (Flags.isByVal()) {
2848 // Copy relative to framepointer.
2849 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2850 if (!StackPtr.getNode())
2851 StackPtr = DAG.getCopyFromReg(Chain, dl,
2852 RegInfo->getStackRegister(),
2854 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2856 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2860 // Store relative to framepointer.
2861 MemOpChains2.push_back(
2862 DAG.getStore(ArgChain, dl, Arg, FIN,
2863 MachinePointerInfo::getFixedStack(FI),
2868 if (!MemOpChains2.empty())
2869 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2871 // Store the return address to the appropriate stack slot.
2872 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2873 getPointerTy(), RegInfo->getSlotSize(),
2877 // Build a sequence of copy-to-reg nodes chained together with token chain
2878 // and flag operands which copy the outgoing args into registers.
2880 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2881 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2882 RegsToPass[i].second, InFlag);
2883 InFlag = Chain.getValue(1);
2886 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2887 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2888 // In the 64-bit large code model, we have to make all calls
2889 // through a register, since the call instruction's 32-bit
2890 // pc-relative offset may not be large enough to hold the whole
2892 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2893 // If the callee is a GlobalAddress node (quite common, every direct call
2894 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2897 // We should use extra load for direct calls to dllimported functions in
2899 const GlobalValue *GV = G->getGlobal();
2900 if (!GV->hasDLLImportStorageClass()) {
2901 unsigned char OpFlags = 0;
2902 bool ExtraLoad = false;
2903 unsigned WrapperKind = ISD::DELETED_NODE;
2905 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2906 // external symbols most go through the PLT in PIC mode. If the symbol
2907 // has hidden or protected visibility, or if it is static or local, then
2908 // we don't need to use the PLT - we can directly call it.
2909 if (Subtarget->isTargetELF() &&
2910 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2911 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2912 OpFlags = X86II::MO_PLT;
2913 } else if (Subtarget->isPICStyleStubAny() &&
2914 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2915 (!Subtarget->getTargetTriple().isMacOSX() ||
2916 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2917 // PC-relative references to external symbols should go through $stub,
2918 // unless we're building with the leopard linker or later, which
2919 // automatically synthesizes these stubs.
2920 OpFlags = X86II::MO_DARWIN_STUB;
2921 } else if (Subtarget->isPICStyleRIPRel() &&
2922 isa<Function>(GV) &&
2923 cast<Function>(GV)->getAttributes().
2924 hasAttribute(AttributeSet::FunctionIndex,
2925 Attribute::NonLazyBind)) {
2926 // If the function is marked as non-lazy, generate an indirect call
2927 // which loads from the GOT directly. This avoids runtime overhead
2928 // at the cost of eager binding (and one extra byte of encoding).
2929 OpFlags = X86II::MO_GOTPCREL;
2930 WrapperKind = X86ISD::WrapperRIP;
2934 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2935 G->getOffset(), OpFlags);
2937 // Add a wrapper if needed.
2938 if (WrapperKind != ISD::DELETED_NODE)
2939 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2940 // Add extra indirection if needed.
2942 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2943 MachinePointerInfo::getGOT(),
2944 false, false, false, 0);
2946 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2947 unsigned char OpFlags = 0;
2949 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2950 // external symbols should go through the PLT.
2951 if (Subtarget->isTargetELF() &&
2952 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2953 OpFlags = X86II::MO_PLT;
2954 } else if (Subtarget->isPICStyleStubAny() &&
2955 (!Subtarget->getTargetTriple().isMacOSX() ||
2956 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2957 // PC-relative references to external symbols should go through $stub,
2958 // unless we're building with the leopard linker or later, which
2959 // automatically synthesizes these stubs.
2960 OpFlags = X86II::MO_DARWIN_STUB;
2963 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2967 // Returns a chain & a flag for retval copy to use.
2968 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2969 SmallVector<SDValue, 8> Ops;
2971 if (!IsSibcall && isTailCall) {
2972 Chain = DAG.getCALLSEQ_END(Chain,
2973 DAG.getIntPtrConstant(NumBytesToPop, true),
2974 DAG.getIntPtrConstant(0, true), InFlag, dl);
2975 InFlag = Chain.getValue(1);
2978 Ops.push_back(Chain);
2979 Ops.push_back(Callee);
2982 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2984 // Add argument registers to the end of the list so that they are known live
2986 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2987 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2988 RegsToPass[i].second.getValueType()));
2990 // Add a register mask operand representing the call-preserved registers.
2991 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2992 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2993 assert(Mask && "Missing call preserved mask for calling convention");
2994 Ops.push_back(DAG.getRegisterMask(Mask));
2996 if (InFlag.getNode())
2997 Ops.push_back(InFlag);
3001 //// If this is the first return lowered for this function, add the regs
3002 //// to the liveout set for the function.
3003 // This isn't right, although it's probably harmless on x86; liveouts
3004 // should be computed from returns not tail calls. Consider a void
3005 // function making a tail call to a function returning int.
3006 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3009 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3010 InFlag = Chain.getValue(1);
3012 // Create the CALLSEQ_END node.
3013 unsigned NumBytesForCalleeToPop;
3014 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3015 DAG.getTarget().Options.GuaranteedTailCallOpt))
3016 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3017 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3018 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3019 SR == StackStructReturn)
3020 // If this is a call to a struct-return function, the callee
3021 // pops the hidden struct pointer, so we have to push it back.
3022 // This is common for Darwin/X86, Linux & Mingw32 targets.
3023 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3024 NumBytesForCalleeToPop = 4;
3026 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3028 // Returns a flag for retval copy to use.
3030 Chain = DAG.getCALLSEQ_END(Chain,
3031 DAG.getIntPtrConstant(NumBytesToPop, true),
3032 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3035 InFlag = Chain.getValue(1);
3038 // Handle result values, copying them out of physregs into vregs that we
3040 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3041 Ins, dl, DAG, InVals);
3044 //===----------------------------------------------------------------------===//
3045 // Fast Calling Convention (tail call) implementation
3046 //===----------------------------------------------------------------------===//
3048 // Like std call, callee cleans arguments, convention except that ECX is
3049 // reserved for storing the tail called function address. Only 2 registers are
3050 // free for argument passing (inreg). Tail call optimization is performed
3052 // * tailcallopt is enabled
3053 // * caller/callee are fastcc
3054 // On X86_64 architecture with GOT-style position independent code only local
3055 // (within module) calls are supported at the moment.
3056 // To keep the stack aligned according to platform abi the function
3057 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3058 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3059 // If a tail called function callee has more arguments than the caller the
3060 // caller needs to make sure that there is room to move the RETADDR to. This is
3061 // achieved by reserving an area the size of the argument delta right after the
3062 // original RETADDR, but before the saved framepointer or the spilled registers
3063 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3075 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3076 /// for a 16 byte align requirement.
3078 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3079 SelectionDAG& DAG) const {
3080 MachineFunction &MF = DAG.getMachineFunction();
3081 const TargetMachine &TM = MF.getTarget();
3082 const X86RegisterInfo *RegInfo =
3083 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3084 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3085 unsigned StackAlignment = TFI.getStackAlignment();
3086 uint64_t AlignMask = StackAlignment - 1;
3087 int64_t Offset = StackSize;
3088 unsigned SlotSize = RegInfo->getSlotSize();
3089 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3090 // Number smaller than 12 so just add the difference.
3091 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3093 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3094 Offset = ((~AlignMask) & Offset) + StackAlignment +
3095 (StackAlignment-SlotSize);
3100 /// MatchingStackOffset - Return true if the given stack call argument is
3101 /// already available in the same position (relatively) of the caller's
3102 /// incoming argument stack.
3104 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3105 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3106 const X86InstrInfo *TII) {
3107 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3109 if (Arg.getOpcode() == ISD::CopyFromReg) {
3110 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3111 if (!TargetRegisterInfo::isVirtualRegister(VR))
3113 MachineInstr *Def = MRI->getVRegDef(VR);
3116 if (!Flags.isByVal()) {
3117 if (!TII->isLoadFromStackSlot(Def, FI))
3120 unsigned Opcode = Def->getOpcode();
3121 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3122 Def->getOperand(1).isFI()) {
3123 FI = Def->getOperand(1).getIndex();
3124 Bytes = Flags.getByValSize();
3128 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3129 if (Flags.isByVal())
3130 // ByVal argument is passed in as a pointer but it's now being
3131 // dereferenced. e.g.
3132 // define @foo(%struct.X* %A) {
3133 // tail call @bar(%struct.X* byval %A)
3136 SDValue Ptr = Ld->getBasePtr();
3137 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3140 FI = FINode->getIndex();
3141 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3142 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3143 FI = FINode->getIndex();
3144 Bytes = Flags.getByValSize();
3148 assert(FI != INT_MAX);
3149 if (!MFI->isFixedObjectIndex(FI))
3151 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3154 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3155 /// for tail call optimization. Targets which want to do tail call
3156 /// optimization should implement this function.
3158 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3159 CallingConv::ID CalleeCC,
3161 bool isCalleeStructRet,
3162 bool isCallerStructRet,
3164 const SmallVectorImpl<ISD::OutputArg> &Outs,
3165 const SmallVectorImpl<SDValue> &OutVals,
3166 const SmallVectorImpl<ISD::InputArg> &Ins,
3167 SelectionDAG &DAG) const {
3168 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3171 // If -tailcallopt is specified, make fastcc functions tail-callable.
3172 const MachineFunction &MF = DAG.getMachineFunction();
3173 const Function *CallerF = MF.getFunction();
3175 // If the function return type is x86_fp80 and the callee return type is not,
3176 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3177 // perform a tailcall optimization here.
3178 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3181 CallingConv::ID CallerCC = CallerF->getCallingConv();
3182 bool CCMatch = CallerCC == CalleeCC;
3183 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3184 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3186 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3187 if (IsTailCallConvention(CalleeCC) && CCMatch)
3192 // Look for obvious safe cases to perform tail call optimization that do not
3193 // require ABI changes. This is what gcc calls sibcall.
3195 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3196 // emit a special epilogue.
3197 const X86RegisterInfo *RegInfo =
3198 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3199 if (RegInfo->needsStackRealignment(MF))
3202 // Also avoid sibcall optimization if either caller or callee uses struct
3203 // return semantics.
3204 if (isCalleeStructRet || isCallerStructRet)
3207 // An stdcall/thiscall caller is expected to clean up its arguments; the
3208 // callee isn't going to do that.
3209 // FIXME: this is more restrictive than needed. We could produce a tailcall
3210 // when the stack adjustment matches. For example, with a thiscall that takes
3211 // only one argument.
3212 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3213 CallerCC == CallingConv::X86_ThisCall))
3216 // Do not sibcall optimize vararg calls unless all arguments are passed via
3218 if (isVarArg && !Outs.empty()) {
3220 // Optimizing for varargs on Win64 is unlikely to be safe without
3221 // additional testing.
3222 if (IsCalleeWin64 || IsCallerWin64)
3225 SmallVector<CCValAssign, 16> ArgLocs;
3226 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3227 DAG.getTarget(), ArgLocs, *DAG.getContext());
3229 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3230 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3231 if (!ArgLocs[i].isRegLoc())
3235 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3236 // stack. Therefore, if it's not used by the call it is not safe to optimize
3237 // this into a sibcall.
3238 bool Unused = false;
3239 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3246 SmallVector<CCValAssign, 16> RVLocs;
3247 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3248 DAG.getTarget(), RVLocs, *DAG.getContext());
3249 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3250 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3251 CCValAssign &VA = RVLocs[i];
3252 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3257 // If the calling conventions do not match, then we'd better make sure the
3258 // results are returned in the same way as what the caller expects.
3260 SmallVector<CCValAssign, 16> RVLocs1;
3261 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3262 DAG.getTarget(), RVLocs1, *DAG.getContext());
3263 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3265 SmallVector<CCValAssign, 16> RVLocs2;
3266 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3267 DAG.getTarget(), RVLocs2, *DAG.getContext());
3268 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3270 if (RVLocs1.size() != RVLocs2.size())
3272 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3273 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3275 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3277 if (RVLocs1[i].isRegLoc()) {
3278 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3281 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3287 // If the callee takes no arguments then go on to check the results of the
3289 if (!Outs.empty()) {
3290 // Check if stack adjustment is needed. For now, do not do this if any
3291 // argument is passed on the stack.
3292 SmallVector<CCValAssign, 16> ArgLocs;
3293 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3294 DAG.getTarget(), ArgLocs, *DAG.getContext());
3296 // Allocate shadow area for Win64
3298 CCInfo.AllocateStack(32, 8);
3300 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3301 if (CCInfo.getNextStackOffset()) {
3302 MachineFunction &MF = DAG.getMachineFunction();
3303 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3306 // Check if the arguments are already laid out in the right way as
3307 // the caller's fixed stack objects.
3308 MachineFrameInfo *MFI = MF.getFrameInfo();
3309 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3310 const X86InstrInfo *TII =
3311 static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3312 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3313 CCValAssign &VA = ArgLocs[i];
3314 SDValue Arg = OutVals[i];
3315 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3316 if (VA.getLocInfo() == CCValAssign::Indirect)
3318 if (!VA.isRegLoc()) {
3319 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3326 // If the tailcall address may be in a register, then make sure it's
3327 // possible to register allocate for it. In 32-bit, the call address can
3328 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3329 // callee-saved registers are restored. These happen to be the same
3330 // registers used to pass 'inreg' arguments so watch out for those.
3331 if (!Subtarget->is64Bit() &&
3332 ((!isa<GlobalAddressSDNode>(Callee) &&
3333 !isa<ExternalSymbolSDNode>(Callee)) ||
3334 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3335 unsigned NumInRegs = 0;
3336 // In PIC we need an extra register to formulate the address computation
3338 unsigned MaxInRegs =
3339 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3341 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3342 CCValAssign &VA = ArgLocs[i];
3345 unsigned Reg = VA.getLocReg();
3348 case X86::EAX: case X86::EDX: case X86::ECX:
3349 if (++NumInRegs == MaxInRegs)
3361 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3362 const TargetLibraryInfo *libInfo) const {
3363 return X86::createFastISel(funcInfo, libInfo);
3366 //===----------------------------------------------------------------------===//
3367 // Other Lowering Hooks
3368 //===----------------------------------------------------------------------===//
3370 static bool MayFoldLoad(SDValue Op) {
3371 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3374 static bool MayFoldIntoStore(SDValue Op) {
3375 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3378 static bool isTargetShuffle(unsigned Opcode) {
3380 default: return false;
3381 case X86ISD::PSHUFD:
3382 case X86ISD::PSHUFHW:
3383 case X86ISD::PSHUFLW:
3385 case X86ISD::PALIGNR:
3386 case X86ISD::MOVLHPS:
3387 case X86ISD::MOVLHPD:
3388 case X86ISD::MOVHLPS:
3389 case X86ISD::MOVLPS:
3390 case X86ISD::MOVLPD:
3391 case X86ISD::MOVSHDUP:
3392 case X86ISD::MOVSLDUP:
3393 case X86ISD::MOVDDUP:
3396 case X86ISD::UNPCKL:
3397 case X86ISD::UNPCKH:
3398 case X86ISD::VPERMILP:
3399 case X86ISD::VPERM2X128:
3400 case X86ISD::VPERMI:
3405 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3406 SDValue V1, SelectionDAG &DAG) {
3408 default: llvm_unreachable("Unknown x86 shuffle node");
3409 case X86ISD::MOVSHDUP:
3410 case X86ISD::MOVSLDUP:
3411 case X86ISD::MOVDDUP:
3412 return DAG.getNode(Opc, dl, VT, V1);
3416 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3417 SDValue V1, unsigned TargetMask,
3418 SelectionDAG &DAG) {
3420 default: llvm_unreachable("Unknown x86 shuffle node");
3421 case X86ISD::PSHUFD:
3422 case X86ISD::PSHUFHW:
3423 case X86ISD::PSHUFLW:
3424 case X86ISD::VPERMILP:
3425 case X86ISD::VPERMI:
3426 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3430 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3431 SDValue V1, SDValue V2, unsigned TargetMask,
3432 SelectionDAG &DAG) {
3434 default: llvm_unreachable("Unknown x86 shuffle node");
3435 case X86ISD::PALIGNR:
3437 case X86ISD::VPERM2X128:
3438 return DAG.getNode(Opc, dl, VT, V1, V2,
3439 DAG.getConstant(TargetMask, MVT::i8));
3443 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3444 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3446 default: llvm_unreachable("Unknown x86 shuffle node");
3447 case X86ISD::MOVLHPS:
3448 case X86ISD::MOVLHPD:
3449 case X86ISD::MOVHLPS:
3450 case X86ISD::MOVLPS:
3451 case X86ISD::MOVLPD:
3454 case X86ISD::UNPCKL:
3455 case X86ISD::UNPCKH:
3456 return DAG.getNode(Opc, dl, VT, V1, V2);
3460 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3461 MachineFunction &MF = DAG.getMachineFunction();
3462 const X86RegisterInfo *RegInfo =
3463 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3464 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3465 int ReturnAddrIndex = FuncInfo->getRAIndex();
3467 if (ReturnAddrIndex == 0) {
3468 // Set up a frame object for the return address.
3469 unsigned SlotSize = RegInfo->getSlotSize();
3470 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3473 FuncInfo->setRAIndex(ReturnAddrIndex);
3476 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3479 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3480 bool hasSymbolicDisplacement) {
3481 // Offset should fit into 32 bit immediate field.
3482 if (!isInt<32>(Offset))
3485 // If we don't have a symbolic displacement - we don't have any extra
3487 if (!hasSymbolicDisplacement)
3490 // FIXME: Some tweaks might be needed for medium code model.
3491 if (M != CodeModel::Small && M != CodeModel::Kernel)
3494 // For small code model we assume that latest object is 16MB before end of 31
3495 // bits boundary. We may also accept pretty large negative constants knowing
3496 // that all objects are in the positive half of address space.
3497 if (M == CodeModel::Small && Offset < 16*1024*1024)
3500 // For kernel code model we know that all object resist in the negative half
3501 // of 32bits address space. We may not accept negative offsets, since they may
3502 // be just off and we may accept pretty large positive ones.
3503 if (M == CodeModel::Kernel && Offset > 0)
3509 /// isCalleePop - Determines whether the callee is required to pop its
3510 /// own arguments. Callee pop is necessary to support tail calls.
3511 bool X86::isCalleePop(CallingConv::ID CallingConv,
3512 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3516 switch (CallingConv) {
3519 case CallingConv::X86_StdCall:
3521 case CallingConv::X86_FastCall:
3523 case CallingConv::X86_ThisCall:
3525 case CallingConv::Fast:
3527 case CallingConv::GHC:
3529 case CallingConv::HiPE:
3534 /// \brief Return true if the condition is an unsigned comparison operation.
3535 static bool isX86CCUnsigned(unsigned X86CC) {
3537 default: llvm_unreachable("Invalid integer condition!");
3538 case X86::COND_E: return true;
3539 case X86::COND_G: return false;
3540 case X86::COND_GE: return false;
3541 case X86::COND_L: return false;
3542 case X86::COND_LE: return false;
3543 case X86::COND_NE: return true;
3544 case X86::COND_B: return true;
3545 case X86::COND_A: return true;
3546 case X86::COND_BE: return true;
3547 case X86::COND_AE: return true;
3549 llvm_unreachable("covered switch fell through?!");
3552 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3553 /// specific condition code, returning the condition code and the LHS/RHS of the
3554 /// comparison to make.
3555 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3556 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3558 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3559 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3560 // X > -1 -> X == 0, jump !sign.
3561 RHS = DAG.getConstant(0, RHS.getValueType());
3562 return X86::COND_NS;
3564 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3565 // X < 0 -> X == 0, jump on sign.
3568 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3570 RHS = DAG.getConstant(0, RHS.getValueType());
3571 return X86::COND_LE;
3575 switch (SetCCOpcode) {
3576 default: llvm_unreachable("Invalid integer condition!");
3577 case ISD::SETEQ: return X86::COND_E;
3578 case ISD::SETGT: return X86::COND_G;
3579 case ISD::SETGE: return X86::COND_GE;
3580 case ISD::SETLT: return X86::COND_L;
3581 case ISD::SETLE: return X86::COND_LE;
3582 case ISD::SETNE: return X86::COND_NE;
3583 case ISD::SETULT: return X86::COND_B;
3584 case ISD::SETUGT: return X86::COND_A;
3585 case ISD::SETULE: return X86::COND_BE;
3586 case ISD::SETUGE: return X86::COND_AE;
3590 // First determine if it is required or is profitable to flip the operands.
3592 // If LHS is a foldable load, but RHS is not, flip the condition.
3593 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3594 !ISD::isNON_EXTLoad(RHS.getNode())) {
3595 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3596 std::swap(LHS, RHS);
3599 switch (SetCCOpcode) {
3605 std::swap(LHS, RHS);
3609 // On a floating point condition, the flags are set as follows:
3611 // 0 | 0 | 0 | X > Y
3612 // 0 | 0 | 1 | X < Y
3613 // 1 | 0 | 0 | X == Y
3614 // 1 | 1 | 1 | unordered
3615 switch (SetCCOpcode) {
3616 default: llvm_unreachable("Condcode should be pre-legalized away");
3618 case ISD::SETEQ: return X86::COND_E;
3619 case ISD::SETOLT: // flipped
3621 case ISD::SETGT: return X86::COND_A;
3622 case ISD::SETOLE: // flipped
3624 case ISD::SETGE: return X86::COND_AE;
3625 case ISD::SETUGT: // flipped
3627 case ISD::SETLT: return X86::COND_B;
3628 case ISD::SETUGE: // flipped
3630 case ISD::SETLE: return X86::COND_BE;
3632 case ISD::SETNE: return X86::COND_NE;
3633 case ISD::SETUO: return X86::COND_P;
3634 case ISD::SETO: return X86::COND_NP;
3636 case ISD::SETUNE: return X86::COND_INVALID;
3640 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3641 /// code. Current x86 isa includes the following FP cmov instructions:
3642 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3643 static bool hasFPCMov(unsigned X86CC) {
3659 /// isFPImmLegal - Returns true if the target can instruction select the
3660 /// specified FP immediate natively. If false, the legalizer will
3661 /// materialize the FP immediate as a load from a constant pool.
3662 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3663 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3664 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3670 /// \brief Returns true if it is beneficial to convert a load of a constant
3671 /// to just the constant itself.
3672 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3674 assert(Ty->isIntegerTy());
3676 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3677 if (BitSize == 0 || BitSize > 64)
3682 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3683 /// the specified range (L, H].
3684 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3685 return (Val < 0) || (Val >= Low && Val < Hi);
3688 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3689 /// specified value.
3690 static bool isUndefOrEqual(int Val, int CmpVal) {
3691 return (Val < 0 || Val == CmpVal);
3694 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3695 /// from position Pos and ending in Pos+Size, falls within the specified
3696 /// sequential range (L, L+Pos]. or is undef.
3697 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3698 unsigned Pos, unsigned Size, int Low) {
3699 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3700 if (!isUndefOrEqual(Mask[i], Low))
3705 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3706 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3707 /// the second operand.
3708 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3709 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3710 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3711 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3712 return (Mask[0] < 2 && Mask[1] < 2);
3716 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3717 /// is suitable for input to PSHUFHW.
3718 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3719 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3722 // Lower quadword copied in order or undef.
3723 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3726 // Upper quadword shuffled.
3727 for (unsigned i = 4; i != 8; ++i)
3728 if (!isUndefOrInRange(Mask[i], 4, 8))
3731 if (VT == MVT::v16i16) {
3732 // Lower quadword copied in order or undef.
3733 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3736 // Upper quadword shuffled.
3737 for (unsigned i = 12; i != 16; ++i)
3738 if (!isUndefOrInRange(Mask[i], 12, 16))
3745 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3746 /// is suitable for input to PSHUFLW.
3747 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3748 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3751 // Upper quadword copied in order.
3752 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3755 // Lower quadword shuffled.
3756 for (unsigned i = 0; i != 4; ++i)
3757 if (!isUndefOrInRange(Mask[i], 0, 4))
3760 if (VT == MVT::v16i16) {
3761 // Upper quadword copied in order.
3762 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3765 // Lower quadword shuffled.
3766 for (unsigned i = 8; i != 12; ++i)
3767 if (!isUndefOrInRange(Mask[i], 8, 12))
3774 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3775 /// is suitable for input to PALIGNR.
3776 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3777 const X86Subtarget *Subtarget) {
3778 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3779 (VT.is256BitVector() && !Subtarget->hasInt256()))
3782 unsigned NumElts = VT.getVectorNumElements();
3783 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3784 unsigned NumLaneElts = NumElts/NumLanes;
3786 // Do not handle 64-bit element shuffles with palignr.
3787 if (NumLaneElts == 2)
3790 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3792 for (i = 0; i != NumLaneElts; ++i) {
3797 // Lane is all undef, go to next lane
3798 if (i == NumLaneElts)
3801 int Start = Mask[i+l];
3803 // Make sure its in this lane in one of the sources
3804 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3805 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3808 // If not lane 0, then we must match lane 0
3809 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3812 // Correct second source to be contiguous with first source
3813 if (Start >= (int)NumElts)
3814 Start -= NumElts - NumLaneElts;
3816 // Make sure we're shifting in the right direction.
3817 if (Start <= (int)(i+l))
3822 // Check the rest of the elements to see if they are consecutive.
3823 for (++i; i != NumLaneElts; ++i) {
3824 int Idx = Mask[i+l];
3826 // Make sure its in this lane
3827 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3828 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3831 // If not lane 0, then we must match lane 0
3832 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3835 if (Idx >= (int)NumElts)
3836 Idx -= NumElts - NumLaneElts;
3838 if (!isUndefOrEqual(Idx, Start+i))
3847 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3848 /// the two vector operands have swapped position.
3849 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3850 unsigned NumElems) {
3851 for (unsigned i = 0; i != NumElems; ++i) {
3855 else if (idx < (int)NumElems)
3856 Mask[i] = idx + NumElems;
3858 Mask[i] = idx - NumElems;
3862 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3863 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3864 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3865 /// reverse of what x86 shuffles want.
3866 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3868 unsigned NumElems = VT.getVectorNumElements();
3869 unsigned NumLanes = VT.getSizeInBits()/128;
3870 unsigned NumLaneElems = NumElems/NumLanes;
3872 if (NumLaneElems != 2 && NumLaneElems != 4)
3875 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3876 bool symetricMaskRequired =
3877 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3879 // VSHUFPSY divides the resulting vector into 4 chunks.
3880 // The sources are also splitted into 4 chunks, and each destination
3881 // chunk must come from a different source chunk.
3883 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3884 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3886 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3887 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3889 // VSHUFPDY divides the resulting vector into 4 chunks.
3890 // The sources are also splitted into 4 chunks, and each destination
3891 // chunk must come from a different source chunk.
3893 // SRC1 => X3 X2 X1 X0
3894 // SRC2 => Y3 Y2 Y1 Y0
3896 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3898 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3899 unsigned HalfLaneElems = NumLaneElems/2;
3900 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3901 for (unsigned i = 0; i != NumLaneElems; ++i) {
3902 int Idx = Mask[i+l];
3903 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3904 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3906 // For VSHUFPSY, the mask of the second half must be the same as the
3907 // first but with the appropriate offsets. This works in the same way as
3908 // VPERMILPS works with masks.
3909 if (!symetricMaskRequired || Idx < 0)
3911 if (MaskVal[i] < 0) {
3912 MaskVal[i] = Idx - l;
3915 if ((signed)(Idx - l) != MaskVal[i])
3923 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3924 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3925 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3926 if (!VT.is128BitVector())
3929 unsigned NumElems = VT.getVectorNumElements();
3934 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3935 return isUndefOrEqual(Mask[0], 6) &&
3936 isUndefOrEqual(Mask[1], 7) &&
3937 isUndefOrEqual(Mask[2], 2) &&
3938 isUndefOrEqual(Mask[3], 3);
3941 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3942 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3944 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3945 if (!VT.is128BitVector())
3948 unsigned NumElems = VT.getVectorNumElements();
3953 return isUndefOrEqual(Mask[0], 2) &&
3954 isUndefOrEqual(Mask[1], 3) &&
3955 isUndefOrEqual(Mask[2], 2) &&
3956 isUndefOrEqual(Mask[3], 3);
3959 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3960 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3961 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3962 if (!VT.is128BitVector())
3965 unsigned NumElems = VT.getVectorNumElements();
3967 if (NumElems != 2 && NumElems != 4)
3970 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3971 if (!isUndefOrEqual(Mask[i], i + NumElems))
3974 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3975 if (!isUndefOrEqual(Mask[i], i))
3981 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3982 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3983 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3984 if (!VT.is128BitVector())
3987 unsigned NumElems = VT.getVectorNumElements();
3989 if (NumElems != 2 && NumElems != 4)
3992 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3993 if (!isUndefOrEqual(Mask[i], i))
3996 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3997 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4003 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4004 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4005 /// i. e: If all but one element come from the same vector.
4006 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4007 // TODO: Deal with AVX's VINSERTPS
4008 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4011 unsigned CorrectPosV1 = 0;
4012 unsigned CorrectPosV2 = 0;
4013 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4014 if (Mask[i] == -1) {
4022 else if (Mask[i] == i + 4)
4026 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4027 // We have 3 elements (undefs count as elements from any vector) from one
4028 // vector, and one from another.
4035 // Some special combinations that can be optimized.
4038 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4039 SelectionDAG &DAG) {
4040 MVT VT = SVOp->getSimpleValueType(0);
4043 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4046 ArrayRef<int> Mask = SVOp->getMask();
4048 // These are the special masks that may be optimized.
4049 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4050 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4051 bool MatchEvenMask = true;
4052 bool MatchOddMask = true;
4053 for (int i=0; i<8; ++i) {
4054 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4055 MatchEvenMask = false;
4056 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4057 MatchOddMask = false;
4060 if (!MatchEvenMask && !MatchOddMask)
4063 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4065 SDValue Op0 = SVOp->getOperand(0);
4066 SDValue Op1 = SVOp->getOperand(1);
4068 if (MatchEvenMask) {
4069 // Shift the second operand right to 32 bits.
4070 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4071 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4073 // Shift the first operand left to 32 bits.
4074 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4075 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4077 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4078 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4081 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4082 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4083 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4084 bool HasInt256, bool V2IsSplat = false) {
4086 assert(VT.getSizeInBits() >= 128 &&
4087 "Unsupported vector type for unpckl");
4089 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4091 unsigned NumOf256BitLanes;
4092 unsigned NumElts = VT.getVectorNumElements();
4093 if (VT.is256BitVector()) {
4094 if (NumElts != 4 && NumElts != 8 &&
4095 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4098 NumOf256BitLanes = 1;
4099 } else if (VT.is512BitVector()) {
4100 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4101 "Unsupported vector type for unpckh");
4103 NumOf256BitLanes = 2;
4106 NumOf256BitLanes = 1;
4109 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4110 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4112 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4113 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4114 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4115 int BitI = Mask[l256*NumEltsInStride+l+i];
4116 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4117 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4119 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4121 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4129 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4130 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4131 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4132 bool HasInt256, bool V2IsSplat = false) {
4133 assert(VT.getSizeInBits() >= 128 &&
4134 "Unsupported vector type for unpckh");
4136 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4138 unsigned NumOf256BitLanes;
4139 unsigned NumElts = VT.getVectorNumElements();
4140 if (VT.is256BitVector()) {
4141 if (NumElts != 4 && NumElts != 8 &&
4142 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4145 NumOf256BitLanes = 1;
4146 } else if (VT.is512BitVector()) {
4147 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4148 "Unsupported vector type for unpckh");
4150 NumOf256BitLanes = 2;
4153 NumOf256BitLanes = 1;
4156 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4157 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4159 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4160 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4161 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4162 int BitI = Mask[l256*NumEltsInStride+l+i];
4163 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4164 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4166 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4168 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4176 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4177 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4179 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4180 unsigned NumElts = VT.getVectorNumElements();
4181 bool Is256BitVec = VT.is256BitVector();
4183 if (VT.is512BitVector())
4185 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4186 "Unsupported vector type for unpckh");
4188 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4189 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4192 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4193 // FIXME: Need a better way to get rid of this, there's no latency difference
4194 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4195 // the former later. We should also remove the "_undef" special mask.
4196 if (NumElts == 4 && Is256BitVec)
4199 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4200 // independently on 128-bit lanes.
4201 unsigned NumLanes = VT.getSizeInBits()/128;
4202 unsigned NumLaneElts = NumElts/NumLanes;
4204 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4205 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4206 int BitI = Mask[l+i];
4207 int BitI1 = Mask[l+i+1];
4209 if (!isUndefOrEqual(BitI, j))
4211 if (!isUndefOrEqual(BitI1, j))
4219 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4220 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4222 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4223 unsigned NumElts = VT.getVectorNumElements();
4225 if (VT.is512BitVector())
4228 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4229 "Unsupported vector type for unpckh");
4231 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4232 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4235 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4236 // independently on 128-bit lanes.
4237 unsigned NumLanes = VT.getSizeInBits()/128;
4238 unsigned NumLaneElts = NumElts/NumLanes;
4240 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4241 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4242 int BitI = Mask[l+i];
4243 int BitI1 = Mask[l+i+1];
4244 if (!isUndefOrEqual(BitI, j))
4246 if (!isUndefOrEqual(BitI1, j))
4253 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4254 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4255 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4256 if (!VT.is512BitVector())
4259 unsigned NumElts = VT.getVectorNumElements();
4260 unsigned HalfSize = NumElts/2;
4261 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4262 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4267 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4268 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4276 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4277 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4278 /// MOVSD, and MOVD, i.e. setting the lowest element.
4279 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4280 if (VT.getVectorElementType().getSizeInBits() < 32)
4282 if (!VT.is128BitVector())
4285 unsigned NumElts = VT.getVectorNumElements();
4287 if (!isUndefOrEqual(Mask[0], NumElts))
4290 for (unsigned i = 1; i != NumElts; ++i)
4291 if (!isUndefOrEqual(Mask[i], i))
4297 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4298 /// as permutations between 128-bit chunks or halves. As an example: this
4300 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4301 /// The first half comes from the second half of V1 and the second half from the
4302 /// the second half of V2.
4303 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4304 if (!HasFp256 || !VT.is256BitVector())
4307 // The shuffle result is divided into half A and half B. In total the two
4308 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4309 // B must come from C, D, E or F.
4310 unsigned HalfSize = VT.getVectorNumElements()/2;
4311 bool MatchA = false, MatchB = false;
4313 // Check if A comes from one of C, D, E, F.
4314 for (unsigned Half = 0; Half != 4; ++Half) {
4315 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4321 // Check if B comes from one of C, D, E, F.
4322 for (unsigned Half = 0; Half != 4; ++Half) {
4323 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4329 return MatchA && MatchB;
4332 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4333 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4334 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4335 MVT VT = SVOp->getSimpleValueType(0);
4337 unsigned HalfSize = VT.getVectorNumElements()/2;
4339 unsigned FstHalf = 0, SndHalf = 0;
4340 for (unsigned i = 0; i < HalfSize; ++i) {
4341 if (SVOp->getMaskElt(i) > 0) {
4342 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4346 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4347 if (SVOp->getMaskElt(i) > 0) {
4348 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4353 return (FstHalf | (SndHalf << 4));
4356 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4357 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4358 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4362 unsigned NumElts = VT.getVectorNumElements();
4364 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4365 for (unsigned i = 0; i != NumElts; ++i) {
4368 Imm8 |= Mask[i] << (i*2);
4373 unsigned LaneSize = 4;
4374 SmallVector<int, 4> MaskVal(LaneSize, -1);
4376 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4377 for (unsigned i = 0; i != LaneSize; ++i) {
4378 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4382 if (MaskVal[i] < 0) {
4383 MaskVal[i] = Mask[i+l] - l;
4384 Imm8 |= MaskVal[i] << (i*2);
4387 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4394 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4395 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4396 /// Note that VPERMIL mask matching is different depending whether theunderlying
4397 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4398 /// to the same elements of the low, but to the higher half of the source.
4399 /// In VPERMILPD the two lanes could be shuffled independently of each other
4400 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4401 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4402 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4403 if (VT.getSizeInBits() < 256 || EltSize < 32)
4405 bool symetricMaskRequired = (EltSize == 32);
4406 unsigned NumElts = VT.getVectorNumElements();
4408 unsigned NumLanes = VT.getSizeInBits()/128;
4409 unsigned LaneSize = NumElts/NumLanes;
4410 // 2 or 4 elements in one lane
4412 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4413 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4414 for (unsigned i = 0; i != LaneSize; ++i) {
4415 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4417 if (symetricMaskRequired) {
4418 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4419 ExpectedMaskVal[i] = Mask[i+l] - l;
4422 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4430 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4431 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4432 /// element of vector 2 and the other elements to come from vector 1 in order.
4433 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4434 bool V2IsSplat = false, bool V2IsUndef = false) {
4435 if (!VT.is128BitVector())
4438 unsigned NumOps = VT.getVectorNumElements();
4439 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4442 if (!isUndefOrEqual(Mask[0], 0))
4445 for (unsigned i = 1; i != NumOps; ++i)
4446 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4447 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4448 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4454 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4455 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4456 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4457 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4458 const X86Subtarget *Subtarget) {
4459 if (!Subtarget->hasSSE3())
4462 unsigned NumElems = VT.getVectorNumElements();
4464 if ((VT.is128BitVector() && NumElems != 4) ||
4465 (VT.is256BitVector() && NumElems != 8) ||
4466 (VT.is512BitVector() && NumElems != 16))
4469 // "i+1" is the value the indexed mask element must have
4470 for (unsigned i = 0; i != NumElems; i += 2)
4471 if (!isUndefOrEqual(Mask[i], i+1) ||
4472 !isUndefOrEqual(Mask[i+1], i+1))
4478 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4479 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4480 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4481 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4482 const X86Subtarget *Subtarget) {
4483 if (!Subtarget->hasSSE3())
4486 unsigned NumElems = VT.getVectorNumElements();
4488 if ((VT.is128BitVector() && NumElems != 4) ||
4489 (VT.is256BitVector() && NumElems != 8) ||
4490 (VT.is512BitVector() && NumElems != 16))
4493 // "i" is the value the indexed mask element must have
4494 for (unsigned i = 0; i != NumElems; i += 2)
4495 if (!isUndefOrEqual(Mask[i], i) ||
4496 !isUndefOrEqual(Mask[i+1], i))
4502 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4503 /// specifies a shuffle of elements that is suitable for input to 256-bit
4504 /// version of MOVDDUP.
4505 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4506 if (!HasFp256 || !VT.is256BitVector())
4509 unsigned NumElts = VT.getVectorNumElements();
4513 for (unsigned i = 0; i != NumElts/2; ++i)
4514 if (!isUndefOrEqual(Mask[i], 0))
4516 for (unsigned i = NumElts/2; i != NumElts; ++i)
4517 if (!isUndefOrEqual(Mask[i], NumElts/2))
4522 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4523 /// specifies a shuffle of elements that is suitable for input to 128-bit
4524 /// version of MOVDDUP.
4525 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4526 if (!VT.is128BitVector())
4529 unsigned e = VT.getVectorNumElements() / 2;
4530 for (unsigned i = 0; i != e; ++i)
4531 if (!isUndefOrEqual(Mask[i], i))
4533 for (unsigned i = 0; i != e; ++i)
4534 if (!isUndefOrEqual(Mask[e+i], i))
4539 /// isVEXTRACTIndex - Return true if the specified
4540 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4541 /// suitable for instruction that extract 128 or 256 bit vectors
4542 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4543 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4544 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4547 // The index should be aligned on a vecWidth-bit boundary.
4549 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4551 MVT VT = N->getSimpleValueType(0);
4552 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4553 bool Result = (Index * ElSize) % vecWidth == 0;
4558 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4559 /// operand specifies a subvector insert that is suitable for input to
4560 /// insertion of 128 or 256-bit subvectors
4561 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4562 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4563 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4565 // The index should be aligned on a vecWidth-bit boundary.
4567 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4569 MVT VT = N->getSimpleValueType(0);
4570 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4571 bool Result = (Index * ElSize) % vecWidth == 0;
4576 bool X86::isVINSERT128Index(SDNode *N) {
4577 return isVINSERTIndex(N, 128);
4580 bool X86::isVINSERT256Index(SDNode *N) {
4581 return isVINSERTIndex(N, 256);
4584 bool X86::isVEXTRACT128Index(SDNode *N) {
4585 return isVEXTRACTIndex(N, 128);
4588 bool X86::isVEXTRACT256Index(SDNode *N) {
4589 return isVEXTRACTIndex(N, 256);
4592 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4593 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4594 /// Handles 128-bit and 256-bit.
4595 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4596 MVT VT = N->getSimpleValueType(0);
4598 assert((VT.getSizeInBits() >= 128) &&
4599 "Unsupported vector type for PSHUF/SHUFP");
4601 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4602 // independently on 128-bit lanes.
4603 unsigned NumElts = VT.getVectorNumElements();
4604 unsigned NumLanes = VT.getSizeInBits()/128;
4605 unsigned NumLaneElts = NumElts/NumLanes;
4607 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4608 "Only supports 2, 4 or 8 elements per lane");
4610 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4612 for (unsigned i = 0; i != NumElts; ++i) {
4613 int Elt = N->getMaskElt(i);
4614 if (Elt < 0) continue;
4615 Elt &= NumLaneElts - 1;
4616 unsigned ShAmt = (i << Shift) % 8;
4617 Mask |= Elt << ShAmt;
4623 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4624 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4625 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4626 MVT VT = N->getSimpleValueType(0);
4628 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4629 "Unsupported vector type for PSHUFHW");
4631 unsigned NumElts = VT.getVectorNumElements();
4634 for (unsigned l = 0; l != NumElts; l += 8) {
4635 // 8 nodes per lane, but we only care about the last 4.
4636 for (unsigned i = 0; i < 4; ++i) {
4637 int Elt = N->getMaskElt(l+i+4);
4638 if (Elt < 0) continue;
4639 Elt &= 0x3; // only 2-bits.
4640 Mask |= Elt << (i * 2);
4647 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4648 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4649 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4650 MVT VT = N->getSimpleValueType(0);
4652 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4653 "Unsupported vector type for PSHUFHW");
4655 unsigned NumElts = VT.getVectorNumElements();
4658 for (unsigned l = 0; l != NumElts; l += 8) {
4659 // 8 nodes per lane, but we only care about the first 4.
4660 for (unsigned i = 0; i < 4; ++i) {
4661 int Elt = N->getMaskElt(l+i);
4662 if (Elt < 0) continue;
4663 Elt &= 0x3; // only 2-bits
4664 Mask |= Elt << (i * 2);
4671 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4672 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4673 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4674 MVT VT = SVOp->getSimpleValueType(0);
4675 unsigned EltSize = VT.is512BitVector() ? 1 :
4676 VT.getVectorElementType().getSizeInBits() >> 3;
4678 unsigned NumElts = VT.getVectorNumElements();
4679 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4680 unsigned NumLaneElts = NumElts/NumLanes;
4684 for (i = 0; i != NumElts; ++i) {
4685 Val = SVOp->getMaskElt(i);
4689 if (Val >= (int)NumElts)
4690 Val -= NumElts - NumLaneElts;
4692 assert(Val - i > 0 && "PALIGNR imm should be positive");
4693 return (Val - i) * EltSize;
4696 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4697 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4698 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4699 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4702 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4704 MVT VecVT = N->getOperand(0).getSimpleValueType();
4705 MVT ElVT = VecVT.getVectorElementType();
4707 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4708 return Index / NumElemsPerChunk;
4711 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4712 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4713 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4714 llvm_unreachable("Illegal insert subvector for VINSERT");
4717 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4719 MVT VecVT = N->getSimpleValueType(0);
4720 MVT ElVT = VecVT.getVectorElementType();
4722 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4723 return Index / NumElemsPerChunk;
4726 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4727 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4728 /// and VINSERTI128 instructions.
4729 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4730 return getExtractVEXTRACTImmediate(N, 128);
4733 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4734 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4735 /// and VINSERTI64x4 instructions.
4736 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4737 return getExtractVEXTRACTImmediate(N, 256);
4740 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4741 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4742 /// and VINSERTI128 instructions.
4743 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4744 return getInsertVINSERTImmediate(N, 128);
4747 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4748 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4749 /// and VINSERTI64x4 instructions.
4750 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4751 return getInsertVINSERTImmediate(N, 256);
4754 /// isZero - Returns true if Elt is a constant integer zero
4755 static bool isZero(SDValue V) {
4756 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4757 return C && C->isNullValue();
4760 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4762 bool X86::isZeroNode(SDValue Elt) {
4765 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4766 return CFP->getValueAPF().isPosZero();
4770 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4771 /// their permute mask.
4772 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4773 SelectionDAG &DAG) {
4774 MVT VT = SVOp->getSimpleValueType(0);
4775 unsigned NumElems = VT.getVectorNumElements();
4776 SmallVector<int, 8> MaskVec;
4778 for (unsigned i = 0; i != NumElems; ++i) {
4779 int Idx = SVOp->getMaskElt(i);
4781 if (Idx < (int)NumElems)
4786 MaskVec.push_back(Idx);
4788 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4789 SVOp->getOperand(0), &MaskVec[0]);
4792 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4793 /// match movhlps. The lower half elements should come from upper half of
4794 /// V1 (and in order), and the upper half elements should come from the upper
4795 /// half of V2 (and in order).
4796 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4797 if (!VT.is128BitVector())
4799 if (VT.getVectorNumElements() != 4)
4801 for (unsigned i = 0, e = 2; i != e; ++i)
4802 if (!isUndefOrEqual(Mask[i], i+2))
4804 for (unsigned i = 2; i != 4; ++i)
4805 if (!isUndefOrEqual(Mask[i], i+4))
4810 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4811 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4813 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4814 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4816 N = N->getOperand(0).getNode();
4817 if (!ISD::isNON_EXTLoad(N))
4820 *LD = cast<LoadSDNode>(N);
4824 // Test whether the given value is a vector value which will be legalized
4826 static bool WillBeConstantPoolLoad(SDNode *N) {
4827 if (N->getOpcode() != ISD::BUILD_VECTOR)
4830 // Check for any non-constant elements.
4831 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4832 switch (N->getOperand(i).getNode()->getOpcode()) {
4834 case ISD::ConstantFP:
4841 // Vectors of all-zeros and all-ones are materialized with special
4842 // instructions rather than being loaded.
4843 return !ISD::isBuildVectorAllZeros(N) &&
4844 !ISD::isBuildVectorAllOnes(N);
4847 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4848 /// match movlp{s|d}. The lower half elements should come from lower half of
4849 /// V1 (and in order), and the upper half elements should come from the upper
4850 /// half of V2 (and in order). And since V1 will become the source of the
4851 /// MOVLP, it must be either a vector load or a scalar load to vector.
4852 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4853 ArrayRef<int> Mask, MVT VT) {
4854 if (!VT.is128BitVector())
4857 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4859 // Is V2 is a vector load, don't do this transformation. We will try to use
4860 // load folding shufps op.
4861 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4864 unsigned NumElems = VT.getVectorNumElements();
4866 if (NumElems != 2 && NumElems != 4)
4868 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4869 if (!isUndefOrEqual(Mask[i], i))
4871 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4872 if (!isUndefOrEqual(Mask[i], i+NumElems))
4877 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4878 /// to an zero vector.
4879 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4880 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4881 SDValue V1 = N->getOperand(0);
4882 SDValue V2 = N->getOperand(1);
4883 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4884 for (unsigned i = 0; i != NumElems; ++i) {
4885 int Idx = N->getMaskElt(i);
4886 if (Idx >= (int)NumElems) {
4887 unsigned Opc = V2.getOpcode();
4888 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4890 if (Opc != ISD::BUILD_VECTOR ||
4891 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4893 } else if (Idx >= 0) {
4894 unsigned Opc = V1.getOpcode();
4895 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4897 if (Opc != ISD::BUILD_VECTOR ||
4898 !X86::isZeroNode(V1.getOperand(Idx)))
4905 /// getZeroVector - Returns a vector of specified type with all zero elements.
4907 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4908 SelectionDAG &DAG, SDLoc dl) {
4909 assert(VT.isVector() && "Expected a vector type");
4911 // Always build SSE zero vectors as <4 x i32> bitcasted
4912 // to their dest type. This ensures they get CSE'd.
4914 if (VT.is128BitVector()) { // SSE
4915 if (Subtarget->hasSSE2()) { // SSE2
4916 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4917 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4919 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4920 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4922 } else if (VT.is256BitVector()) { // AVX
4923 if (Subtarget->hasInt256()) { // AVX2
4924 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4925 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4926 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4928 // 256-bit logic and arithmetic instructions in AVX are all
4929 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4930 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4931 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4932 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4934 } else if (VT.is512BitVector()) { // AVX-512
4935 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4936 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4937 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4938 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4939 } else if (VT.getScalarType() == MVT::i1) {
4940 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4941 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4942 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4943 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4945 llvm_unreachable("Unexpected vector type");
4947 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4950 /// getOnesVector - Returns a vector of specified type with all bits set.
4951 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4952 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4953 /// Then bitcast to their original type, ensuring they get CSE'd.
4954 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4956 assert(VT.isVector() && "Expected a vector type");
4958 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4960 if (VT.is256BitVector()) {
4961 if (HasInt256) { // AVX2
4962 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4963 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4965 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4966 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4968 } else if (VT.is128BitVector()) {
4969 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4971 llvm_unreachable("Unexpected vector type");
4973 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4976 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4977 /// that point to V2 points to its first element.
4978 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4979 for (unsigned i = 0; i != NumElems; ++i) {
4980 if (Mask[i] > (int)NumElems) {
4986 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4987 /// operation of specified width.
4988 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4990 unsigned NumElems = VT.getVectorNumElements();
4991 SmallVector<int, 8> Mask;
4992 Mask.push_back(NumElems);
4993 for (unsigned i = 1; i != NumElems; ++i)
4995 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4998 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4999 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5001 unsigned NumElems = VT.getVectorNumElements();
5002 SmallVector<int, 8> Mask;
5003 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5005 Mask.push_back(i + NumElems);
5007 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5010 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5011 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5013 unsigned NumElems = VT.getVectorNumElements();
5014 SmallVector<int, 8> Mask;
5015 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5016 Mask.push_back(i + Half);
5017 Mask.push_back(i + NumElems + Half);
5019 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5022 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5023 // a generic shuffle instruction because the target has no such instructions.
5024 // Generate shuffles which repeat i16 and i8 several times until they can be
5025 // represented by v4f32 and then be manipulated by target suported shuffles.
5026 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5027 MVT VT = V.getSimpleValueType();
5028 int NumElems = VT.getVectorNumElements();
5031 while (NumElems > 4) {
5032 if (EltNo < NumElems/2) {
5033 V = getUnpackl(DAG, dl, VT, V, V);
5035 V = getUnpackh(DAG, dl, VT, V, V);
5036 EltNo -= NumElems/2;
5043 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5044 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5045 MVT VT = V.getSimpleValueType();
5048 if (VT.is128BitVector()) {
5049 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5050 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5051 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5053 } else if (VT.is256BitVector()) {
5054 // To use VPERMILPS to splat scalars, the second half of indicies must
5055 // refer to the higher part, which is a duplication of the lower one,
5056 // because VPERMILPS can only handle in-lane permutations.
5057 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5058 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5060 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5061 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5064 llvm_unreachable("Vector size not supported");
5066 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5069 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5070 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5071 MVT SrcVT = SV->getSimpleValueType(0);
5072 SDValue V1 = SV->getOperand(0);
5075 int EltNo = SV->getSplatIndex();
5076 int NumElems = SrcVT.getVectorNumElements();
5077 bool Is256BitVec = SrcVT.is256BitVector();
5079 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5080 "Unknown how to promote splat for type");
5082 // Extract the 128-bit part containing the splat element and update
5083 // the splat element index when it refers to the higher register.
5085 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5086 if (EltNo >= NumElems/2)
5087 EltNo -= NumElems/2;
5090 // All i16 and i8 vector types can't be used directly by a generic shuffle
5091 // instruction because the target has no such instruction. Generate shuffles
5092 // which repeat i16 and i8 several times until they fit in i32, and then can
5093 // be manipulated by target suported shuffles.
5094 MVT EltVT = SrcVT.getVectorElementType();
5095 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5096 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5098 // Recreate the 256-bit vector and place the same 128-bit vector
5099 // into the low and high part. This is necessary because we want
5100 // to use VPERM* to shuffle the vectors
5102 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5105 return getLegalSplat(DAG, V1, EltNo);
5108 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5109 /// vector of zero or undef vector. This produces a shuffle where the low
5110 /// element of V2 is swizzled into the zero/undef vector, landing at element
5111 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5112 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5114 const X86Subtarget *Subtarget,
5115 SelectionDAG &DAG) {
5116 MVT VT = V2.getSimpleValueType();
5118 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5119 unsigned NumElems = VT.getVectorNumElements();
5120 SmallVector<int, 16> MaskVec;
5121 for (unsigned i = 0; i != NumElems; ++i)
5122 // If this is the insertion idx, put the low elt of V2 here.
5123 MaskVec.push_back(i == Idx ? NumElems : i);
5124 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5127 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5128 /// target specific opcode. Returns true if the Mask could be calculated.
5129 /// Sets IsUnary to true if only uses one source.
5130 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5131 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5132 unsigned NumElems = VT.getVectorNumElements();
5136 switch(N->getOpcode()) {
5138 ImmN = N->getOperand(N->getNumOperands()-1);
5139 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5141 case X86ISD::UNPCKH:
5142 DecodeUNPCKHMask(VT, Mask);
5144 case X86ISD::UNPCKL:
5145 DecodeUNPCKLMask(VT, Mask);
5147 case X86ISD::MOVHLPS:
5148 DecodeMOVHLPSMask(NumElems, Mask);
5150 case X86ISD::MOVLHPS:
5151 DecodeMOVLHPSMask(NumElems, Mask);
5153 case X86ISD::PALIGNR:
5154 ImmN = N->getOperand(N->getNumOperands()-1);
5155 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5157 case X86ISD::PSHUFD:
5158 case X86ISD::VPERMILP:
5159 ImmN = N->getOperand(N->getNumOperands()-1);
5160 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5163 case X86ISD::PSHUFHW:
5164 ImmN = N->getOperand(N->getNumOperands()-1);
5165 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5168 case X86ISD::PSHUFLW:
5169 ImmN = N->getOperand(N->getNumOperands()-1);
5170 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5173 case X86ISD::VPERMI:
5174 ImmN = N->getOperand(N->getNumOperands()-1);
5175 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5179 case X86ISD::MOVSD: {
5180 // The index 0 always comes from the first element of the second source,
5181 // this is why MOVSS and MOVSD are used in the first place. The other
5182 // elements come from the other positions of the first source vector
5183 Mask.push_back(NumElems);
5184 for (unsigned i = 1; i != NumElems; ++i) {
5189 case X86ISD::VPERM2X128:
5190 ImmN = N->getOperand(N->getNumOperands()-1);
5191 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5192 if (Mask.empty()) return false;
5194 case X86ISD::MOVDDUP:
5195 case X86ISD::MOVLHPD:
5196 case X86ISD::MOVLPD:
5197 case X86ISD::MOVLPS:
5198 case X86ISD::MOVSHDUP:
5199 case X86ISD::MOVSLDUP:
5200 // Not yet implemented
5202 default: llvm_unreachable("unknown target shuffle node");
5208 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5209 /// element of the result of the vector shuffle.
5210 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5213 return SDValue(); // Limit search depth.
5215 SDValue V = SDValue(N, 0);
5216 EVT VT = V.getValueType();
5217 unsigned Opcode = V.getOpcode();
5219 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5220 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5221 int Elt = SV->getMaskElt(Index);
5224 return DAG.getUNDEF(VT.getVectorElementType());
5226 unsigned NumElems = VT.getVectorNumElements();
5227 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5228 : SV->getOperand(1);
5229 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5232 // Recurse into target specific vector shuffles to find scalars.
5233 if (isTargetShuffle(Opcode)) {
5234 MVT ShufVT = V.getSimpleValueType();
5235 unsigned NumElems = ShufVT.getVectorNumElements();
5236 SmallVector<int, 16> ShuffleMask;
5239 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5242 int Elt = ShuffleMask[Index];
5244 return DAG.getUNDEF(ShufVT.getVectorElementType());
5246 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5248 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5252 // Actual nodes that may contain scalar elements
5253 if (Opcode == ISD::BITCAST) {
5254 V = V.getOperand(0);
5255 EVT SrcVT = V.getValueType();
5256 unsigned NumElems = VT.getVectorNumElements();
5258 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5262 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5263 return (Index == 0) ? V.getOperand(0)
5264 : DAG.getUNDEF(VT.getVectorElementType());
5266 if (V.getOpcode() == ISD::BUILD_VECTOR)
5267 return V.getOperand(Index);
5272 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5273 /// shuffle operation which come from a consecutively from a zero. The
5274 /// search can start in two different directions, from left or right.
5275 /// We count undefs as zeros until PreferredNum is reached.
5276 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5277 unsigned NumElems, bool ZerosFromLeft,
5279 unsigned PreferredNum = -1U) {
5280 unsigned NumZeros = 0;
5281 for (unsigned i = 0; i != NumElems; ++i) {
5282 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5283 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5287 if (X86::isZeroNode(Elt))
5289 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5290 NumZeros = std::min(NumZeros + 1, PreferredNum);
5298 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5299 /// correspond consecutively to elements from one of the vector operands,
5300 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5302 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5303 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5304 unsigned NumElems, unsigned &OpNum) {
5305 bool SeenV1 = false;
5306 bool SeenV2 = false;
5308 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5309 int Idx = SVOp->getMaskElt(i);
5310 // Ignore undef indicies
5314 if (Idx < (int)NumElems)
5319 // Only accept consecutive elements from the same vector
5320 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5324 OpNum = SeenV1 ? 0 : 1;
5328 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5329 /// logical left shift of a vector.
5330 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5331 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5333 SVOp->getSimpleValueType(0).getVectorNumElements();
5334 unsigned NumZeros = getNumOfConsecutiveZeros(
5335 SVOp, NumElems, false /* check zeros from right */, DAG,
5336 SVOp->getMaskElt(0));
5342 // Considering the elements in the mask that are not consecutive zeros,
5343 // check if they consecutively come from only one of the source vectors.
5345 // V1 = {X, A, B, C} 0
5347 // vector_shuffle V1, V2 <1, 2, 3, X>
5349 if (!isShuffleMaskConsecutive(SVOp,
5350 0, // Mask Start Index
5351 NumElems-NumZeros, // Mask End Index(exclusive)
5352 NumZeros, // Where to start looking in the src vector
5353 NumElems, // Number of elements in vector
5354 OpSrc)) // Which source operand ?
5359 ShVal = SVOp->getOperand(OpSrc);
5363 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5364 /// logical left shift of a vector.
5365 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5366 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5368 SVOp->getSimpleValueType(0).getVectorNumElements();
5369 unsigned NumZeros = getNumOfConsecutiveZeros(
5370 SVOp, NumElems, true /* check zeros from left */, DAG,
5371 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5377 // Considering the elements in the mask that are not consecutive zeros,
5378 // check if they consecutively come from only one of the source vectors.
5380 // 0 { A, B, X, X } = V2
5382 // vector_shuffle V1, V2 <X, X, 4, 5>
5384 if (!isShuffleMaskConsecutive(SVOp,
5385 NumZeros, // Mask Start Index
5386 NumElems, // Mask End Index(exclusive)
5387 0, // Where to start looking in the src vector
5388 NumElems, // Number of elements in vector
5389 OpSrc)) // Which source operand ?
5394 ShVal = SVOp->getOperand(OpSrc);
5398 /// isVectorShift - Returns true if the shuffle can be implemented as a
5399 /// logical left or right shift of a vector.
5400 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5401 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5402 // Although the logic below support any bitwidth size, there are no
5403 // shift instructions which handle more than 128-bit vectors.
5404 if (!SVOp->getSimpleValueType(0).is128BitVector())
5407 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5408 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5414 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5416 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5417 unsigned NumNonZero, unsigned NumZero,
5419 const X86Subtarget* Subtarget,
5420 const TargetLowering &TLI) {
5427 for (unsigned i = 0; i < 16; ++i) {
5428 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5429 if (ThisIsNonZero && First) {
5431 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5433 V = DAG.getUNDEF(MVT::v8i16);
5438 SDValue ThisElt, LastElt;
5439 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5440 if (LastIsNonZero) {
5441 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5442 MVT::i16, Op.getOperand(i-1));
5444 if (ThisIsNonZero) {
5445 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5446 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5447 ThisElt, DAG.getConstant(8, MVT::i8));
5449 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5453 if (ThisElt.getNode())
5454 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5455 DAG.getIntPtrConstant(i/2));
5459 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5462 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5464 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5465 unsigned NumNonZero, unsigned NumZero,
5467 const X86Subtarget* Subtarget,
5468 const TargetLowering &TLI) {
5475 for (unsigned i = 0; i < 8; ++i) {
5476 bool isNonZero = (NonZeros & (1 << i)) != 0;
5480 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5482 V = DAG.getUNDEF(MVT::v8i16);
5485 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5486 MVT::v8i16, V, Op.getOperand(i),
5487 DAG.getIntPtrConstant(i));
5494 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5495 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5496 unsigned NonZeros, unsigned NumNonZero,
5497 unsigned NumZero, SelectionDAG &DAG,
5498 const X86Subtarget *Subtarget,
5499 const TargetLowering &TLI) {
5500 // We know there's at least one non-zero element
5501 unsigned FirstNonZeroIdx = 0;
5502 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5503 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5504 X86::isZeroNode(FirstNonZero)) {
5506 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5509 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5510 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5513 SDValue V = FirstNonZero.getOperand(0);
5514 MVT VVT = V.getSimpleValueType();
5515 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5518 unsigned FirstNonZeroDst =
5519 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5520 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5521 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5522 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5524 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5525 SDValue Elem = Op.getOperand(Idx);
5526 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5529 // TODO: What else can be here? Deal with it.
5530 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5533 // TODO: Some optimizations are still possible here
5534 // ex: Getting one element from a vector, and the rest from another.
5535 if (Elem.getOperand(0) != V)
5538 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5541 else if (IncorrectIdx == -1U) {
5545 // There was already one element with an incorrect index.
5546 // We can't optimize this case to an insertps.
5550 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5552 EVT VT = Op.getSimpleValueType();
5553 unsigned ElementMoveMask = 0;
5554 if (IncorrectIdx == -1U)
5555 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5557 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5559 SDValue InsertpsMask =
5560 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5561 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5567 /// getVShift - Return a vector logical shift node.
5569 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5570 unsigned NumBits, SelectionDAG &DAG,
5571 const TargetLowering &TLI, SDLoc dl) {
5572 assert(VT.is128BitVector() && "Unknown type for VShift");
5573 EVT ShVT = MVT::v2i64;
5574 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5575 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5576 return DAG.getNode(ISD::BITCAST, dl, VT,
5577 DAG.getNode(Opc, dl, ShVT, SrcOp,
5578 DAG.getConstant(NumBits,
5579 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5583 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5585 // Check if the scalar load can be widened into a vector load. And if
5586 // the address is "base + cst" see if the cst can be "absorbed" into
5587 // the shuffle mask.
5588 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5589 SDValue Ptr = LD->getBasePtr();
5590 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5592 EVT PVT = LD->getValueType(0);
5593 if (PVT != MVT::i32 && PVT != MVT::f32)
5598 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5599 FI = FINode->getIndex();
5601 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5602 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5603 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5604 Offset = Ptr.getConstantOperandVal(1);
5605 Ptr = Ptr.getOperand(0);
5610 // FIXME: 256-bit vector instructions don't require a strict alignment,
5611 // improve this code to support it better.
5612 unsigned RequiredAlign = VT.getSizeInBits()/8;
5613 SDValue Chain = LD->getChain();
5614 // Make sure the stack object alignment is at least 16 or 32.
5615 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5616 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5617 if (MFI->isFixedObjectIndex(FI)) {
5618 // Can't change the alignment. FIXME: It's possible to compute
5619 // the exact stack offset and reference FI + adjust offset instead.
5620 // If someone *really* cares about this. That's the way to implement it.
5623 MFI->setObjectAlignment(FI, RequiredAlign);
5627 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5628 // Ptr + (Offset & ~15).
5631 if ((Offset % RequiredAlign) & 3)
5633 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5635 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5636 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5638 int EltNo = (Offset - StartOffset) >> 2;
5639 unsigned NumElems = VT.getVectorNumElements();
5641 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5642 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5643 LD->getPointerInfo().getWithOffset(StartOffset),
5644 false, false, false, 0);
5646 SmallVector<int, 8> Mask;
5647 for (unsigned i = 0; i != NumElems; ++i)
5648 Mask.push_back(EltNo);
5650 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5656 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5657 /// vector of type 'VT', see if the elements can be replaced by a single large
5658 /// load which has the same value as a build_vector whose operands are 'elts'.
5660 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5662 /// FIXME: we'd also like to handle the case where the last elements are zero
5663 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5664 /// There's even a handy isZeroNode for that purpose.
5665 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5666 SDLoc &DL, SelectionDAG &DAG,
5667 bool isAfterLegalize) {
5668 EVT EltVT = VT.getVectorElementType();
5669 unsigned NumElems = Elts.size();
5671 LoadSDNode *LDBase = nullptr;
5672 unsigned LastLoadedElt = -1U;
5674 // For each element in the initializer, see if we've found a load or an undef.
5675 // If we don't find an initial load element, or later load elements are
5676 // non-consecutive, bail out.
5677 for (unsigned i = 0; i < NumElems; ++i) {
5678 SDValue Elt = Elts[i];
5680 if (!Elt.getNode() ||
5681 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5684 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5686 LDBase = cast<LoadSDNode>(Elt.getNode());
5690 if (Elt.getOpcode() == ISD::UNDEF)
5693 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5694 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5699 // If we have found an entire vector of loads and undefs, then return a large
5700 // load of the entire vector width starting at the base pointer. If we found
5701 // consecutive loads for the low half, generate a vzext_load node.
5702 if (LastLoadedElt == NumElems - 1) {
5704 if (isAfterLegalize &&
5705 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5708 SDValue NewLd = SDValue();
5710 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5711 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5712 LDBase->getPointerInfo(),
5713 LDBase->isVolatile(), LDBase->isNonTemporal(),
5714 LDBase->isInvariant(), 0);
5715 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5716 LDBase->getPointerInfo(),
5717 LDBase->isVolatile(), LDBase->isNonTemporal(),
5718 LDBase->isInvariant(), LDBase->getAlignment());
5720 if (LDBase->hasAnyUseOfValue(1)) {
5721 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5723 SDValue(NewLd.getNode(), 1));
5724 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5725 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5726 SDValue(NewLd.getNode(), 1));
5731 if (NumElems == 4 && LastLoadedElt == 1 &&
5732 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5733 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5734 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5736 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5737 LDBase->getPointerInfo(),
5738 LDBase->getAlignment(),
5739 false/*isVolatile*/, true/*ReadMem*/,
5742 // Make sure the newly-created LOAD is in the same position as LDBase in
5743 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5744 // update uses of LDBase's output chain to use the TokenFactor.
5745 if (LDBase->hasAnyUseOfValue(1)) {
5746 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5747 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5748 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5749 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5750 SDValue(ResNode.getNode(), 1));
5753 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5758 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5759 /// to generate a splat value for the following cases:
5760 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5761 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5762 /// a scalar load, or a constant.
5763 /// The VBROADCAST node is returned when a pattern is found,
5764 /// or SDValue() otherwise.
5765 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5766 SelectionDAG &DAG) {
5767 if (!Subtarget->hasFp256())
5770 MVT VT = Op.getSimpleValueType();
5773 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5774 "Unsupported vector type for broadcast.");
5779 switch (Op.getOpcode()) {
5781 // Unknown pattern found.
5784 case ISD::BUILD_VECTOR: {
5785 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5786 BitVector UndefElements;
5787 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5789 // We need a splat of a single value to use broadcast, and it doesn't
5790 // make any sense if the value is only in one element of the vector.
5791 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5795 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5796 Ld.getOpcode() == ISD::ConstantFP);
5798 // Make sure that all of the users of a non-constant load are from the
5799 // BUILD_VECTOR node.
5800 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5805 case ISD::VECTOR_SHUFFLE: {
5806 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5808 // Shuffles must have a splat mask where the first element is
5810 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5813 SDValue Sc = Op.getOperand(0);
5814 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5815 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5817 if (!Subtarget->hasInt256())
5820 // Use the register form of the broadcast instruction available on AVX2.
5821 if (VT.getSizeInBits() >= 256)
5822 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5823 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5826 Ld = Sc.getOperand(0);
5827 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5828 Ld.getOpcode() == ISD::ConstantFP);
5830 // The scalar_to_vector node and the suspected
5831 // load node must have exactly one user.
5832 // Constants may have multiple users.
5834 // AVX-512 has register version of the broadcast
5835 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5836 Ld.getValueType().getSizeInBits() >= 32;
5837 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5844 bool IsGE256 = (VT.getSizeInBits() >= 256);
5846 // Handle the broadcasting a single constant scalar from the constant pool
5847 // into a vector. On Sandybridge it is still better to load a constant vector
5848 // from the constant pool and not to broadcast it from a scalar.
5849 if (ConstSplatVal && Subtarget->hasInt256()) {
5850 EVT CVT = Ld.getValueType();
5851 assert(!CVT.isVector() && "Must not broadcast a vector type");
5852 unsigned ScalarSize = CVT.getSizeInBits();
5854 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5855 const Constant *C = nullptr;
5856 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5857 C = CI->getConstantIntValue();
5858 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5859 C = CF->getConstantFPValue();
5861 assert(C && "Invalid constant type");
5863 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5864 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5865 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5866 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5867 MachinePointerInfo::getConstantPool(),
5868 false, false, false, Alignment);
5870 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5874 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5875 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5877 // Handle AVX2 in-register broadcasts.
5878 if (!IsLoad && Subtarget->hasInt256() &&
5879 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5880 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5882 // The scalar source must be a normal load.
5886 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5887 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5889 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5890 // double since there is no vbroadcastsd xmm
5891 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5892 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5893 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5896 // Unsupported broadcast.
5900 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5901 /// underlying vector and index.
5903 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5905 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5907 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5908 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5911 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5913 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5915 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5916 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5919 // In this case the vector is the extract_subvector expression and the index
5920 // is 2, as specified by the shuffle.
5921 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5922 SDValue ShuffleVec = SVOp->getOperand(0);
5923 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5924 assert(ShuffleVecVT.getVectorElementType() ==
5925 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5927 int ShuffleIdx = SVOp->getMaskElt(Idx);
5928 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5929 ExtractedFromVec = ShuffleVec;
5935 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5936 MVT VT = Op.getSimpleValueType();
5938 // Skip if insert_vec_elt is not supported.
5939 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5940 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5944 unsigned NumElems = Op.getNumOperands();
5948 SmallVector<unsigned, 4> InsertIndices;
5949 SmallVector<int, 8> Mask(NumElems, -1);
5951 for (unsigned i = 0; i != NumElems; ++i) {
5952 unsigned Opc = Op.getOperand(i).getOpcode();
5954 if (Opc == ISD::UNDEF)
5957 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5958 // Quit if more than 1 elements need inserting.
5959 if (InsertIndices.size() > 1)
5962 InsertIndices.push_back(i);
5966 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5967 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5968 // Quit if non-constant index.
5969 if (!isa<ConstantSDNode>(ExtIdx))
5971 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5973 // Quit if extracted from vector of different type.
5974 if (ExtractedFromVec.getValueType() != VT)
5977 if (!VecIn1.getNode())
5978 VecIn1 = ExtractedFromVec;
5979 else if (VecIn1 != ExtractedFromVec) {
5980 if (!VecIn2.getNode())
5981 VecIn2 = ExtractedFromVec;
5982 else if (VecIn2 != ExtractedFromVec)
5983 // Quit if more than 2 vectors to shuffle
5987 if (ExtractedFromVec == VecIn1)
5989 else if (ExtractedFromVec == VecIn2)
5990 Mask[i] = Idx + NumElems;
5993 if (!VecIn1.getNode())
5996 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5997 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5998 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5999 unsigned Idx = InsertIndices[i];
6000 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6001 DAG.getIntPtrConstant(Idx));
6007 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6009 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6011 MVT VT = Op.getSimpleValueType();
6012 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6013 "Unexpected type in LowerBUILD_VECTORvXi1!");
6016 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6017 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6018 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6019 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6022 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6023 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6024 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6025 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6028 bool AllContants = true;
6029 uint64_t Immediate = 0;
6030 int NonConstIdx = -1;
6031 bool IsSplat = true;
6032 unsigned NumNonConsts = 0;
6033 unsigned NumConsts = 0;
6034 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6035 SDValue In = Op.getOperand(idx);
6036 if (In.getOpcode() == ISD::UNDEF)
6038 if (!isa<ConstantSDNode>(In)) {
6039 AllContants = false;
6045 if (cast<ConstantSDNode>(In)->getZExtValue())
6046 Immediate |= (1ULL << idx);
6048 if (In != Op.getOperand(0))
6053 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6054 DAG.getConstant(Immediate, MVT::i16));
6055 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6056 DAG.getIntPtrConstant(0));
6059 if (NumNonConsts == 1 && NonConstIdx != 0) {
6062 SDValue VecAsImm = DAG.getConstant(Immediate,
6063 MVT::getIntegerVT(VT.getSizeInBits()));
6064 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6067 DstVec = DAG.getUNDEF(VT);
6068 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6069 Op.getOperand(NonConstIdx),
6070 DAG.getIntPtrConstant(NonConstIdx));
6072 if (!IsSplat && (NonConstIdx != 0))
6073 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6074 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6077 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6078 DAG.getConstant(-1, SelectVT),
6079 DAG.getConstant(0, SelectVT));
6081 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6082 DAG.getConstant((Immediate | 1), SelectVT),
6083 DAG.getConstant(Immediate, SelectVT));
6084 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6087 /// \brief Return true if \p N implements a horizontal binop and return the
6088 /// operands for the horizontal binop into V0 and V1.
6090 /// This is a helper function of PerformBUILD_VECTORCombine.
6091 /// This function checks that the build_vector \p N in input implements a
6092 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6093 /// operation to match.
6094 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6095 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6096 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6099 /// This function only analyzes elements of \p N whose indices are
6100 /// in range [BaseIdx, LastIdx).
6101 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6103 unsigned BaseIdx, unsigned LastIdx,
6104 SDValue &V0, SDValue &V1) {
6105 EVT VT = N->getValueType(0);
6107 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6108 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6109 "Invalid Vector in input!");
6111 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6112 bool CanFold = true;
6113 unsigned ExpectedVExtractIdx = BaseIdx;
6114 unsigned NumElts = LastIdx - BaseIdx;
6115 V0 = DAG.getUNDEF(VT);
6116 V1 = DAG.getUNDEF(VT);
6118 // Check if N implements a horizontal binop.
6119 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6120 SDValue Op = N->getOperand(i + BaseIdx);
6123 if (Op->getOpcode() == ISD::UNDEF) {
6124 // Update the expected vector extract index.
6125 if (i * 2 == NumElts)
6126 ExpectedVExtractIdx = BaseIdx;
6127 ExpectedVExtractIdx += 2;
6131 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6136 SDValue Op0 = Op.getOperand(0);
6137 SDValue Op1 = Op.getOperand(1);
6139 // Try to match the following pattern:
6140 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6141 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6142 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6143 Op0.getOperand(0) == Op1.getOperand(0) &&
6144 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6145 isa<ConstantSDNode>(Op1.getOperand(1)));
6149 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6150 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6152 if (i * 2 < NumElts) {
6153 if (V0.getOpcode() == ISD::UNDEF)
6154 V0 = Op0.getOperand(0);
6156 if (V1.getOpcode() == ISD::UNDEF)
6157 V1 = Op0.getOperand(0);
6158 if (i * 2 == NumElts)
6159 ExpectedVExtractIdx = BaseIdx;
6162 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6163 if (I0 == ExpectedVExtractIdx)
6164 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6165 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6166 // Try to match the following dag sequence:
6167 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6168 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6172 ExpectedVExtractIdx += 2;
6178 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6179 /// a concat_vector.
6181 /// This is a helper function of PerformBUILD_VECTORCombine.
6182 /// This function expects two 256-bit vectors called V0 and V1.
6183 /// At first, each vector is split into two separate 128-bit vectors.
6184 /// Then, the resulting 128-bit vectors are used to implement two
6185 /// horizontal binary operations.
6187 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6189 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6190 /// the two new horizontal binop.
6191 /// When Mode is set, the first horizontal binop dag node would take as input
6192 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6193 /// horizontal binop dag node would take as input the lower 128-bit of V1
6194 /// and the upper 128-bit of V1.
6196 /// HADD V0_LO, V0_HI
6197 /// HADD V1_LO, V1_HI
6199 /// Otherwise, the first horizontal binop dag node takes as input the lower
6200 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6201 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6203 /// HADD V0_LO, V1_LO
6204 /// HADD V0_HI, V1_HI
6206 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6207 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6208 /// the upper 128-bits of the result.
6209 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6210 SDLoc DL, SelectionDAG &DAG,
6211 unsigned X86Opcode, bool Mode,
6212 bool isUndefLO, bool isUndefHI) {
6213 EVT VT = V0.getValueType();
6214 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6215 "Invalid nodes in input!");
6217 unsigned NumElts = VT.getVectorNumElements();
6218 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6219 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6220 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6221 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6222 EVT NewVT = V0_LO.getValueType();
6224 SDValue LO = DAG.getUNDEF(NewVT);
6225 SDValue HI = DAG.getUNDEF(NewVT);
6228 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6229 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6230 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6231 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6232 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6234 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6235 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6236 V1_LO->getOpcode() != ISD::UNDEF))
6237 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6239 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6240 V1_HI->getOpcode() != ISD::UNDEF))
6241 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6244 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6247 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6248 /// sequence of 'vadd + vsub + blendi'.
6249 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6250 const X86Subtarget *Subtarget) {
6252 EVT VT = BV->getValueType(0);
6253 unsigned NumElts = VT.getVectorNumElements();
6254 SDValue InVec0 = DAG.getUNDEF(VT);
6255 SDValue InVec1 = DAG.getUNDEF(VT);
6257 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6258 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6260 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6261 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6262 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6265 // Odd-numbered elements in the input build vector are obtained from
6266 // adding two integer/float elements.
6267 // Even-numbered elements in the input build vector are obtained from
6268 // subtracting two integer/float elements.
6269 unsigned ExpectedOpcode = ISD::FSUB;
6270 unsigned NextExpectedOpcode = ISD::FADD;
6271 bool AddFound = false;
6272 bool SubFound = false;
6274 for (unsigned i = 0, e = NumElts; i != e; i++) {
6275 SDValue Op = BV->getOperand(i);
6277 // Skip 'undef' values.
6278 unsigned Opcode = Op.getOpcode();
6279 if (Opcode == ISD::UNDEF) {
6280 std::swap(ExpectedOpcode, NextExpectedOpcode);
6284 // Early exit if we found an unexpected opcode.
6285 if (Opcode != ExpectedOpcode)
6288 SDValue Op0 = Op.getOperand(0);
6289 SDValue Op1 = Op.getOperand(1);
6291 // Try to match the following pattern:
6292 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6293 // Early exit if we cannot match that sequence.
6294 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6295 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6296 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6297 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6298 Op0.getOperand(1) != Op1.getOperand(1))
6301 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6305 // We found a valid add/sub node. Update the information accordingly.
6311 // Update InVec0 and InVec1.
6312 if (InVec0.getOpcode() == ISD::UNDEF)
6313 InVec0 = Op0.getOperand(0);
6314 if (InVec1.getOpcode() == ISD::UNDEF)
6315 InVec1 = Op1.getOperand(0);
6317 // Make sure that operands in input to each add/sub node always
6318 // come from a same pair of vectors.
6319 if (InVec0 != Op0.getOperand(0)) {
6320 if (ExpectedOpcode == ISD::FSUB)
6323 // FADD is commutable. Try to commute the operands
6324 // and then test again.
6325 std::swap(Op0, Op1);
6326 if (InVec0 != Op0.getOperand(0))
6330 if (InVec1 != Op1.getOperand(0))
6333 // Update the pair of expected opcodes.
6334 std::swap(ExpectedOpcode, NextExpectedOpcode);
6337 // Don't try to fold this build_vector into a VSELECT if it has
6338 // too many UNDEF operands.
6339 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6340 InVec1.getOpcode() != ISD::UNDEF) {
6341 // Emit a sequence of vector add and sub followed by a VSELECT.
6342 // The new VSELECT will be lowered into a BLENDI.
6343 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6344 // and emit a single ADDSUB instruction.
6345 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6346 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6348 // Construct the VSELECT mask.
6349 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6350 EVT SVT = MaskVT.getVectorElementType();
6351 unsigned SVTBits = SVT.getSizeInBits();
6352 SmallVector<SDValue, 8> Ops;
6354 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6355 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6356 APInt::getAllOnesValue(SVTBits);
6357 SDValue Constant = DAG.getConstant(Value, SVT);
6358 Ops.push_back(Constant);
6361 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6362 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6368 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6369 const X86Subtarget *Subtarget) {
6371 EVT VT = N->getValueType(0);
6372 unsigned NumElts = VT.getVectorNumElements();
6373 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6374 SDValue InVec0, InVec1;
6376 // Try to match an ADDSUB.
6377 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6378 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6379 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6380 if (Value.getNode())
6384 // Try to match horizontal ADD/SUB.
6385 unsigned NumUndefsLO = 0;
6386 unsigned NumUndefsHI = 0;
6387 unsigned Half = NumElts/2;
6389 // Count the number of UNDEF operands in the build_vector in input.
6390 for (unsigned i = 0, e = Half; i != e; ++i)
6391 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6394 for (unsigned i = Half, e = NumElts; i != e; ++i)
6395 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6398 // Early exit if this is either a build_vector of all UNDEFs or all the
6399 // operands but one are UNDEF.
6400 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6403 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6404 // Try to match an SSE3 float HADD/HSUB.
6405 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6406 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6408 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6409 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6410 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6411 // Try to match an SSSE3 integer HADD/HSUB.
6412 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6413 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6415 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6416 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6419 if (!Subtarget->hasAVX())
6422 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6423 // Try to match an AVX horizontal add/sub of packed single/double
6424 // precision floating point values from 256-bit vectors.
6425 SDValue InVec2, InVec3;
6426 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6427 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6428 ((InVec0.getOpcode() == ISD::UNDEF ||
6429 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6430 ((InVec1.getOpcode() == ISD::UNDEF ||
6431 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6432 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6434 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6435 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6436 ((InVec0.getOpcode() == ISD::UNDEF ||
6437 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6438 ((InVec1.getOpcode() == ISD::UNDEF ||
6439 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6440 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6441 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6442 // Try to match an AVX2 horizontal add/sub of signed integers.
6443 SDValue InVec2, InVec3;
6445 bool CanFold = true;
6447 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6448 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6449 ((InVec0.getOpcode() == ISD::UNDEF ||
6450 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6451 ((InVec1.getOpcode() == ISD::UNDEF ||
6452 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6453 X86Opcode = X86ISD::HADD;
6454 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6455 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6456 ((InVec0.getOpcode() == ISD::UNDEF ||
6457 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6458 ((InVec1.getOpcode() == ISD::UNDEF ||
6459 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6460 X86Opcode = X86ISD::HSUB;
6465 // Fold this build_vector into a single horizontal add/sub.
6466 // Do this only if the target has AVX2.
6467 if (Subtarget->hasAVX2())
6468 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6470 // Do not try to expand this build_vector into a pair of horizontal
6471 // add/sub if we can emit a pair of scalar add/sub.
6472 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6475 // Convert this build_vector into a pair of horizontal binop followed by
6477 bool isUndefLO = NumUndefsLO == Half;
6478 bool isUndefHI = NumUndefsHI == Half;
6479 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6480 isUndefLO, isUndefHI);
6484 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6485 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6487 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6488 X86Opcode = X86ISD::HADD;
6489 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6490 X86Opcode = X86ISD::HSUB;
6491 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6492 X86Opcode = X86ISD::FHADD;
6493 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6494 X86Opcode = X86ISD::FHSUB;
6498 // Don't try to expand this build_vector into a pair of horizontal add/sub
6499 // if we can simply emit a pair of scalar add/sub.
6500 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6503 // Convert this build_vector into two horizontal add/sub followed by
6505 bool isUndefLO = NumUndefsLO == Half;
6506 bool isUndefHI = NumUndefsHI == Half;
6507 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6508 isUndefLO, isUndefHI);
6515 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6518 MVT VT = Op.getSimpleValueType();
6519 MVT ExtVT = VT.getVectorElementType();
6520 unsigned NumElems = Op.getNumOperands();
6522 // Generate vectors for predicate vectors.
6523 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6524 return LowerBUILD_VECTORvXi1(Op, DAG);
6526 // Vectors containing all zeros can be matched by pxor and xorps later
6527 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6528 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6529 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6530 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6533 return getZeroVector(VT, Subtarget, DAG, dl);
6536 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6537 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6538 // vpcmpeqd on 256-bit vectors.
6539 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6540 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6543 if (!VT.is512BitVector())
6544 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6547 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6548 if (Broadcast.getNode())
6551 unsigned EVTBits = ExtVT.getSizeInBits();
6553 unsigned NumZero = 0;
6554 unsigned NumNonZero = 0;
6555 unsigned NonZeros = 0;
6556 bool IsAllConstants = true;
6557 SmallSet<SDValue, 8> Values;
6558 for (unsigned i = 0; i < NumElems; ++i) {
6559 SDValue Elt = Op.getOperand(i);
6560 if (Elt.getOpcode() == ISD::UNDEF)
6563 if (Elt.getOpcode() != ISD::Constant &&
6564 Elt.getOpcode() != ISD::ConstantFP)
6565 IsAllConstants = false;
6566 if (X86::isZeroNode(Elt))
6569 NonZeros |= (1 << i);
6574 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6575 if (NumNonZero == 0)
6576 return DAG.getUNDEF(VT);
6578 // Special case for single non-zero, non-undef, element.
6579 if (NumNonZero == 1) {
6580 unsigned Idx = countTrailingZeros(NonZeros);
6581 SDValue Item = Op.getOperand(Idx);
6583 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6584 // the value are obviously zero, truncate the value to i32 and do the
6585 // insertion that way. Only do this if the value is non-constant or if the
6586 // value is a constant being inserted into element 0. It is cheaper to do
6587 // a constant pool load than it is to do a movd + shuffle.
6588 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6589 (!IsAllConstants || Idx == 0)) {
6590 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6592 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6593 EVT VecVT = MVT::v4i32;
6594 unsigned VecElts = 4;
6596 // Truncate the value (which may itself be a constant) to i32, and
6597 // convert it to a vector with movd (S2V+shuffle to zero extend).
6598 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6599 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6600 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6602 // Now we have our 32-bit value zero extended in the low element of
6603 // a vector. If Idx != 0, swizzle it into place.
6605 SmallVector<int, 4> Mask;
6606 Mask.push_back(Idx);
6607 for (unsigned i = 1; i != VecElts; ++i)
6609 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6612 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6616 // If we have a constant or non-constant insertion into the low element of
6617 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6618 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6619 // depending on what the source datatype is.
6622 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6624 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6625 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6626 if (VT.is256BitVector() || VT.is512BitVector()) {
6627 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6628 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6629 Item, DAG.getIntPtrConstant(0));
6631 assert(VT.is128BitVector() && "Expected an SSE value type!");
6632 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6633 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6634 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6637 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6638 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6639 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6640 if (VT.is256BitVector()) {
6641 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6642 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6644 assert(VT.is128BitVector() && "Expected an SSE value type!");
6645 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6647 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6651 // Is it a vector logical left shift?
6652 if (NumElems == 2 && Idx == 1 &&
6653 X86::isZeroNode(Op.getOperand(0)) &&
6654 !X86::isZeroNode(Op.getOperand(1))) {
6655 unsigned NumBits = VT.getSizeInBits();
6656 return getVShift(true, VT,
6657 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6658 VT, Op.getOperand(1)),
6659 NumBits/2, DAG, *this, dl);
6662 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6665 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6666 // is a non-constant being inserted into an element other than the low one,
6667 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6668 // movd/movss) to move this into the low element, then shuffle it into
6670 if (EVTBits == 32) {
6671 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6673 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6674 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6675 SmallVector<int, 8> MaskVec;
6676 for (unsigned i = 0; i != NumElems; ++i)
6677 MaskVec.push_back(i == Idx ? 0 : 1);
6678 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6682 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6683 if (Values.size() == 1) {
6684 if (EVTBits == 32) {
6685 // Instead of a shuffle like this:
6686 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6687 // Check if it's possible to issue this instead.
6688 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6689 unsigned Idx = countTrailingZeros(NonZeros);
6690 SDValue Item = Op.getOperand(Idx);
6691 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6692 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6697 // A vector full of immediates; various special cases are already
6698 // handled, so this is best done with a single constant-pool load.
6702 // For AVX-length vectors, build the individual 128-bit pieces and use
6703 // shuffles to put them in place.
6704 if (VT.is256BitVector() || VT.is512BitVector()) {
6705 SmallVector<SDValue, 64> V;
6706 for (unsigned i = 0; i != NumElems; ++i)
6707 V.push_back(Op.getOperand(i));
6709 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6711 // Build both the lower and upper subvector.
6712 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6713 makeArrayRef(&V[0], NumElems/2));
6714 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6715 makeArrayRef(&V[NumElems / 2], NumElems/2));
6717 // Recreate the wider vector with the lower and upper part.
6718 if (VT.is256BitVector())
6719 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6720 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6723 // Let legalizer expand 2-wide build_vectors.
6724 if (EVTBits == 64) {
6725 if (NumNonZero == 1) {
6726 // One half is zero or undef.
6727 unsigned Idx = countTrailingZeros(NonZeros);
6728 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6729 Op.getOperand(Idx));
6730 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6735 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6736 if (EVTBits == 8 && NumElems == 16) {
6737 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6739 if (V.getNode()) return V;
6742 if (EVTBits == 16 && NumElems == 8) {
6743 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6745 if (V.getNode()) return V;
6748 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6749 if (EVTBits == 32 && NumElems == 4) {
6750 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6751 NumZero, DAG, Subtarget, *this);
6756 // If element VT is == 32 bits, turn it into a number of shuffles.
6757 SmallVector<SDValue, 8> V(NumElems);
6758 if (NumElems == 4 && NumZero > 0) {
6759 for (unsigned i = 0; i < 4; ++i) {
6760 bool isZero = !(NonZeros & (1 << i));
6762 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6764 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6767 for (unsigned i = 0; i < 2; ++i) {
6768 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6771 V[i] = V[i*2]; // Must be a zero vector.
6774 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6777 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6780 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6785 bool Reverse1 = (NonZeros & 0x3) == 2;
6786 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6790 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6791 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6793 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6796 if (Values.size() > 1 && VT.is128BitVector()) {
6797 // Check for a build vector of consecutive loads.
6798 for (unsigned i = 0; i < NumElems; ++i)
6799 V[i] = Op.getOperand(i);
6801 // Check for elements which are consecutive loads.
6802 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6806 // Check for a build vector from mostly shuffle plus few inserting.
6807 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6811 // For SSE 4.1, use insertps to put the high elements into the low element.
6812 if (getSubtarget()->hasSSE41()) {
6814 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6815 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6817 Result = DAG.getUNDEF(VT);
6819 for (unsigned i = 1; i < NumElems; ++i) {
6820 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6821 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6822 Op.getOperand(i), DAG.getIntPtrConstant(i));
6827 // Otherwise, expand into a number of unpckl*, start by extending each of
6828 // our (non-undef) elements to the full vector width with the element in the
6829 // bottom slot of the vector (which generates no code for SSE).
6830 for (unsigned i = 0; i < NumElems; ++i) {
6831 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6832 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6834 V[i] = DAG.getUNDEF(VT);
6837 // Next, we iteratively mix elements, e.g. for v4f32:
6838 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6839 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6840 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6841 unsigned EltStride = NumElems >> 1;
6842 while (EltStride != 0) {
6843 for (unsigned i = 0; i < EltStride; ++i) {
6844 // If V[i+EltStride] is undef and this is the first round of mixing,
6845 // then it is safe to just drop this shuffle: V[i] is already in the
6846 // right place, the one element (since it's the first round) being
6847 // inserted as undef can be dropped. This isn't safe for successive
6848 // rounds because they will permute elements within both vectors.
6849 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6850 EltStride == NumElems/2)
6853 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6862 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6863 // to create 256-bit vectors from two other 128-bit ones.
6864 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6866 MVT ResVT = Op.getSimpleValueType();
6868 assert((ResVT.is256BitVector() ||
6869 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6871 SDValue V1 = Op.getOperand(0);
6872 SDValue V2 = Op.getOperand(1);
6873 unsigned NumElems = ResVT.getVectorNumElements();
6874 if(ResVT.is256BitVector())
6875 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6877 if (Op.getNumOperands() == 4) {
6878 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6879 ResVT.getVectorNumElements()/2);
6880 SDValue V3 = Op.getOperand(2);
6881 SDValue V4 = Op.getOperand(3);
6882 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6883 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6885 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6888 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6889 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6890 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6891 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6892 Op.getNumOperands() == 4)));
6894 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6895 // from two other 128-bit ones.
6897 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6898 return LowerAVXCONCAT_VECTORS(Op, DAG);
6902 //===----------------------------------------------------------------------===//
6903 // Vector shuffle lowering
6905 // This is an experimental code path for lowering vector shuffles on x86. It is
6906 // designed to handle arbitrary vector shuffles and blends, gracefully
6907 // degrading performance as necessary. It works hard to recognize idiomatic
6908 // shuffles and lower them to optimal instruction patterns without leaving
6909 // a framework that allows reasonably efficient handling of all vector shuffle
6911 //===----------------------------------------------------------------------===//
6913 /// \brief Tiny helper function to identify a no-op mask.
6915 /// This is a somewhat boring predicate function. It checks whether the mask
6916 /// array input, which is assumed to be a single-input shuffle mask of the kind
6917 /// used by the X86 shuffle instructions (not a fully general
6918 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6919 /// in-place shuffle are 'no-op's.
6920 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6921 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6922 if (Mask[i] != -1 && Mask[i] != i)
6927 /// \brief Helper function to classify a mask as a single-input mask.
6929 /// This isn't a generic single-input test because in the vector shuffle
6930 /// lowering we canonicalize single inputs to be the first input operand. This
6931 /// means we can more quickly test for a single input by only checking whether
6932 /// an input from the second operand exists. We also assume that the size of
6933 /// mask corresponds to the size of the input vectors which isn't true in the
6934 /// fully general case.
6935 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6937 if (M >= (int)Mask.size())
6942 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6944 /// This helper function produces an 8-bit shuffle immediate corresponding to
6945 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6946 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6949 /// NB: We rely heavily on "undef" masks preserving the input lane.
6950 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6951 SelectionDAG &DAG) {
6952 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6953 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6954 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6955 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6956 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6959 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6960 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6961 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6962 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6963 return DAG.getConstant(Imm, MVT::i8);
6966 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6968 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6969 /// support for floating point shuffles but not integer shuffles. These
6970 /// instructions will incur a domain crossing penalty on some chips though so
6971 /// it is better to avoid lowering through this for integer vectors where
6973 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6974 const X86Subtarget *Subtarget,
6975 SelectionDAG &DAG) {
6977 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6978 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6979 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6980 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6981 ArrayRef<int> Mask = SVOp->getMask();
6982 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6984 if (isSingleInputShuffleMask(Mask)) {
6985 // Straight shuffle of a single input vector. Simulate this by using the
6986 // single input as both of the "inputs" to this instruction..
6987 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6988 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6989 DAG.getConstant(SHUFPDMask, MVT::i8));
6991 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6992 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6994 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6995 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6996 DAG.getConstant(SHUFPDMask, MVT::i8));
6999 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7001 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7002 /// the integer unit to minimize domain crossing penalties. However, for blends
7003 /// it falls back to the floating point shuffle operation with appropriate bit
7005 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7006 const X86Subtarget *Subtarget,
7007 SelectionDAG &DAG) {
7009 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7010 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7011 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7012 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7013 ArrayRef<int> Mask = SVOp->getMask();
7014 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7016 if (isSingleInputShuffleMask(Mask)) {
7017 // Straight shuffle of a single input vector. For everything from SSE2
7018 // onward this has a single fast instruction with no scary immediates.
7019 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7020 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7021 int WidenedMask[4] = {
7022 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7023 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7025 ISD::BITCAST, DL, MVT::v2i64,
7026 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7027 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7030 // We implement this with SHUFPD which is pretty lame because it will likely
7031 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7032 // However, all the alternatives are still more cycles and newer chips don't
7033 // have this problem. It would be really nice if x86 had better shuffles here.
7034 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7035 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7036 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7037 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7040 /// \brief Lower 4-lane 32-bit floating point shuffles.
7042 /// Uses instructions exclusively from the floating point unit to minimize
7043 /// domain crossing penalties, as these are sufficient to implement all v4f32
7045 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7046 const X86Subtarget *Subtarget,
7047 SelectionDAG &DAG) {
7049 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7050 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7051 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7052 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7053 ArrayRef<int> Mask = SVOp->getMask();
7054 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7056 SDValue LowV = V1, HighV = V2;
7057 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7060 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7062 if (NumV2Elements == 0)
7063 // Straight shuffle of a single input vector. We pass the input vector to
7064 // both operands to simulate this with a SHUFPS.
7065 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7066 getV4X86ShuffleImm8ForMask(Mask, DAG));
7068 if (NumV2Elements == 1) {
7070 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7072 // Compute the index adjacent to V2Index and in the same half by toggling
7074 int V2AdjIndex = V2Index ^ 1;
7076 if (Mask[V2AdjIndex] == -1) {
7077 // Handles all the cases where we have a single V2 element and an undef.
7078 // This will only ever happen in the high lanes because we commute the
7079 // vector otherwise.
7081 std::swap(LowV, HighV);
7082 NewMask[V2Index] -= 4;
7084 // Handle the case where the V2 element ends up adjacent to a V1 element.
7085 // To make this work, blend them together as the first step.
7086 int V1Index = V2AdjIndex;
7087 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7088 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7089 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7091 // Now proceed to reconstruct the final blend as we have the necessary
7092 // high or low half formed.
7099 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7100 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7102 } else if (NumV2Elements == 2) {
7103 if (Mask[0] < 4 && Mask[1] < 4) {
7104 // Handle the easy case where we have V1 in the low lanes and V2 in the
7105 // high lanes. We never see this reversed because we sort the shuffle.
7109 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7110 // trying to place elements directly, just blend them and set up the final
7111 // shuffle to place them.
7113 // The first two blend mask elements are for V1, the second two are for
7115 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7116 Mask[2] < 4 ? Mask[2] : Mask[3],
7117 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7118 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7119 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7120 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7122 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7125 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7126 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7127 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7128 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7131 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7132 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7135 /// \brief Lower 4-lane i32 vector shuffles.
7137 /// We try to handle these with integer-domain shuffles where we can, but for
7138 /// blends we use the floating point domain blend instructions.
7139 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7140 const X86Subtarget *Subtarget,
7141 SelectionDAG &DAG) {
7143 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7144 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7145 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7146 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7147 ArrayRef<int> Mask = SVOp->getMask();
7148 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7150 if (isSingleInputShuffleMask(Mask))
7151 // Straight shuffle of a single input vector. For everything from SSE2
7152 // onward this has a single fast instruction with no scary immediates.
7153 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7154 getV4X86ShuffleImm8ForMask(Mask, DAG));
7156 // We implement this with SHUFPS because it can blend from two vectors.
7157 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7158 // up the inputs, bypassing domain shift penalties that we would encur if we
7159 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7161 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7162 DAG.getVectorShuffle(
7164 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7165 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7168 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7169 /// shuffle lowering, and the most complex part.
7171 /// The lowering strategy is to try to form pairs of input lanes which are
7172 /// targeted at the same half of the final vector, and then use a dword shuffle
7173 /// to place them onto the right half, and finally unpack the paired lanes into
7174 /// their final position.
7176 /// The exact breakdown of how to form these dword pairs and align them on the
7177 /// correct sides is really tricky. See the comments within the function for
7178 /// more of the details.
7179 static SDValue lowerV8I16SingleInputVectorShuffle(
7180 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7181 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7182 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7183 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7184 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7186 SmallVector<int, 4> LoInputs;
7187 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7188 [](int M) { return M >= 0; });
7189 std::sort(LoInputs.begin(), LoInputs.end());
7190 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7191 SmallVector<int, 4> HiInputs;
7192 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7193 [](int M) { return M >= 0; });
7194 std::sort(HiInputs.begin(), HiInputs.end());
7195 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7197 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7198 int NumHToL = LoInputs.size() - NumLToL;
7200 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7201 int NumHToH = HiInputs.size() - NumLToH;
7202 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7203 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7204 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7205 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7207 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7208 // such inputs we can swap two of the dwords across the half mark and end up
7209 // with <=2 inputs to each half in each half. Once there, we can fall through
7210 // to the generic code below. For example:
7212 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7213 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7215 // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7217 auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7218 int ThreeInputHalfSum, int OneInputHalfOffset) {
7219 // Compute the index of dword with only one word among the three inputs in
7220 // a half by taking the sum of the half with three inputs and subtracting
7221 // the sum of the actual three inputs. The difference is the remaining
7223 int DWordA = (ThreeInputHalfSum -
7224 std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7226 int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7228 int PSHUFDMask[] = {0, 1, 2, 3};
7229 PSHUFDMask[DWordA] = DWordB;
7230 PSHUFDMask[DWordB] = DWordA;
7231 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7232 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7233 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7234 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7236 // Adjust the mask to match the new locations of A and B.
7238 if (M != -1 && M/2 == DWordA)
7239 M = 2 * DWordB + M % 2;
7240 else if (M != -1 && M/2 == DWordB)
7241 M = 2 * DWordA + M % 2;
7243 // Recurse back into this routine to re-compute state now that this isn't
7244 // a 3 and 1 problem.
7245 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7248 if (NumLToL == 3 && NumHToL == 1)
7249 return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7250 else if (NumLToL == 1 && NumHToL == 3)
7251 return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7252 else if (NumLToH == 1 && NumHToH == 3)
7253 return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7254 else if (NumLToH == 3 && NumHToH == 1)
7255 return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7257 // At this point there are at most two inputs to the low and high halves from
7258 // each half. That means the inputs can always be grouped into dwords and
7259 // those dwords can then be moved to the correct half with a dword shuffle.
7260 // We use at most one low and one high word shuffle to collect these paired
7261 // inputs into dwords, and finally a dword shuffle to place them.
7262 int PSHUFLMask[4] = {-1, -1, -1, -1};
7263 int PSHUFHMask[4] = {-1, -1, -1, -1};
7264 int PSHUFDMask[4] = {-1, -1, -1, -1};
7266 // First fix the masks for all the inputs that are staying in their
7267 // original halves. This will then dictate the targets of the cross-half
7269 auto fixInPlaceInputs = [&PSHUFDMask](
7270 ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7271 MutableArrayRef<int> HalfMask, int HalfOffset) {
7272 if (InPlaceInputs.empty())
7274 if (InPlaceInputs.size() == 1) {
7275 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7276 InPlaceInputs[0] - HalfOffset;
7277 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7281 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7282 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7283 InPlaceInputs[0] - HalfOffset;
7284 // Put the second input next to the first so that they are packed into
7285 // a dword. We find the adjacent index by toggling the low bit.
7286 int AdjIndex = InPlaceInputs[0] ^ 1;
7287 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7288 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7289 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7291 if (!HToLInputs.empty())
7292 fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7293 if (!LToHInputs.empty())
7294 fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7296 // Now gather the cross-half inputs and place them into a free dword of
7297 // their target half.
7298 // FIXME: This operation could almost certainly be simplified dramatically to
7299 // look more like the 3-1 fixing operation.
7300 auto moveInputsToRightHalf = [&PSHUFDMask](
7301 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7302 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7303 int SourceOffset, int DestOffset) {
7304 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7305 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7307 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7309 int LowWord = Word & ~1;
7310 int HighWord = Word | 1;
7311 return isWordClobbered(SourceHalfMask, LowWord) ||
7312 isWordClobbered(SourceHalfMask, HighWord);
7315 if (IncomingInputs.empty())
7318 if (ExistingInputs.empty()) {
7319 // Map any dwords with inputs from them into the right half.
7320 for (int Input : IncomingInputs) {
7321 // If the source half mask maps over the inputs, turn those into
7322 // swaps and use the swapped lane.
7323 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7324 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7325 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7326 Input - SourceOffset;
7327 // We have to swap the uses in our half mask in one sweep.
7328 for (int &M : HalfMask)
7329 if (M == SourceHalfMask[Input - SourceOffset])
7331 else if (M == Input)
7332 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7334 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7335 Input - SourceOffset &&
7336 "Previous placement doesn't match!");
7338 // Note that this correctly re-maps both when we do a swap and when
7339 // we observe the other side of the swap above. We rely on that to
7340 // avoid swapping the members of the input list directly.
7341 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7344 // Map the input's dword into the correct half.
7345 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7346 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7348 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7350 "Previous placement doesn't match!");
7353 // And just directly shift any other-half mask elements to be same-half
7354 // as we will have mirrored the dword containing the element into the
7355 // same position within that half.
7356 for (int &M : HalfMask)
7357 if (M >= SourceOffset && M < SourceOffset + 4) {
7358 M = M - SourceOffset + DestOffset;
7359 assert(M >= 0 && "This should never wrap below zero!");
7364 // Ensure we have the input in a viable dword of its current half. This
7365 // is particularly tricky because the original position may be clobbered
7366 // by inputs being moved and *staying* in that half.
7367 if (IncomingInputs.size() == 1) {
7368 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7369 int InputFixed = std::find(std::begin(SourceHalfMask),
7370 std::end(SourceHalfMask), -1) -
7371 std::begin(SourceHalfMask) + SourceOffset;
7372 SourceHalfMask[InputFixed - SourceOffset] =
7373 IncomingInputs[0] - SourceOffset;
7374 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7376 IncomingInputs[0] = InputFixed;
7378 } else if (IncomingInputs.size() == 2) {
7379 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7380 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7381 int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7382 assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7383 "Not all dwords can be clobbered!");
7384 SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7385 SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7386 for (int &M : HalfMask)
7387 if (M == IncomingInputs[0])
7388 M = SourceDWordBase + SourceOffset;
7389 else if (M == IncomingInputs[1])
7390 M = SourceDWordBase + 1 + SourceOffset;
7391 IncomingInputs[0] = SourceDWordBase + SourceOffset;
7392 IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7395 llvm_unreachable("Unhandled input size!");
7398 // Now hoist the DWord down to the right half.
7399 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7400 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7401 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7402 for (int Input : IncomingInputs)
7403 std::replace(HalfMask.begin(), HalfMask.end(), Input,
7404 FreeDWord * 2 + Input % 2);
7406 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7407 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7408 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7409 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7411 // Now enact all the shuffles we've computed to move the inputs into their
7413 if (!isNoopShuffleMask(PSHUFLMask))
7414 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7415 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7416 if (!isNoopShuffleMask(PSHUFHMask))
7417 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7418 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7419 if (!isNoopShuffleMask(PSHUFDMask))
7420 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7421 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7422 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7423 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7425 // At this point, each half should contain all its inputs, and we can then
7426 // just shuffle them into their final position.
7427 assert(std::count_if(LoMask.begin(), LoMask.end(),
7428 [](int M) { return M >= 4; }) == 0 &&
7429 "Failed to lift all the high half inputs to the low mask!");
7430 assert(std::count_if(HiMask.begin(), HiMask.end(),
7431 [](int M) { return M >= 0 && M < 4; }) == 0 &&
7432 "Failed to lift all the low half inputs to the high mask!");
7434 // Do a half shuffle for the low mask.
7435 if (!isNoopShuffleMask(LoMask))
7436 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7437 getV4X86ShuffleImm8ForMask(LoMask, DAG));
7439 // Do a half shuffle with the high mask after shifting its values down.
7440 for (int &M : HiMask)
7443 if (!isNoopShuffleMask(HiMask))
7444 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7445 getV4X86ShuffleImm8ForMask(HiMask, DAG));
7450 /// \brief Detect whether the mask pattern should be lowered through
7453 /// This essentially tests whether viewing the mask as an interleaving of two
7454 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7455 /// lowering it through interleaving is a significantly better strategy.
7456 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7457 int NumEvenInputs[2] = {0, 0};
7458 int NumOddInputs[2] = {0, 0};
7459 int NumLoInputs[2] = {0, 0};
7460 int NumHiInputs[2] = {0, 0};
7461 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7465 int InputIdx = Mask[i] >= Size;
7468 ++NumLoInputs[InputIdx];
7470 ++NumHiInputs[InputIdx];
7473 ++NumEvenInputs[InputIdx];
7475 ++NumOddInputs[InputIdx];
7478 // The minimum number of cross-input results for both the interleaved and
7479 // split cases. If interleaving results in fewer cross-input results, return
7481 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7482 NumEvenInputs[0] + NumOddInputs[1]);
7483 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7484 NumLoInputs[0] + NumHiInputs[1]);
7485 return InterleavedCrosses < SplitCrosses;
7488 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7490 /// This strategy only works when the inputs from each vector fit into a single
7491 /// half of that vector, and generally there are not so many inputs as to leave
7492 /// the in-place shuffles required highly constrained (and thus expensive). It
7493 /// shifts all the inputs into a single side of both input vectors and then
7494 /// uses an unpack to interleave these inputs in a single vector. At that
7495 /// point, we will fall back on the generic single input shuffle lowering.
7496 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7498 MutableArrayRef<int> Mask,
7499 const X86Subtarget *Subtarget,
7500 SelectionDAG &DAG) {
7501 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7502 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7503 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7504 for (int i = 0; i < 8; ++i)
7505 if (Mask[i] >= 0 && Mask[i] < 4)
7506 LoV1Inputs.push_back(i);
7507 else if (Mask[i] >= 4 && Mask[i] < 8)
7508 HiV1Inputs.push_back(i);
7509 else if (Mask[i] >= 8 && Mask[i] < 12)
7510 LoV2Inputs.push_back(i);
7511 else if (Mask[i] >= 12)
7512 HiV2Inputs.push_back(i);
7514 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7515 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7518 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7519 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7520 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7522 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7523 HiV1Inputs.size() + HiV2Inputs.size();
7525 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7526 ArrayRef<int> HiInputs, bool MoveToLo,
7528 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7529 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7530 if (BadInputs.empty())
7533 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7534 int MoveOffset = MoveToLo ? 0 : 4;
7536 if (GoodInputs.empty()) {
7537 for (int BadInput : BadInputs) {
7538 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7539 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7542 if (GoodInputs.size() == 2) {
7543 // If the low inputs are spread across two dwords, pack them into
7545 MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7546 Mask[GoodInputs[0]] - MaskOffset;
7547 MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7548 Mask[GoodInputs[1]] - MaskOffset;
7549 Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7550 Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7552 // Otherwise pin the low inputs.
7553 for (int GoodInput : GoodInputs)
7554 MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7558 std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7559 std::begin(MoveMask);
7560 assert(MoveMaskIdx >= MoveOffset && "Established above");
7562 if (BadInputs.size() == 2) {
7563 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7564 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7565 MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7566 Mask[BadInputs[0]] - MaskOffset;
7567 MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7568 Mask[BadInputs[1]] - MaskOffset;
7569 Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7570 Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7572 assert(BadInputs.size() == 1 && "All sizes handled");
7573 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7574 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7578 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7581 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7583 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7586 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7587 // cross-half traffic in the final shuffle.
7589 // Munge the mask to be a single-input mask after the unpack merges the
7593 M = 2 * (M % 4) + (M / 8);
7595 return DAG.getVectorShuffle(
7596 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7597 DL, MVT::v8i16, V1, V2),
7598 DAG.getUNDEF(MVT::v8i16), Mask);
7601 /// \brief Generic lowering of 8-lane i16 shuffles.
7603 /// This handles both single-input shuffles and combined shuffle/blends with
7604 /// two inputs. The single input shuffles are immediately delegated to
7605 /// a dedicated lowering routine.
7607 /// The blends are lowered in one of three fundamental ways. If there are few
7608 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7609 /// of the input is significantly cheaper when lowered as an interleaving of
7610 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7611 /// halves of the inputs separately (making them have relatively few inputs)
7612 /// and then concatenate them.
7613 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7614 const X86Subtarget *Subtarget,
7615 SelectionDAG &DAG) {
7617 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7618 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7619 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7620 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7621 ArrayRef<int> OrigMask = SVOp->getMask();
7622 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7623 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7624 MutableArrayRef<int> Mask(MaskStorage);
7626 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7628 auto isV1 = [](int M) { return M >= 0 && M < 8; };
7629 auto isV2 = [](int M) { return M >= 8; };
7631 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7632 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7634 if (NumV2Inputs == 0)
7635 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7637 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7638 "to be V1-input shuffles.");
7640 if (NumV1Inputs + NumV2Inputs <= 4)
7641 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7643 // Check whether an interleaving lowering is likely to be more efficient.
7644 // This isn't perfect but it is a strong heuristic that tends to work well on
7645 // the kinds of shuffles that show up in practice.
7647 // FIXME: Handle 1x, 2x, and 4x interleaving.
7648 if (shouldLowerAsInterleaving(Mask)) {
7649 // FIXME: Figure out whether we should pack these into the low or high
7652 int EMask[8], OMask[8];
7653 for (int i = 0; i < 4; ++i) {
7654 EMask[i] = Mask[2*i];
7655 OMask[i] = Mask[2*i + 1];
7660 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7661 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7663 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7666 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7667 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7669 for (int i = 0; i < 4; ++i) {
7670 LoBlendMask[i] = Mask[i];
7671 HiBlendMask[i] = Mask[i + 4];
7674 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7675 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7676 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7677 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7679 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7680 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7683 /// \brief Generic lowering of v16i8 shuffles.
7685 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7686 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7687 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7688 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7690 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7691 const X86Subtarget *Subtarget,
7692 SelectionDAG &DAG) {
7694 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7695 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7696 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7697 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7698 ArrayRef<int> OrigMask = SVOp->getMask();
7699 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7700 int MaskStorage[16] = {
7701 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7702 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
7703 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
7704 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7705 MutableArrayRef<int> Mask(MaskStorage);
7706 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7707 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7709 // For single-input shuffles, there are some nicer lowering tricks we can use.
7710 if (isSingleInputShuffleMask(Mask)) {
7711 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7712 // Notably, this handles splat and partial-splat shuffles more efficiently.
7713 // However, it only makes sense if the pre-duplication shuffle simplifies
7714 // things significantly. Currently, this means we need to be able to
7715 // express the pre-duplication shuffle as an i16 shuffle.
7717 // FIXME: We should check for other patterns which can be widened into an
7718 // i16 shuffle as well.
7719 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7720 for (int i = 0; i < 16; i += 2) {
7721 if (Mask[i] != Mask[i + 1])
7726 auto tryToWidenViaDuplication = [&]() -> SDValue {
7727 if (!canWidenViaDuplication(Mask))
7729 SmallVector<int, 4> LoInputs;
7730 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7731 [](int M) { return M >= 0 && M < 8; });
7732 std::sort(LoInputs.begin(), LoInputs.end());
7733 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7735 SmallVector<int, 4> HiInputs;
7736 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7737 [](int M) { return M >= 8; });
7738 std::sort(HiInputs.begin(), HiInputs.end());
7739 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7742 bool TargetLo = LoInputs.size() >= HiInputs.size();
7743 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7744 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7746 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7747 SmallDenseMap<int, int, 8> LaneMap;
7748 for (int I : InPlaceInputs) {
7749 PreDupI16Shuffle[I/2] = I/2;
7752 int j = TargetLo ? 0 : 4, je = j + 4;
7753 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7754 // Check if j is already a shuffle of this input. This happens when
7755 // there are two adjacent bytes after we move the low one.
7756 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7757 // If we haven't yet mapped the input, search for a slot into which
7759 while (j < je && PreDupI16Shuffle[j] != -1)
7763 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7766 // Map this input with the i16 shuffle.
7767 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7770 // Update the lane map based on the mapping we ended up with.
7771 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7774 ISD::BITCAST, DL, MVT::v16i8,
7775 DAG.getVectorShuffle(MVT::v8i16, DL,
7776 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7777 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
7779 // Unpack the bytes to form the i16s that will be shuffled into place.
7780 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7781 MVT::v16i8, V1, V1);
7783 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7784 for (int i = 0; i < 16; i += 2) {
7786 PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7787 assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7790 ISD::BITCAST, DL, MVT::v16i8,
7791 DAG.getVectorShuffle(MVT::v8i16, DL,
7792 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7793 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7795 if (SDValue V = tryToWidenViaDuplication())
7799 // Check whether an interleaving lowering is likely to be more efficient.
7800 // This isn't perfect but it is a strong heuristic that tends to work well on
7801 // the kinds of shuffles that show up in practice.
7803 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7804 if (shouldLowerAsInterleaving(Mask)) {
7805 // FIXME: Figure out whether we should pack these into the low or high
7808 int EMask[16], OMask[16];
7809 for (int i = 0; i < 8; ++i) {
7810 EMask[i] = Mask[2*i];
7811 OMask[i] = Mask[2*i + 1];
7816 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7817 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7819 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7822 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7823 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7824 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7825 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7827 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7828 MutableArrayRef<int> V1HalfBlendMask,
7829 MutableArrayRef<int> V2HalfBlendMask) {
7830 for (int i = 0; i < 8; ++i)
7831 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7832 V1HalfBlendMask[i] = HalfMask[i];
7834 } else if (HalfMask[i] >= 16) {
7835 V2HalfBlendMask[i] = HalfMask[i] - 16;
7836 HalfMask[i] = i + 8;
7839 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7840 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7842 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7844 auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
7845 MutableArrayRef<int> HiBlendMask) {
7847 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
7848 // them out and avoid using UNPCK{L,H} to extract the elements of V as
7850 if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
7851 [](int M) { return M >= 0 && M % 2 == 1; }) &&
7852 std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
7853 [](int M) { return M >= 0 && M % 2 == 1; })) {
7854 // Use a mask to drop the high bytes.
7855 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
7856 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
7857 DAG.getConstant(0x00FF, MVT::v8i16));
7859 // This will be a single vector shuffle instead of a blend so nuke V2.
7860 V2 = DAG.getUNDEF(MVT::v8i16);
7862 // Squash the masks to point directly into V1.
7863 for (int &M : LoBlendMask)
7866 for (int &M : HiBlendMask)
7870 // Otherwise just unpack the low half of V into V1 and the high half into
7871 // V2 so that we can blend them as i16s.
7872 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7873 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
7874 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7875 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
7878 SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7879 SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7880 return std::make_pair(BlendedLo, BlendedHi);
7882 SDValue V1Lo, V1Hi, V2Lo, V2Hi;
7883 std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
7884 std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
7886 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7887 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7889 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7892 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7894 /// This routine breaks down the specific type of 128-bit shuffle and
7895 /// dispatches to the lowering routines accordingly.
7896 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7897 MVT VT, const X86Subtarget *Subtarget,
7898 SelectionDAG &DAG) {
7899 switch (VT.SimpleTy) {
7901 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7903 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7905 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7907 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7909 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7911 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7914 llvm_unreachable("Unimplemented!");
7918 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7919 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7920 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7921 if (Mask[i] + 1 != Mask[i+1])
7927 /// \brief Top-level lowering for x86 vector shuffles.
7929 /// This handles decomposition, canonicalization, and lowering of all x86
7930 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7931 /// above in helper routines. The canonicalization attempts to widen shuffles
7932 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7933 /// s.t. only one of the two inputs needs to be tested, etc.
7934 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7935 SelectionDAG &DAG) {
7936 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7937 ArrayRef<int> Mask = SVOp->getMask();
7938 SDValue V1 = Op.getOperand(0);
7939 SDValue V2 = Op.getOperand(1);
7940 MVT VT = Op.getSimpleValueType();
7941 int NumElements = VT.getVectorNumElements();
7944 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7946 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7947 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7948 if (V1IsUndef && V2IsUndef)
7949 return DAG.getUNDEF(VT);
7951 // When we create a shuffle node we put the UNDEF node to second operand,
7952 // but in some cases the first operand may be transformed to UNDEF.
7953 // In this case we should just commute the node.
7955 return CommuteVectorShuffle(SVOp, DAG);
7957 // Check for non-undef masks pointing at an undef vector and make the masks
7958 // undef as well. This makes it easier to match the shuffle based solely on
7962 if (M >= NumElements) {
7963 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7964 for (int &M : NewMask)
7965 if (M >= NumElements)
7967 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7970 // For integer vector shuffles, try to collapse them into a shuffle of fewer
7971 // lanes but wider integers. We cap this to not form integers larger than i64
7972 // but it might be interesting to form i128 integers to handle flipping the
7973 // low and high halves of AVX 256-bit vectors.
7974 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7975 areAdjacentMasksSequential(Mask)) {
7976 SmallVector<int, 8> NewMask;
7977 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7978 NewMask.push_back(Mask[i] / 2);
7980 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7981 VT.getVectorNumElements() / 2);
7982 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7983 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7984 return DAG.getNode(ISD::BITCAST, dl, VT,
7985 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7988 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7989 for (int M : SVOp->getMask())
7992 else if (M < NumElements)
7997 // Commute the shuffle as needed such that more elements come from V1 than
7998 // V2. This allows us to match the shuffle pattern strictly on how many
7999 // elements come from V1 without handling the symmetric cases.
8000 if (NumV2Elements > NumV1Elements)
8001 return CommuteVectorShuffle(SVOp, DAG);
8003 // When the number of V1 and V2 elements are the same, try to minimize the
8004 // number of uses of V2 in the low half of the vector.
8005 if (NumV1Elements == NumV2Elements) {
8006 int LowV1Elements = 0, LowV2Elements = 0;
8007 for (int M : SVOp->getMask().slice(0, NumElements / 2))
8008 if (M >= NumElements)
8012 if (LowV2Elements > LowV1Elements)
8013 return CommuteVectorShuffle(SVOp, DAG);
8016 // For each vector width, delegate to a specialized lowering routine.
8017 if (VT.getSizeInBits() == 128)
8018 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8020 llvm_unreachable("Unimplemented!");
8024 //===----------------------------------------------------------------------===//
8025 // Legacy vector shuffle lowering
8027 // This code is the legacy code handling vector shuffles until the above
8028 // replaces its functionality and performance.
8029 //===----------------------------------------------------------------------===//
8031 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8032 bool hasInt256, unsigned *MaskOut = nullptr) {
8033 MVT EltVT = VT.getVectorElementType();
8035 // There is no blend with immediate in AVX-512.
8036 if (VT.is512BitVector())
8039 if (!hasSSE41 || EltVT == MVT::i8)
8041 if (!hasInt256 && VT == MVT::v16i16)
8044 unsigned MaskValue = 0;
8045 unsigned NumElems = VT.getVectorNumElements();
8046 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8047 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8048 unsigned NumElemsInLane = NumElems / NumLanes;
8050 // Blend for v16i16 should be symetric for the both lanes.
8051 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8053 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8054 int EltIdx = MaskVals[i];
8056 if ((EltIdx < 0 || EltIdx == (int)i) &&
8057 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8060 if (((unsigned)EltIdx == (i + NumElems)) &&
8061 (SndLaneEltIdx < 0 ||
8062 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8063 MaskValue |= (1 << i);
8069 *MaskOut = MaskValue;
8073 // Try to lower a shuffle node into a simple blend instruction.
8074 // This function assumes isBlendMask returns true for this
8075 // SuffleVectorSDNode
8076 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8078 const X86Subtarget *Subtarget,
8079 SelectionDAG &DAG) {
8080 MVT VT = SVOp->getSimpleValueType(0);
8081 MVT EltVT = VT.getVectorElementType();
8082 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8083 Subtarget->hasInt256() && "Trying to lower a "
8084 "VECTOR_SHUFFLE to a Blend but "
8085 "with the wrong mask"));
8086 SDValue V1 = SVOp->getOperand(0);
8087 SDValue V2 = SVOp->getOperand(1);
8089 unsigned NumElems = VT.getVectorNumElements();
8091 // Convert i32 vectors to floating point if it is not AVX2.
8092 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8094 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8095 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8097 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8098 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8101 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8102 DAG.getConstant(MaskValue, MVT::i32));
8103 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8106 /// In vector type \p VT, return true if the element at index \p InputIdx
8107 /// falls on a different 128-bit lane than \p OutputIdx.
8108 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8109 unsigned OutputIdx) {
8110 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8111 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8114 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
8115 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
8116 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
8117 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8119 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8120 SelectionDAG &DAG) {
8121 MVT VT = V1.getSimpleValueType();
8122 assert(VT.is128BitVector() || VT.is256BitVector());
8124 MVT EltVT = VT.getVectorElementType();
8125 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8126 unsigned NumElts = VT.getVectorNumElements();
8128 SmallVector<SDValue, 32> PshufbMask;
8129 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8130 int InputIdx = MaskVals[OutputIdx];
8131 unsigned InputByteIdx;
8133 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8134 InputByteIdx = 0x80;
8136 // Cross lane is not allowed.
8137 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8139 InputByteIdx = InputIdx * EltSizeInBytes;
8140 // Index is an byte offset within the 128-bit lane.
8141 InputByteIdx &= 0xf;
8144 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8145 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8146 if (InputByteIdx != 0x80)
8151 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8153 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8154 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8155 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8158 // v8i16 shuffles - Prefer shuffles in the following order:
8159 // 1. [all] pshuflw, pshufhw, optional move
8160 // 2. [ssse3] 1 x pshufb
8161 // 3. [ssse3] 2 x pshufb + 1 x por
8162 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8164 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8165 SelectionDAG &DAG) {
8166 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8167 SDValue V1 = SVOp->getOperand(0);
8168 SDValue V2 = SVOp->getOperand(1);
8170 SmallVector<int, 8> MaskVals;
8172 // Determine if more than 1 of the words in each of the low and high quadwords
8173 // of the result come from the same quadword of one of the two inputs. Undef
8174 // mask values count as coming from any quadword, for better codegen.
8176 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8177 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8178 unsigned LoQuad[] = { 0, 0, 0, 0 };
8179 unsigned HiQuad[] = { 0, 0, 0, 0 };
8180 // Indices of quads used.
8181 std::bitset<4> InputQuads;
8182 for (unsigned i = 0; i < 8; ++i) {
8183 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8184 int EltIdx = SVOp->getMaskElt(i);
8185 MaskVals.push_back(EltIdx);
8194 InputQuads.set(EltIdx / 4);
8197 int BestLoQuad = -1;
8198 unsigned MaxQuad = 1;
8199 for (unsigned i = 0; i < 4; ++i) {
8200 if (LoQuad[i] > MaxQuad) {
8202 MaxQuad = LoQuad[i];
8206 int BestHiQuad = -1;
8208 for (unsigned i = 0; i < 4; ++i) {
8209 if (HiQuad[i] > MaxQuad) {
8211 MaxQuad = HiQuad[i];
8215 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8216 // of the two input vectors, shuffle them into one input vector so only a
8217 // single pshufb instruction is necessary. If there are more than 2 input
8218 // quads, disable the next transformation since it does not help SSSE3.
8219 bool V1Used = InputQuads[0] || InputQuads[1];
8220 bool V2Used = InputQuads[2] || InputQuads[3];
8221 if (Subtarget->hasSSSE3()) {
8222 if (InputQuads.count() == 2 && V1Used && V2Used) {
8223 BestLoQuad = InputQuads[0] ? 0 : 1;
8224 BestHiQuad = InputQuads[2] ? 2 : 3;
8226 if (InputQuads.count() > 2) {
8232 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8233 // the shuffle mask. If a quad is scored as -1, that means that it contains
8234 // words from all 4 input quadwords.
8236 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8238 BestLoQuad < 0 ? 0 : BestLoQuad,
8239 BestHiQuad < 0 ? 1 : BestHiQuad
8241 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8242 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8243 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8244 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8246 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8247 // source words for the shuffle, to aid later transformations.
8248 bool AllWordsInNewV = true;
8249 bool InOrder[2] = { true, true };
8250 for (unsigned i = 0; i != 8; ++i) {
8251 int idx = MaskVals[i];
8253 InOrder[i/4] = false;
8254 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8256 AllWordsInNewV = false;
8260 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8261 if (AllWordsInNewV) {
8262 for (int i = 0; i != 8; ++i) {
8263 int idx = MaskVals[i];
8266 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8267 if ((idx != i) && idx < 4)
8269 if ((idx != i) && idx > 3)
8278 // If we've eliminated the use of V2, and the new mask is a pshuflw or
8279 // pshufhw, that's as cheap as it gets. Return the new shuffle.
8280 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8281 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8282 unsigned TargetMask = 0;
8283 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8284 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8285 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8286 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8287 getShufflePSHUFLWImmediate(SVOp);
8288 V1 = NewV.getOperand(0);
8289 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8293 // Promote splats to a larger type which usually leads to more efficient code.
8294 // FIXME: Is this true if pshufb is available?
8295 if (SVOp->isSplat())
8296 return PromoteSplat(SVOp, DAG);
8298 // If we have SSSE3, and all words of the result are from 1 input vector,
8299 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
8300 // is present, fall back to case 4.
8301 if (Subtarget->hasSSSE3()) {
8302 SmallVector<SDValue,16> pshufbMask;
8304 // If we have elements from both input vectors, set the high bit of the
8305 // shuffle mask element to zero out elements that come from V2 in the V1
8306 // mask, and elements that come from V1 in the V2 mask, so that the two
8307 // results can be OR'd together.
8308 bool TwoInputs = V1Used && V2Used;
8309 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8311 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8313 // Calculate the shuffle mask for the second input, shuffle it, and
8314 // OR it with the first shuffled input.
8315 CommuteVectorShuffleMask(MaskVals, 8);
8316 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8317 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8318 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8321 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8322 // and update MaskVals with new element order.
8323 std::bitset<8> InOrder;
8324 if (BestLoQuad >= 0) {
8325 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8326 for (int i = 0; i != 4; ++i) {
8327 int idx = MaskVals[i];
8330 } else if ((idx / 4) == BestLoQuad) {
8335 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8338 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8339 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8340 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8342 getShufflePSHUFLWImmediate(SVOp), DAG);
8346 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8347 // and update MaskVals with the new element order.
8348 if (BestHiQuad >= 0) {
8349 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8350 for (unsigned i = 4; i != 8; ++i) {
8351 int idx = MaskVals[i];
8354 } else if ((idx / 4) == BestHiQuad) {
8355 MaskV[i] = (idx & 3) + 4;
8359 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8362 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8363 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8364 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8366 getShufflePSHUFHWImmediate(SVOp), DAG);
8370 // In case BestHi & BestLo were both -1, which means each quadword has a word
8371 // from each of the four input quadwords, calculate the InOrder bitvector now
8372 // before falling through to the insert/extract cleanup.
8373 if (BestLoQuad == -1 && BestHiQuad == -1) {
8375 for (int i = 0; i != 8; ++i)
8376 if (MaskVals[i] < 0 || MaskVals[i] == i)
8380 // The other elements are put in the right place using pextrw and pinsrw.
8381 for (unsigned i = 0; i != 8; ++i) {
8384 int EltIdx = MaskVals[i];
8387 SDValue ExtOp = (EltIdx < 8) ?
8388 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8389 DAG.getIntPtrConstant(EltIdx)) :
8390 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8391 DAG.getIntPtrConstant(EltIdx - 8));
8392 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8393 DAG.getIntPtrConstant(i));
8398 /// \brief v16i16 shuffles
8400 /// FIXME: We only support generation of a single pshufb currently. We can
8401 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8402 /// well (e.g 2 x pshufb + 1 x por).
8404 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8405 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8406 SDValue V1 = SVOp->getOperand(0);
8407 SDValue V2 = SVOp->getOperand(1);
8410 if (V2.getOpcode() != ISD::UNDEF)
8413 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8414 return getPSHUFB(MaskVals, V1, dl, DAG);
8417 // v16i8 shuffles - Prefer shuffles in the following order:
8418 // 1. [ssse3] 1 x pshufb
8419 // 2. [ssse3] 2 x pshufb + 1 x por
8420 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
8421 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8422 const X86Subtarget* Subtarget,
8423 SelectionDAG &DAG) {
8424 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8425 SDValue V1 = SVOp->getOperand(0);
8426 SDValue V2 = SVOp->getOperand(1);
8428 ArrayRef<int> MaskVals = SVOp->getMask();
8430 // Promote splats to a larger type which usually leads to more efficient code.
8431 // FIXME: Is this true if pshufb is available?
8432 if (SVOp->isSplat())
8433 return PromoteSplat(SVOp, DAG);
8435 // If we have SSSE3, case 1 is generated when all result bytes come from
8436 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
8437 // present, fall back to case 3.
8439 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8440 if (Subtarget->hasSSSE3()) {
8441 SmallVector<SDValue,16> pshufbMask;
8443 // If all result elements are from one input vector, then only translate
8444 // undef mask values to 0x80 (zero out result) in the pshufb mask.
8446 // Otherwise, we have elements from both input vectors, and must zero out
8447 // elements that come from V2 in the first mask, and V1 in the second mask
8448 // so that we can OR them together.
8449 for (unsigned i = 0; i != 16; ++i) {
8450 int EltIdx = MaskVals[i];
8451 if (EltIdx < 0 || EltIdx >= 16)
8453 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8455 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8456 DAG.getNode(ISD::BUILD_VECTOR, dl,
8457 MVT::v16i8, pshufbMask));
8459 // As PSHUFB will zero elements with negative indices, it's safe to ignore
8460 // the 2nd operand if it's undefined or zero.
8461 if (V2.getOpcode() == ISD::UNDEF ||
8462 ISD::isBuildVectorAllZeros(V2.getNode()))
8465 // Calculate the shuffle mask for the second input, shuffle it, and
8466 // OR it with the first shuffled input.
8468 for (unsigned i = 0; i != 16; ++i) {
8469 int EltIdx = MaskVals[i];
8470 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8471 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8473 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8474 DAG.getNode(ISD::BUILD_VECTOR, dl,
8475 MVT::v16i8, pshufbMask));
8476 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8479 // No SSSE3 - Calculate in place words and then fix all out of place words
8480 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
8481 // the 16 different words that comprise the two doublequadword input vectors.
8482 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8483 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8485 for (int i = 0; i != 8; ++i) {
8486 int Elt0 = MaskVals[i*2];
8487 int Elt1 = MaskVals[i*2+1];
8489 // This word of the result is all undef, skip it.
8490 if (Elt0 < 0 && Elt1 < 0)
8493 // This word of the result is already in the correct place, skip it.
8494 if ((Elt0 == i*2) && (Elt1 == i*2+1))
8497 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8498 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8501 // If Elt0 and Elt1 are defined, are consecutive, and can be load
8502 // using a single extract together, load it and store it.
8503 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8504 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8505 DAG.getIntPtrConstant(Elt1 / 2));
8506 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8507 DAG.getIntPtrConstant(i));
8511 // If Elt1 is defined, extract it from the appropriate source. If the
8512 // source byte is not also odd, shift the extracted word left 8 bits
8513 // otherwise clear the bottom 8 bits if we need to do an or.
8515 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8516 DAG.getIntPtrConstant(Elt1 / 2));
8517 if ((Elt1 & 1) == 0)
8518 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8520 TLI.getShiftAmountTy(InsElt.getValueType())));
8522 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8523 DAG.getConstant(0xFF00, MVT::i16));
8525 // If Elt0 is defined, extract it from the appropriate source. If the
8526 // source byte is not also even, shift the extracted word right 8 bits. If
8527 // Elt1 was also defined, OR the extracted values together before
8528 // inserting them in the result.
8530 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8531 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8532 if ((Elt0 & 1) != 0)
8533 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8535 TLI.getShiftAmountTy(InsElt0.getValueType())));
8537 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8538 DAG.getConstant(0x00FF, MVT::i16));
8539 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8542 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8543 DAG.getIntPtrConstant(i));
8545 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8548 // v32i8 shuffles - Translate to VPSHUFB if possible.
8550 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8551 const X86Subtarget *Subtarget,
8552 SelectionDAG &DAG) {
8553 MVT VT = SVOp->getSimpleValueType(0);
8554 SDValue V1 = SVOp->getOperand(0);
8555 SDValue V2 = SVOp->getOperand(1);
8557 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8559 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8560 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8561 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8563 // VPSHUFB may be generated if
8564 // (1) one of input vector is undefined or zeroinitializer.
8565 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8566 // And (2) the mask indexes don't cross the 128-bit lane.
8567 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8568 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8571 if (V1IsAllZero && !V2IsAllZero) {
8572 CommuteVectorShuffleMask(MaskVals, 32);
8575 return getPSHUFB(MaskVals, V1, dl, DAG);
8578 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8579 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8580 /// done when every pair / quad of shuffle mask elements point to elements in
8581 /// the right sequence. e.g.
8582 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8584 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8585 SelectionDAG &DAG) {
8586 MVT VT = SVOp->getSimpleValueType(0);
8588 unsigned NumElems = VT.getVectorNumElements();
8591 switch (VT.SimpleTy) {
8592 default: llvm_unreachable("Unexpected!");
8595 return SDValue(SVOp, 0);
8596 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
8597 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
8598 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
8599 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
8600 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8601 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
8604 SmallVector<int, 8> MaskVec;
8605 for (unsigned i = 0; i != NumElems; i += Scale) {
8607 for (unsigned j = 0; j != Scale; ++j) {
8608 int EltIdx = SVOp->getMaskElt(i+j);
8612 StartIdx = (EltIdx / Scale);
8613 if (EltIdx != (int)(StartIdx*Scale + j))
8616 MaskVec.push_back(StartIdx);
8619 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8620 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8621 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8624 /// getVZextMovL - Return a zero-extending vector move low node.
8626 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8627 SDValue SrcOp, SelectionDAG &DAG,
8628 const X86Subtarget *Subtarget, SDLoc dl) {
8629 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8630 LoadSDNode *LD = nullptr;
8631 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8632 LD = dyn_cast<LoadSDNode>(SrcOp);
8634 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8636 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8637 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8638 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8639 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8640 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8642 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8643 return DAG.getNode(ISD::BITCAST, dl, VT,
8644 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8645 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8653 return DAG.getNode(ISD::BITCAST, dl, VT,
8654 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8655 DAG.getNode(ISD::BITCAST, dl,
8659 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8660 /// which could not be matched by any known target speficic shuffle
8662 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8664 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8665 if (NewOp.getNode())
8668 MVT VT = SVOp->getSimpleValueType(0);
8670 unsigned NumElems = VT.getVectorNumElements();
8671 unsigned NumLaneElems = NumElems / 2;
8674 MVT EltVT = VT.getVectorElementType();
8675 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8678 SmallVector<int, 16> Mask;
8679 for (unsigned l = 0; l < 2; ++l) {
8680 // Build a shuffle mask for the output, discovering on the fly which
8681 // input vectors to use as shuffle operands (recorded in InputUsed).
8682 // If building a suitable shuffle vector proves too hard, then bail
8683 // out with UseBuildVector set.
8684 bool UseBuildVector = false;
8685 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8686 unsigned LaneStart = l * NumLaneElems;
8687 for (unsigned i = 0; i != NumLaneElems; ++i) {
8688 // The mask element. This indexes into the input.
8689 int Idx = SVOp->getMaskElt(i+LaneStart);
8691 // the mask element does not index into any input vector.
8696 // The input vector this mask element indexes into.
8697 int Input = Idx / NumLaneElems;
8699 // Turn the index into an offset from the start of the input vector.
8700 Idx -= Input * NumLaneElems;
8702 // Find or create a shuffle vector operand to hold this input.
8704 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8705 if (InputUsed[OpNo] == Input)
8706 // This input vector is already an operand.
8708 if (InputUsed[OpNo] < 0) {
8709 // Create a new operand for this input vector.
8710 InputUsed[OpNo] = Input;
8715 if (OpNo >= array_lengthof(InputUsed)) {
8716 // More than two input vectors used! Give up on trying to create a
8717 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
8718 UseBuildVector = true;
8722 // Add the mask index for the new shuffle vector.
8723 Mask.push_back(Idx + OpNo * NumLaneElems);
8726 if (UseBuildVector) {
8727 SmallVector<SDValue, 16> SVOps;
8728 for (unsigned i = 0; i != NumLaneElems; ++i) {
8729 // The mask element. This indexes into the input.
8730 int Idx = SVOp->getMaskElt(i+LaneStart);
8732 SVOps.push_back(DAG.getUNDEF(EltVT));
8736 // The input vector this mask element indexes into.
8737 int Input = Idx / NumElems;
8739 // Turn the index into an offset from the start of the input vector.
8740 Idx -= Input * NumElems;
8742 // Extract the vector element by hand.
8743 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8744 SVOp->getOperand(Input),
8745 DAG.getIntPtrConstant(Idx)));
8748 // Construct the output using a BUILD_VECTOR.
8749 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8750 } else if (InputUsed[0] < 0) {
8751 // No input vectors were used! The result is undefined.
8752 Output[l] = DAG.getUNDEF(NVT);
8754 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8755 (InputUsed[0] % 2) * NumLaneElems,
8757 // If only one input was used, use an undefined vector for the other.
8758 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8759 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8760 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8761 // At least one input vector was used. Create a new shuffle vector.
8762 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8768 // Concatenate the result back
8769 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8772 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8773 /// 4 elements, and match them with several different shuffle types.
8775 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8776 SDValue V1 = SVOp->getOperand(0);
8777 SDValue V2 = SVOp->getOperand(1);
8779 MVT VT = SVOp->getSimpleValueType(0);
8781 assert(VT.is128BitVector() && "Unsupported vector size");
8783 std::pair<int, int> Locs[4];
8784 int Mask1[] = { -1, -1, -1, -1 };
8785 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8789 for (unsigned i = 0; i != 4; ++i) {
8790 int Idx = PermMask[i];
8792 Locs[i] = std::make_pair(-1, -1);
8794 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8796 Locs[i] = std::make_pair(0, NumLo);
8800 Locs[i] = std::make_pair(1, NumHi);
8802 Mask1[2+NumHi] = Idx;
8808 if (NumLo <= 2 && NumHi <= 2) {
8809 // If no more than two elements come from either vector. This can be
8810 // implemented with two shuffles. First shuffle gather the elements.
8811 // The second shuffle, which takes the first shuffle as both of its
8812 // vector operands, put the elements into the right order.
8813 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8815 int Mask2[] = { -1, -1, -1, -1 };
8817 for (unsigned i = 0; i != 4; ++i)
8818 if (Locs[i].first != -1) {
8819 unsigned Idx = (i < 2) ? 0 : 4;
8820 Idx += Locs[i].first * 2 + Locs[i].second;
8824 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8827 if (NumLo == 3 || NumHi == 3) {
8828 // Otherwise, we must have three elements from one vector, call it X, and
8829 // one element from the other, call it Y. First, use a shufps to build an
8830 // intermediate vector with the one element from Y and the element from X
8831 // that will be in the same half in the final destination (the indexes don't
8832 // matter). Then, use a shufps to build the final vector, taking the half
8833 // containing the element from Y from the intermediate, and the other half
8836 // Normalize it so the 3 elements come from V1.
8837 CommuteVectorShuffleMask(PermMask, 4);
8841 // Find the element from V2.
8843 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8844 int Val = PermMask[HiIndex];
8851 Mask1[0] = PermMask[HiIndex];
8853 Mask1[2] = PermMask[HiIndex^1];
8855 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8858 Mask1[0] = PermMask[0];
8859 Mask1[1] = PermMask[1];
8860 Mask1[2] = HiIndex & 1 ? 6 : 4;
8861 Mask1[3] = HiIndex & 1 ? 4 : 6;
8862 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8865 Mask1[0] = HiIndex & 1 ? 2 : 0;
8866 Mask1[1] = HiIndex & 1 ? 0 : 2;
8867 Mask1[2] = PermMask[2];
8868 Mask1[3] = PermMask[3];
8873 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8876 // Break it into (shuffle shuffle_hi, shuffle_lo).
8877 int LoMask[] = { -1, -1, -1, -1 };
8878 int HiMask[] = { -1, -1, -1, -1 };
8880 int *MaskPtr = LoMask;
8881 unsigned MaskIdx = 0;
8884 for (unsigned i = 0; i != 4; ++i) {
8891 int Idx = PermMask[i];
8893 Locs[i] = std::make_pair(-1, -1);
8894 } else if (Idx < 4) {
8895 Locs[i] = std::make_pair(MaskIdx, LoIdx);
8896 MaskPtr[LoIdx] = Idx;
8899 Locs[i] = std::make_pair(MaskIdx, HiIdx);
8900 MaskPtr[HiIdx] = Idx;
8905 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8906 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8907 int MaskOps[] = { -1, -1, -1, -1 };
8908 for (unsigned i = 0; i != 4; ++i)
8909 if (Locs[i].first != -1)
8910 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8911 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8914 static bool MayFoldVectorLoad(SDValue V) {
8915 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8916 V = V.getOperand(0);
8918 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8919 V = V.getOperand(0);
8920 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8921 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8922 // BUILD_VECTOR (load), undef
8923 V = V.getOperand(0);
8925 return MayFoldLoad(V);
8929 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8930 MVT VT = Op.getSimpleValueType();
8932 // Canonizalize to v2f64.
8933 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8934 return DAG.getNode(ISD::BITCAST, dl, VT,
8935 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8940 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8942 SDValue V1 = Op.getOperand(0);
8943 SDValue V2 = Op.getOperand(1);
8944 MVT VT = Op.getSimpleValueType();
8946 assert(VT != MVT::v2i64 && "unsupported shuffle type");
8948 if (HasSSE2 && VT == MVT::v2f64)
8949 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8951 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8952 return DAG.getNode(ISD::BITCAST, dl, VT,
8953 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8954 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8955 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8959 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8960 SDValue V1 = Op.getOperand(0);
8961 SDValue V2 = Op.getOperand(1);
8962 MVT VT = Op.getSimpleValueType();
8964 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8965 "unsupported shuffle type");
8967 if (V2.getOpcode() == ISD::UNDEF)
8971 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8975 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8976 SDValue V1 = Op.getOperand(0);
8977 SDValue V2 = Op.getOperand(1);
8978 MVT VT = Op.getSimpleValueType();
8979 unsigned NumElems = VT.getVectorNumElements();
8981 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8982 // operand of these instructions is only memory, so check if there's a
8983 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8985 bool CanFoldLoad = false;
8987 // Trivial case, when V2 comes from a load.
8988 if (MayFoldVectorLoad(V2))
8991 // When V1 is a load, it can be folded later into a store in isel, example:
8992 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8994 // (MOVLPSmr addr:$src1, VR128:$src2)
8995 // So, recognize this potential and also use MOVLPS or MOVLPD
8996 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8999 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9001 if (HasSSE2 && NumElems == 2)
9002 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9005 // If we don't care about the second element, proceed to use movss.
9006 if (SVOp->getMaskElt(1) != -1)
9007 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9010 // movl and movlp will both match v2i64, but v2i64 is never matched by
9011 // movl earlier because we make it strict to avoid messing with the movlp load
9012 // folding logic (see the code above getMOVLP call). Match it here then,
9013 // this is horrible, but will stay like this until we move all shuffle
9014 // matching to x86 specific nodes. Note that for the 1st condition all
9015 // types are matched with movsd.
9017 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9018 // as to remove this logic from here, as much as possible
9019 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9020 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9021 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9024 assert(VT != MVT::v4i32 && "unsupported shuffle type");
9026 // Invert the operand order and use SHUFPS to match it.
9027 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9028 getShuffleSHUFImmediate(SVOp), DAG);
9031 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9032 SelectionDAG &DAG) {
9034 MVT VT = Load->getSimpleValueType(0);
9035 MVT EVT = VT.getVectorElementType();
9036 SDValue Addr = Load->getOperand(1);
9037 SDValue NewAddr = DAG.getNode(
9038 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9039 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9042 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9043 DAG.getMachineFunction().getMachineMemOperand(
9044 Load->getMemOperand(), 0, EVT.getStoreSize()));
9048 // It is only safe to call this function if isINSERTPSMask is true for
9049 // this shufflevector mask.
9050 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9051 SelectionDAG &DAG) {
9052 // Generate an insertps instruction when inserting an f32 from memory onto a
9053 // v4f32 or when copying a member from one v4f32 to another.
9054 // We also use it for transferring i32 from one register to another,
9055 // since it simply copies the same bits.
9056 // If we're transferring an i32 from memory to a specific element in a
9057 // register, we output a generic DAG that will match the PINSRD
9059 MVT VT = SVOp->getSimpleValueType(0);
9060 MVT EVT = VT.getVectorElementType();
9061 SDValue V1 = SVOp->getOperand(0);
9062 SDValue V2 = SVOp->getOperand(1);
9063 auto Mask = SVOp->getMask();
9064 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9065 "unsupported vector type for insertps/pinsrd");
9067 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9068 auto FromV2Predicate = [](const int &i) { return i >= 4; };
9069 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9077 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9080 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9081 "More than one element from V1 and from V2, or no elements from one "
9082 "of the vectors. This case should not have returned true from "
9087 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9090 unsigned SrcIndex = Mask[DestIndex] % 4;
9091 if (MayFoldLoad(From)) {
9092 // Trivial case, when From comes from a load and is only used by the
9093 // shuffle. Make it use insertps from the vector that we need from that
9096 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9097 if (!NewLoad.getNode())
9100 if (EVT == MVT::f32) {
9101 // Create this as a scalar to vector to match the instruction pattern.
9102 SDValue LoadScalarToVector =
9103 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9104 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9105 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9107 } else { // EVT == MVT::i32
9108 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9109 // instruction, to match the PINSRD instruction, which loads an i32 to a
9110 // certain vector element.
9111 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9112 DAG.getConstant(DestIndex, MVT::i32));
9116 // Vector-element-to-vector
9117 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9118 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9121 // Reduce a vector shuffle to zext.
9122 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9123 SelectionDAG &DAG) {
9124 // PMOVZX is only available from SSE41.
9125 if (!Subtarget->hasSSE41())
9128 MVT VT = Op.getSimpleValueType();
9130 // Only AVX2 support 256-bit vector integer extending.
9131 if (!Subtarget->hasInt256() && VT.is256BitVector())
9134 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9136 SDValue V1 = Op.getOperand(0);
9137 SDValue V2 = Op.getOperand(1);
9138 unsigned NumElems = VT.getVectorNumElements();
9140 // Extending is an unary operation and the element type of the source vector
9141 // won't be equal to or larger than i64.
9142 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9143 VT.getVectorElementType() == MVT::i64)
9146 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9147 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9148 while ((1U << Shift) < NumElems) {
9149 if (SVOp->getMaskElt(1U << Shift) == 1)
9152 // The maximal ratio is 8, i.e. from i8 to i64.
9157 // Check the shuffle mask.
9158 unsigned Mask = (1U << Shift) - 1;
9159 for (unsigned i = 0; i != NumElems; ++i) {
9160 int EltIdx = SVOp->getMaskElt(i);
9161 if ((i & Mask) != 0 && EltIdx != -1)
9163 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9167 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9168 MVT NeVT = MVT::getIntegerVT(NBits);
9169 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9171 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9174 // Simplify the operand as it's prepared to be fed into shuffle.
9175 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9176 if (V1.getOpcode() == ISD::BITCAST &&
9177 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9178 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9179 V1.getOperand(0).getOperand(0)
9180 .getSimpleValueType().getSizeInBits() == SignificantBits) {
9181 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9182 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9183 ConstantSDNode *CIdx =
9184 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9185 // If it's foldable, i.e. normal load with single use, we will let code
9186 // selection to fold it. Otherwise, we will short the conversion sequence.
9187 if (CIdx && CIdx->getZExtValue() == 0 &&
9188 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9189 MVT FullVT = V.getSimpleValueType();
9190 MVT V1VT = V1.getSimpleValueType();
9191 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9192 // The "ext_vec_elt" node is wider than the result node.
9193 // In this case we should extract subvector from V.
9194 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9195 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9196 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9197 FullVT.getVectorNumElements()/Ratio);
9198 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9199 DAG.getIntPtrConstant(0));
9201 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9205 return DAG.getNode(ISD::BITCAST, DL, VT,
9206 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9209 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9210 SelectionDAG &DAG) {
9211 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9212 MVT VT = Op.getSimpleValueType();
9214 SDValue V1 = Op.getOperand(0);
9215 SDValue V2 = Op.getOperand(1);
9217 if (isZeroShuffle(SVOp))
9218 return getZeroVector(VT, Subtarget, DAG, dl);
9220 // Handle splat operations
9221 if (SVOp->isSplat()) {
9222 // Use vbroadcast whenever the splat comes from a foldable load
9223 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9224 if (Broadcast.getNode())
9228 // Check integer expanding shuffles.
9229 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9230 if (NewOp.getNode())
9233 // If the shuffle can be profitably rewritten as a narrower shuffle, then
9235 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9237 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9238 if (NewOp.getNode())
9239 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9240 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9241 // FIXME: Figure out a cleaner way to do this.
9242 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9243 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9244 if (NewOp.getNode()) {
9245 MVT NewVT = NewOp.getSimpleValueType();
9246 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9247 NewVT, true, false))
9248 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9251 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9252 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9253 if (NewOp.getNode()) {
9254 MVT NewVT = NewOp.getSimpleValueType();
9255 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9256 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9265 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9266 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9267 SDValue V1 = Op.getOperand(0);
9268 SDValue V2 = Op.getOperand(1);
9269 MVT VT = Op.getSimpleValueType();
9271 unsigned NumElems = VT.getVectorNumElements();
9272 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9273 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9274 bool V1IsSplat = false;
9275 bool V2IsSplat = false;
9276 bool HasSSE2 = Subtarget->hasSSE2();
9277 bool HasFp256 = Subtarget->hasFp256();
9278 bool HasInt256 = Subtarget->hasInt256();
9279 MachineFunction &MF = DAG.getMachineFunction();
9280 bool OptForSize = MF.getFunction()->getAttributes().
9281 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9283 // Check if we should use the experimental vector shuffle lowering. If so,
9284 // delegate completely to that code path.
9285 if (ExperimentalVectorShuffleLowering)
9286 return lowerVectorShuffle(Op, Subtarget, DAG);
9288 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9290 if (V1IsUndef && V2IsUndef)
9291 return DAG.getUNDEF(VT);
9293 // When we create a shuffle node we put the UNDEF node to second operand,
9294 // but in some cases the first operand may be transformed to UNDEF.
9295 // In this case we should just commute the node.
9297 return CommuteVectorShuffle(SVOp, DAG);
9299 // Vector shuffle lowering takes 3 steps:
9301 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9302 // narrowing and commutation of operands should be handled.
9303 // 2) Matching of shuffles with known shuffle masks to x86 target specific
9305 // 3) Rewriting of unmatched masks into new generic shuffle operations,
9306 // so the shuffle can be broken into other shuffles and the legalizer can
9307 // try the lowering again.
9309 // The general idea is that no vector_shuffle operation should be left to
9310 // be matched during isel, all of them must be converted to a target specific
9313 // Normalize the input vectors. Here splats, zeroed vectors, profitable
9314 // narrowing and commutation of operands should be handled. The actual code
9315 // doesn't include all of those, work in progress...
9316 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9317 if (NewOp.getNode())
9320 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9322 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9323 // unpckh_undef). Only use pshufd if speed is more important than size.
9324 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9325 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9326 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9327 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9329 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9330 V2IsUndef && MayFoldVectorLoad(V1))
9331 return getMOVDDup(Op, dl, V1, DAG);
9333 if (isMOVHLPS_v_undef_Mask(M, VT))
9334 return getMOVHighToLow(Op, dl, DAG);
9336 // Use to match splats
9337 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9338 (VT == MVT::v2f64 || VT == MVT::v2i64))
9339 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9341 if (isPSHUFDMask(M, VT)) {
9342 // The actual implementation will match the mask in the if above and then
9343 // during isel it can match several different instructions, not only pshufd
9344 // as its name says, sad but true, emulate the behavior for now...
9345 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9346 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9348 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9350 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9351 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9353 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9354 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9357 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9361 if (isPALIGNRMask(M, VT, Subtarget))
9362 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9363 getShufflePALIGNRImmediate(SVOp),
9366 // Check if this can be converted into a logical shift.
9367 bool isLeft = false;
9370 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9371 if (isShift && ShVal.hasOneUse()) {
9372 // If the shifted value has multiple uses, it may be cheaper to use
9373 // v_set0 + movlhps or movhlps, etc.
9374 MVT EltVT = VT.getVectorElementType();
9375 ShAmt *= EltVT.getSizeInBits();
9376 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9379 if (isMOVLMask(M, VT)) {
9380 if (ISD::isBuildVectorAllZeros(V1.getNode()))
9381 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9382 if (!isMOVLPMask(M, VT)) {
9383 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9384 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9386 if (VT == MVT::v4i32 || VT == MVT::v4f32)
9387 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9391 // FIXME: fold these into legal mask.
9392 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9393 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9395 if (isMOVHLPSMask(M, VT))
9396 return getMOVHighToLow(Op, dl, DAG);
9398 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9399 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9401 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9402 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9404 if (isMOVLPMask(M, VT))
9405 return getMOVLP(Op, dl, DAG, HasSSE2);
9407 if (ShouldXformToMOVHLPS(M, VT) ||
9408 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9409 return CommuteVectorShuffle(SVOp, DAG);
9412 // No better options. Use a vshldq / vsrldq.
9413 MVT EltVT = VT.getVectorElementType();
9414 ShAmt *= EltVT.getSizeInBits();
9415 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9418 bool Commuted = false;
9419 // FIXME: This should also accept a bitcast of a splat? Be careful, not
9420 // 1,1,1,1 -> v8i16 though.
9421 BitVector UndefElements;
9422 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9423 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9425 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9426 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9429 // Canonicalize the splat or undef, if present, to be on the RHS.
9430 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9431 CommuteVectorShuffleMask(M, NumElems);
9433 std::swap(V1IsSplat, V2IsSplat);
9437 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9438 // Shuffling low element of v1 into undef, just return v1.
9441 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9442 // the instruction selector will not match, so get a canonical MOVL with
9443 // swapped operands to undo the commute.
9444 return getMOVL(DAG, dl, VT, V2, V1);
9447 if (isUNPCKLMask(M, VT, HasInt256))
9448 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9450 if (isUNPCKHMask(M, VT, HasInt256))
9451 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9454 // Normalize mask so all entries that point to V2 points to its first
9455 // element then try to match unpck{h|l} again. If match, return a
9456 // new vector_shuffle with the corrected mask.p
9457 SmallVector<int, 8> NewMask(M.begin(), M.end());
9458 NormalizeMask(NewMask, NumElems);
9459 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9460 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9461 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9462 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9466 // Commute is back and try unpck* again.
9467 // FIXME: this seems wrong.
9468 CommuteVectorShuffleMask(M, NumElems);
9470 std::swap(V1IsSplat, V2IsSplat);
9472 if (isUNPCKLMask(M, VT, HasInt256))
9473 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9475 if (isUNPCKHMask(M, VT, HasInt256))
9476 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9479 // Normalize the node to match x86 shuffle ops if needed
9480 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9481 return CommuteVectorShuffle(SVOp, DAG);
9483 // The checks below are all present in isShuffleMaskLegal, but they are
9484 // inlined here right now to enable us to directly emit target specific
9485 // nodes, and remove one by one until they don't return Op anymore.
9487 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9488 SVOp->getSplatIndex() == 0 && V2IsUndef) {
9489 if (VT == MVT::v2f64 || VT == MVT::v2i64)
9490 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9493 if (isPSHUFHWMask(M, VT, HasInt256))
9494 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9495 getShufflePSHUFHWImmediate(SVOp),
9498 if (isPSHUFLWMask(M, VT, HasInt256))
9499 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9500 getShufflePSHUFLWImmediate(SVOp),
9504 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9506 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9508 if (isSHUFPMask(M, VT))
9509 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9510 getShuffleSHUFImmediate(SVOp), DAG);
9512 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9513 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9514 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9515 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9517 //===--------------------------------------------------------------------===//
9518 // Generate target specific nodes for 128 or 256-bit shuffles only
9519 // supported in the AVX instruction set.
9522 // Handle VMOVDDUPY permutations
9523 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9524 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9526 // Handle VPERMILPS/D* permutations
9527 if (isVPERMILPMask(M, VT)) {
9528 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9529 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9530 getShuffleSHUFImmediate(SVOp), DAG);
9531 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9532 getShuffleSHUFImmediate(SVOp), DAG);
9536 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9537 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9538 Idx*(NumElems/2), DAG, dl);
9540 // Handle VPERM2F128/VPERM2I128 permutations
9541 if (isVPERM2X128Mask(M, VT, HasFp256))
9542 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9543 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9545 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9546 return getINSERTPS(SVOp, dl, DAG);
9549 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9550 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9552 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9553 VT.is512BitVector()) {
9554 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9555 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9556 SmallVector<SDValue, 16> permclMask;
9557 for (unsigned i = 0; i != NumElems; ++i) {
9558 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9561 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9563 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9564 return DAG.getNode(X86ISD::VPERMV, dl, VT,
9565 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9566 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9567 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9570 //===--------------------------------------------------------------------===//
9571 // Since no target specific shuffle was selected for this generic one,
9572 // lower it into other known shuffles. FIXME: this isn't true yet, but
9573 // this is the plan.
9576 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9577 if (VT == MVT::v8i16) {
9578 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9579 if (NewOp.getNode())
9583 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9584 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9585 if (NewOp.getNode())
9589 if (VT == MVT::v16i8) {
9590 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9591 if (NewOp.getNode())
9595 if (VT == MVT::v32i8) {
9596 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9597 if (NewOp.getNode())
9601 // Handle all 128-bit wide vectors with 4 elements, and match them with
9602 // several different shuffle types.
9603 if (NumElems == 4 && VT.is128BitVector())
9604 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9606 // Handle general 256-bit shuffles
9607 if (VT.is256BitVector())
9608 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9613 // This function assumes its argument is a BUILD_VECTOR of constants or
9614 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9616 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9617 unsigned &MaskValue) {
9619 unsigned NumElems = BuildVector->getNumOperands();
9620 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9621 unsigned NumLanes = (NumElems - 1) / 8 + 1;
9622 unsigned NumElemsInLane = NumElems / NumLanes;
9624 // Blend for v16i16 should be symetric for the both lanes.
9625 for (unsigned i = 0; i < NumElemsInLane; ++i) {
9626 SDValue EltCond = BuildVector->getOperand(i);
9627 SDValue SndLaneEltCond =
9628 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9630 int Lane1Cond = -1, Lane2Cond = -1;
9631 if (isa<ConstantSDNode>(EltCond))
9632 Lane1Cond = !isZero(EltCond);
9633 if (isa<ConstantSDNode>(SndLaneEltCond))
9634 Lane2Cond = !isZero(SndLaneEltCond);
9636 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9637 // Lane1Cond != 0, means we want the first argument.
9638 // Lane1Cond == 0, means we want the second argument.
9639 // The encoding of this argument is 0 for the first argument, 1
9640 // for the second. Therefore, invert the condition.
9641 MaskValue |= !Lane1Cond << i;
9642 else if (Lane1Cond < 0)
9643 MaskValue |= !Lane2Cond << i;
9650 // Try to lower a vselect node into a simple blend instruction.
9651 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9652 SelectionDAG &DAG) {
9653 SDValue Cond = Op.getOperand(0);
9654 SDValue LHS = Op.getOperand(1);
9655 SDValue RHS = Op.getOperand(2);
9657 MVT VT = Op.getSimpleValueType();
9658 MVT EltVT = VT.getVectorElementType();
9659 unsigned NumElems = VT.getVectorNumElements();
9661 // There is no blend with immediate in AVX-512.
9662 if (VT.is512BitVector())
9665 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9667 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9670 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9673 // Check the mask for BLEND and build the value.
9674 unsigned MaskValue = 0;
9675 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9678 // Convert i32 vectors to floating point if it is not AVX2.
9679 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9681 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9682 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9684 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9685 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9688 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9689 DAG.getConstant(MaskValue, MVT::i32));
9690 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9693 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9694 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9695 if (BlendOp.getNode())
9698 // Some types for vselect were previously set to Expand, not Legal or
9699 // Custom. Return an empty SDValue so we fall-through to Expand, after
9700 // the Custom lowering phase.
9701 MVT VT = Op.getSimpleValueType();
9702 switch (VT.SimpleTy) {
9710 // We couldn't create a "Blend with immediate" node.
9711 // This node should still be legal, but we'll have to emit a blendv*
9716 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9717 MVT VT = Op.getSimpleValueType();
9720 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9723 if (VT.getSizeInBits() == 8) {
9724 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9725 Op.getOperand(0), Op.getOperand(1));
9726 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9727 DAG.getValueType(VT));
9728 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9731 if (VT.getSizeInBits() == 16) {
9732 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9733 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9735 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9736 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9737 DAG.getNode(ISD::BITCAST, dl,
9741 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9742 Op.getOperand(0), Op.getOperand(1));
9743 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9744 DAG.getValueType(VT));
9745 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9748 if (VT == MVT::f32) {
9749 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9750 // the result back to FR32 register. It's only worth matching if the
9751 // result has a single use which is a store or a bitcast to i32. And in
9752 // the case of a store, it's not worth it if the index is a constant 0,
9753 // because a MOVSSmr can be used instead, which is smaller and faster.
9754 if (!Op.hasOneUse())
9756 SDNode *User = *Op.getNode()->use_begin();
9757 if ((User->getOpcode() != ISD::STORE ||
9758 (isa<ConstantSDNode>(Op.getOperand(1)) &&
9759 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9760 (User->getOpcode() != ISD::BITCAST ||
9761 User->getValueType(0) != MVT::i32))
9763 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9764 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9767 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9770 if (VT == MVT::i32 || VT == MVT::i64) {
9771 // ExtractPS/pextrq works with constant index.
9772 if (isa<ConstantSDNode>(Op.getOperand(1)))
9778 /// Extract one bit from mask vector, like v16i1 or v8i1.
9779 /// AVX-512 feature.
9781 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9782 SDValue Vec = Op.getOperand(0);
9784 MVT VecVT = Vec.getSimpleValueType();
9785 SDValue Idx = Op.getOperand(1);
9786 MVT EltVT = Op.getSimpleValueType();
9788 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9790 // variable index can't be handled in mask registers,
9791 // extend vector to VR512
9792 if (!isa<ConstantSDNode>(Idx)) {
9793 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9794 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9795 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9796 ExtVT.getVectorElementType(), Ext, Idx);
9797 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9800 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9801 const TargetRegisterClass* rc = getRegClassFor(VecVT);
9802 unsigned MaxSift = rc->getSize()*8 - 1;
9803 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9804 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9805 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9806 DAG.getConstant(MaxSift, MVT::i8));
9807 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9808 DAG.getIntPtrConstant(0));
9812 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9813 SelectionDAG &DAG) const {
9815 SDValue Vec = Op.getOperand(0);
9816 MVT VecVT = Vec.getSimpleValueType();
9817 SDValue Idx = Op.getOperand(1);
9819 if (Op.getSimpleValueType() == MVT::i1)
9820 return ExtractBitFromMaskVector(Op, DAG);
9822 if (!isa<ConstantSDNode>(Idx)) {
9823 if (VecVT.is512BitVector() ||
9824 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9825 VecVT.getVectorElementType().getSizeInBits() == 32)) {
9828 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9829 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9830 MaskEltVT.getSizeInBits());
9832 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9833 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9834 getZeroVector(MaskVT, Subtarget, DAG, dl),
9835 Idx, DAG.getConstant(0, getPointerTy()));
9836 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9837 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9838 Perm, DAG.getConstant(0, getPointerTy()));
9843 // If this is a 256-bit vector result, first extract the 128-bit vector and
9844 // then extract the element from the 128-bit vector.
9845 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9847 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9848 // Get the 128-bit vector.
9849 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9850 MVT EltVT = VecVT.getVectorElementType();
9852 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9854 //if (IdxVal >= NumElems/2)
9855 // IdxVal -= NumElems/2;
9856 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9857 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9858 DAG.getConstant(IdxVal, MVT::i32));
9861 assert(VecVT.is128BitVector() && "Unexpected vector length");
9863 if (Subtarget->hasSSE41()) {
9864 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9869 MVT VT = Op.getSimpleValueType();
9870 // TODO: handle v16i8.
9871 if (VT.getSizeInBits() == 16) {
9872 SDValue Vec = Op.getOperand(0);
9873 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9875 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9876 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9877 DAG.getNode(ISD::BITCAST, dl,
9880 // Transform it so it match pextrw which produces a 32-bit result.
9881 MVT EltVT = MVT::i32;
9882 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9883 Op.getOperand(0), Op.getOperand(1));
9884 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9885 DAG.getValueType(VT));
9886 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9889 if (VT.getSizeInBits() == 32) {
9890 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9894 // SHUFPS the element to the lowest double word, then movss.
9895 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9896 MVT VVT = Op.getOperand(0).getSimpleValueType();
9897 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9898 DAG.getUNDEF(VVT), Mask);
9899 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9900 DAG.getIntPtrConstant(0));
9903 if (VT.getSizeInBits() == 64) {
9904 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9905 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9906 // to match extract_elt for f64.
9907 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9911 // UNPCKHPD the element to the lowest double word, then movsd.
9912 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9913 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9914 int Mask[2] = { 1, -1 };
9915 MVT VVT = Op.getOperand(0).getSimpleValueType();
9916 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9917 DAG.getUNDEF(VVT), Mask);
9918 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9919 DAG.getIntPtrConstant(0));
9925 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9926 MVT VT = Op.getSimpleValueType();
9927 MVT EltVT = VT.getVectorElementType();
9930 SDValue N0 = Op.getOperand(0);
9931 SDValue N1 = Op.getOperand(1);
9932 SDValue N2 = Op.getOperand(2);
9934 if (!VT.is128BitVector())
9937 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9938 isa<ConstantSDNode>(N2)) {
9940 if (VT == MVT::v8i16)
9941 Opc = X86ISD::PINSRW;
9942 else if (VT == MVT::v16i8)
9943 Opc = X86ISD::PINSRB;
9945 Opc = X86ISD::PINSRB;
9947 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9949 if (N1.getValueType() != MVT::i32)
9950 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9951 if (N2.getValueType() != MVT::i32)
9952 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9953 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9956 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9957 // Bits [7:6] of the constant are the source select. This will always be
9958 // zero here. The DAG Combiner may combine an extract_elt index into these
9959 // bits. For example (insert (extract, 3), 2) could be matched by putting
9960 // the '3' into bits [7:6] of X86ISD::INSERTPS.
9961 // Bits [5:4] of the constant are the destination select. This is the
9962 // value of the incoming immediate.
9963 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
9964 // combine either bitwise AND or insert of float 0.0 to set these bits.
9965 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9966 // Create this as a scalar to vector..
9967 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9968 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9971 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9972 // PINSR* works with constant index.
9978 /// Insert one bit to mask vector, like v16i1 or v8i1.
9979 /// AVX-512 feature.
9981 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9983 SDValue Vec = Op.getOperand(0);
9984 SDValue Elt = Op.getOperand(1);
9985 SDValue Idx = Op.getOperand(2);
9986 MVT VecVT = Vec.getSimpleValueType();
9988 if (!isa<ConstantSDNode>(Idx)) {
9989 // Non constant index. Extend source and destination,
9990 // insert element and then truncate the result.
9991 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9992 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
9993 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
9994 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9995 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9996 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
9999 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10000 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10001 if (Vec.getOpcode() == ISD::UNDEF)
10002 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10003 DAG.getConstant(IdxVal, MVT::i8));
10004 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10005 unsigned MaxSift = rc->getSize()*8 - 1;
10006 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10007 DAG.getConstant(MaxSift, MVT::i8));
10008 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10009 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10010 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10013 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10014 MVT VT = Op.getSimpleValueType();
10015 MVT EltVT = VT.getVectorElementType();
10017 if (EltVT == MVT::i1)
10018 return InsertBitToMaskVector(Op, DAG);
10021 SDValue N0 = Op.getOperand(0);
10022 SDValue N1 = Op.getOperand(1);
10023 SDValue N2 = Op.getOperand(2);
10025 // If this is a 256-bit vector result, first extract the 128-bit vector,
10026 // insert the element into the extracted half and then place it back.
10027 if (VT.is256BitVector() || VT.is512BitVector()) {
10028 if (!isa<ConstantSDNode>(N2))
10031 // Get the desired 128-bit vector half.
10032 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10033 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10035 // Insert the element into the desired half.
10036 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10037 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10039 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10040 DAG.getConstant(IdxIn128, MVT::i32));
10042 // Insert the changed part back to the 256-bit vector
10043 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10046 if (Subtarget->hasSSE41())
10047 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10049 if (EltVT == MVT::i8)
10052 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10053 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10054 // as its second argument.
10055 if (N1.getValueType() != MVT::i32)
10056 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10057 if (N2.getValueType() != MVT::i32)
10058 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10059 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10064 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10066 MVT OpVT = Op.getSimpleValueType();
10068 // If this is a 256-bit vector result, first insert into a 128-bit
10069 // vector and then insert into the 256-bit vector.
10070 if (!OpVT.is128BitVector()) {
10071 // Insert into a 128-bit vector.
10072 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10073 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10074 OpVT.getVectorNumElements() / SizeFactor);
10076 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10078 // Insert the 128-bit vector.
10079 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10082 if (OpVT == MVT::v1i64 &&
10083 Op.getOperand(0).getValueType() == MVT::i64)
10084 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10086 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10087 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10088 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10089 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10092 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10093 // a simple subregister reference or explicit instructions to grab
10094 // upper bits of a vector.
10095 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10096 SelectionDAG &DAG) {
10098 SDValue In = Op.getOperand(0);
10099 SDValue Idx = Op.getOperand(1);
10100 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10101 MVT ResVT = Op.getSimpleValueType();
10102 MVT InVT = In.getSimpleValueType();
10104 if (Subtarget->hasFp256()) {
10105 if (ResVT.is128BitVector() &&
10106 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10107 isa<ConstantSDNode>(Idx)) {
10108 return Extract128BitVector(In, IdxVal, DAG, dl);
10110 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10111 isa<ConstantSDNode>(Idx)) {
10112 return Extract256BitVector(In, IdxVal, DAG, dl);
10118 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10119 // simple superregister reference or explicit instructions to insert
10120 // the upper bits of a vector.
10121 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10122 SelectionDAG &DAG) {
10123 if (Subtarget->hasFp256()) {
10124 SDLoc dl(Op.getNode());
10125 SDValue Vec = Op.getNode()->getOperand(0);
10126 SDValue SubVec = Op.getNode()->getOperand(1);
10127 SDValue Idx = Op.getNode()->getOperand(2);
10129 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10130 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10131 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10132 isa<ConstantSDNode>(Idx)) {
10133 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10134 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10137 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10138 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10139 isa<ConstantSDNode>(Idx)) {
10140 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10141 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10147 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10148 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10149 // one of the above mentioned nodes. It has to be wrapped because otherwise
10150 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10151 // be used to form addressing mode. These wrapped nodes will be selected
10154 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10155 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10157 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10158 // global base reg.
10159 unsigned char OpFlag = 0;
10160 unsigned WrapperKind = X86ISD::Wrapper;
10161 CodeModel::Model M = DAG.getTarget().getCodeModel();
10163 if (Subtarget->isPICStyleRIPRel() &&
10164 (M == CodeModel::Small || M == CodeModel::Kernel))
10165 WrapperKind = X86ISD::WrapperRIP;
10166 else if (Subtarget->isPICStyleGOT())
10167 OpFlag = X86II::MO_GOTOFF;
10168 else if (Subtarget->isPICStyleStubPIC())
10169 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10171 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10172 CP->getAlignment(),
10173 CP->getOffset(), OpFlag);
10175 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10176 // With PIC, the address is actually $g + Offset.
10178 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10179 DAG.getNode(X86ISD::GlobalBaseReg,
10180 SDLoc(), getPointerTy()),
10187 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10188 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10190 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10191 // global base reg.
10192 unsigned char OpFlag = 0;
10193 unsigned WrapperKind = X86ISD::Wrapper;
10194 CodeModel::Model M = DAG.getTarget().getCodeModel();
10196 if (Subtarget->isPICStyleRIPRel() &&
10197 (M == CodeModel::Small || M == CodeModel::Kernel))
10198 WrapperKind = X86ISD::WrapperRIP;
10199 else if (Subtarget->isPICStyleGOT())
10200 OpFlag = X86II::MO_GOTOFF;
10201 else if (Subtarget->isPICStyleStubPIC())
10202 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10204 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10207 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10209 // With PIC, the address is actually $g + Offset.
10211 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10212 DAG.getNode(X86ISD::GlobalBaseReg,
10213 SDLoc(), getPointerTy()),
10220 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10221 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10223 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10224 // global base reg.
10225 unsigned char OpFlag = 0;
10226 unsigned WrapperKind = X86ISD::Wrapper;
10227 CodeModel::Model M = DAG.getTarget().getCodeModel();
10229 if (Subtarget->isPICStyleRIPRel() &&
10230 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10231 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10232 OpFlag = X86II::MO_GOTPCREL;
10233 WrapperKind = X86ISD::WrapperRIP;
10234 } else if (Subtarget->isPICStyleGOT()) {
10235 OpFlag = X86II::MO_GOT;
10236 } else if (Subtarget->isPICStyleStubPIC()) {
10237 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10238 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10239 OpFlag = X86II::MO_DARWIN_NONLAZY;
10242 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10245 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10247 // With PIC, the address is actually $g + Offset.
10248 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10249 !Subtarget->is64Bit()) {
10250 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10251 DAG.getNode(X86ISD::GlobalBaseReg,
10252 SDLoc(), getPointerTy()),
10256 // For symbols that require a load from a stub to get the address, emit the
10258 if (isGlobalStubReference(OpFlag))
10259 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10260 MachinePointerInfo::getGOT(), false, false, false, 0);
10266 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10267 // Create the TargetBlockAddressAddress node.
10268 unsigned char OpFlags =
10269 Subtarget->ClassifyBlockAddressReference();
10270 CodeModel::Model M = DAG.getTarget().getCodeModel();
10271 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10272 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10274 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10277 if (Subtarget->isPICStyleRIPRel() &&
10278 (M == CodeModel::Small || M == CodeModel::Kernel))
10279 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10281 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10283 // With PIC, the address is actually $g + Offset.
10284 if (isGlobalRelativeToPICBase(OpFlags)) {
10285 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10286 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10294 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10295 int64_t Offset, SelectionDAG &DAG) const {
10296 // Create the TargetGlobalAddress node, folding in the constant
10297 // offset if it is legal.
10298 unsigned char OpFlags =
10299 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10300 CodeModel::Model M = DAG.getTarget().getCodeModel();
10302 if (OpFlags == X86II::MO_NO_FLAG &&
10303 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10304 // A direct static reference to a global.
10305 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10308 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10311 if (Subtarget->isPICStyleRIPRel() &&
10312 (M == CodeModel::Small || M == CodeModel::Kernel))
10313 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10315 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10317 // With PIC, the address is actually $g + Offset.
10318 if (isGlobalRelativeToPICBase(OpFlags)) {
10319 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10320 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10324 // For globals that require a load from a stub to get the address, emit the
10326 if (isGlobalStubReference(OpFlags))
10327 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10328 MachinePointerInfo::getGOT(), false, false, false, 0);
10330 // If there was a non-zero offset that we didn't fold, create an explicit
10331 // addition for it.
10333 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10334 DAG.getConstant(Offset, getPointerTy()));
10340 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10341 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10342 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10343 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10347 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10348 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10349 unsigned char OperandFlags, bool LocalDynamic = false) {
10350 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10351 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10353 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10354 GA->getValueType(0),
10358 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10362 SDValue Ops[] = { Chain, TGA, *InFlag };
10363 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10365 SDValue Ops[] = { Chain, TGA };
10366 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10369 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10370 MFI->setAdjustsStack(true);
10372 SDValue Flag = Chain.getValue(1);
10373 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10376 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10378 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10381 SDLoc dl(GA); // ? function entry point might be better
10382 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10383 DAG.getNode(X86ISD::GlobalBaseReg,
10384 SDLoc(), PtrVT), InFlag);
10385 InFlag = Chain.getValue(1);
10387 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10390 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10392 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10394 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10395 X86::RAX, X86II::MO_TLSGD);
10398 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10404 // Get the start address of the TLS block for this module.
10405 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10406 .getInfo<X86MachineFunctionInfo>();
10407 MFI->incNumLocalDynamicTLSAccesses();
10411 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10412 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10415 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10416 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10417 InFlag = Chain.getValue(1);
10418 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10419 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10422 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10426 unsigned char OperandFlags = X86II::MO_DTPOFF;
10427 unsigned WrapperKind = X86ISD::Wrapper;
10428 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10429 GA->getValueType(0),
10430 GA->getOffset(), OperandFlags);
10431 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10433 // Add x@dtpoff with the base.
10434 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10437 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10438 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10439 const EVT PtrVT, TLSModel::Model model,
10440 bool is64Bit, bool isPIC) {
10443 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10444 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10445 is64Bit ? 257 : 256));
10447 SDValue ThreadPointer =
10448 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10449 MachinePointerInfo(Ptr), false, false, false, 0);
10451 unsigned char OperandFlags = 0;
10452 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10454 unsigned WrapperKind = X86ISD::Wrapper;
10455 if (model == TLSModel::LocalExec) {
10456 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10457 } else if (model == TLSModel::InitialExec) {
10459 OperandFlags = X86II::MO_GOTTPOFF;
10460 WrapperKind = X86ISD::WrapperRIP;
10462 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10465 llvm_unreachable("Unexpected model");
10468 // emit "addl x@ntpoff,%eax" (local exec)
10469 // or "addl x@indntpoff,%eax" (initial exec)
10470 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10472 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10473 GA->getOffset(), OperandFlags);
10474 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10476 if (model == TLSModel::InitialExec) {
10477 if (isPIC && !is64Bit) {
10478 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10479 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10483 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10484 MachinePointerInfo::getGOT(), false, false, false, 0);
10487 // The address of the thread local variable is the add of the thread
10488 // pointer with the offset of the variable.
10489 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10493 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10495 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10496 const GlobalValue *GV = GA->getGlobal();
10498 if (Subtarget->isTargetELF()) {
10499 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10502 case TLSModel::GeneralDynamic:
10503 if (Subtarget->is64Bit())
10504 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10505 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10506 case TLSModel::LocalDynamic:
10507 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10508 Subtarget->is64Bit());
10509 case TLSModel::InitialExec:
10510 case TLSModel::LocalExec:
10511 return LowerToTLSExecModel(
10512 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10513 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10515 llvm_unreachable("Unknown TLS model.");
10518 if (Subtarget->isTargetDarwin()) {
10519 // Darwin only has one model of TLS. Lower to that.
10520 unsigned char OpFlag = 0;
10521 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10522 X86ISD::WrapperRIP : X86ISD::Wrapper;
10524 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10525 // global base reg.
10526 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10527 !Subtarget->is64Bit();
10529 OpFlag = X86II::MO_TLVP_PIC_BASE;
10531 OpFlag = X86II::MO_TLVP;
10533 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10534 GA->getValueType(0),
10535 GA->getOffset(), OpFlag);
10536 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10538 // With PIC32, the address is actually $g + Offset.
10540 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10541 DAG.getNode(X86ISD::GlobalBaseReg,
10542 SDLoc(), getPointerTy()),
10545 // Lowering the machine isd will make sure everything is in the right
10547 SDValue Chain = DAG.getEntryNode();
10548 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10549 SDValue Args[] = { Chain, Offset };
10550 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10552 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10553 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10554 MFI->setAdjustsStack(true);
10556 // And our return value (tls address) is in the standard call return value
10558 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10559 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10560 Chain.getValue(1));
10563 if (Subtarget->isTargetKnownWindowsMSVC() ||
10564 Subtarget->isTargetWindowsGNU()) {
10565 // Just use the implicit TLS architecture
10566 // Need to generate someting similar to:
10567 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10569 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
10570 // mov rcx, qword [rdx+rcx*8]
10571 // mov eax, .tls$:tlsvar
10572 // [rax+rcx] contains the address
10573 // Windows 64bit: gs:0x58
10574 // Windows 32bit: fs:__tls_array
10577 SDValue Chain = DAG.getEntryNode();
10579 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10580 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10581 // use its literal value of 0x2C.
10582 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10583 ? Type::getInt8PtrTy(*DAG.getContext(),
10585 : Type::getInt32PtrTy(*DAG.getContext(),
10589 Subtarget->is64Bit()
10590 ? DAG.getIntPtrConstant(0x58)
10591 : (Subtarget->isTargetWindowsGNU()
10592 ? DAG.getIntPtrConstant(0x2C)
10593 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10595 SDValue ThreadPointer =
10596 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10597 MachinePointerInfo(Ptr), false, false, false, 0);
10599 // Load the _tls_index variable
10600 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10601 if (Subtarget->is64Bit())
10602 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10603 IDX, MachinePointerInfo(), MVT::i32,
10606 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10607 false, false, false, 0);
10609 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10611 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10613 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10614 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10615 false, false, false, 0);
10617 // Get the offset of start of .tls section
10618 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10619 GA->getValueType(0),
10620 GA->getOffset(), X86II::MO_SECREL);
10621 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10623 // The address of the thread local variable is the add of the thread
10624 // pointer with the offset of the variable.
10625 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10628 llvm_unreachable("TLS not implemented for this target.");
10631 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10632 /// and take a 2 x i32 value to shift plus a shift amount.
10633 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10634 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10635 MVT VT = Op.getSimpleValueType();
10636 unsigned VTBits = VT.getSizeInBits();
10638 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10639 SDValue ShOpLo = Op.getOperand(0);
10640 SDValue ShOpHi = Op.getOperand(1);
10641 SDValue ShAmt = Op.getOperand(2);
10642 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10643 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10645 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10646 DAG.getConstant(VTBits - 1, MVT::i8));
10647 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10648 DAG.getConstant(VTBits - 1, MVT::i8))
10649 : DAG.getConstant(0, VT);
10651 SDValue Tmp2, Tmp3;
10652 if (Op.getOpcode() == ISD::SHL_PARTS) {
10653 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10654 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10656 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10657 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10660 // If the shift amount is larger or equal than the width of a part we can't
10661 // rely on the results of shld/shrd. Insert a test and select the appropriate
10662 // values for large shift amounts.
10663 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10664 DAG.getConstant(VTBits, MVT::i8));
10665 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10666 AndNode, DAG.getConstant(0, MVT::i8));
10669 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10670 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10671 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10673 if (Op.getOpcode() == ISD::SHL_PARTS) {
10674 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10675 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10677 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10678 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10681 SDValue Ops[2] = { Lo, Hi };
10682 return DAG.getMergeValues(Ops, dl);
10685 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10686 SelectionDAG &DAG) const {
10687 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10689 if (SrcVT.isVector())
10692 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10693 "Unknown SINT_TO_FP to lower!");
10695 // These are really Legal; return the operand so the caller accepts it as
10697 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10699 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10700 Subtarget->is64Bit()) {
10705 unsigned Size = SrcVT.getSizeInBits()/8;
10706 MachineFunction &MF = DAG.getMachineFunction();
10707 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10708 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10709 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10711 MachinePointerInfo::getFixedStack(SSFI),
10713 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10716 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10718 SelectionDAG &DAG) const {
10722 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10724 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10726 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10728 unsigned ByteSize = SrcVT.getSizeInBits()/8;
10730 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10731 MachineMemOperand *MMO;
10733 int SSFI = FI->getIndex();
10735 DAG.getMachineFunction()
10736 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10737 MachineMemOperand::MOLoad, ByteSize, ByteSize);
10739 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10740 StackSlot = StackSlot.getOperand(1);
10742 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10743 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10745 Tys, Ops, SrcVT, MMO);
10748 Chain = Result.getValue(1);
10749 SDValue InFlag = Result.getValue(2);
10751 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10752 // shouldn't be necessary except that RFP cannot be live across
10753 // multiple blocks. When stackifier is fixed, they can be uncoupled.
10754 MachineFunction &MF = DAG.getMachineFunction();
10755 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10756 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10757 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10758 Tys = DAG.getVTList(MVT::Other);
10760 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10762 MachineMemOperand *MMO =
10763 DAG.getMachineFunction()
10764 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10765 MachineMemOperand::MOStore, SSFISize, SSFISize);
10767 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10768 Ops, Op.getValueType(), MMO);
10769 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10770 MachinePointerInfo::getFixedStack(SSFI),
10771 false, false, false, 0);
10777 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10778 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10779 SelectionDAG &DAG) const {
10780 // This algorithm is not obvious. Here it is what we're trying to output:
10783 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10784 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10786 haddpd %xmm0, %xmm0
10788 pshufd $0x4e, %xmm0, %xmm1
10794 LLVMContext *Context = DAG.getContext();
10796 // Build some magic constants.
10797 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10798 Constant *C0 = ConstantDataVector::get(*Context, CV0);
10799 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10801 SmallVector<Constant*,2> CV1;
10803 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10804 APInt(64, 0x4330000000000000ULL))));
10806 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10807 APInt(64, 0x4530000000000000ULL))));
10808 Constant *C1 = ConstantVector::get(CV1);
10809 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10811 // Load the 64-bit value into an XMM register.
10812 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10814 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10815 MachinePointerInfo::getConstantPool(),
10816 false, false, false, 16);
10817 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10818 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10821 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10822 MachinePointerInfo::getConstantPool(),
10823 false, false, false, 16);
10824 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10825 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10828 if (Subtarget->hasSSE3()) {
10829 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10830 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10832 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10833 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10835 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10836 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10840 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10841 DAG.getIntPtrConstant(0));
10844 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10845 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10846 SelectionDAG &DAG) const {
10848 // FP constant to bias correct the final result.
10849 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10852 // Load the 32-bit value into an XMM register.
10853 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10856 // Zero out the upper parts of the register.
10857 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10859 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10860 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10861 DAG.getIntPtrConstant(0));
10863 // Or the load with the bias.
10864 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10865 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10866 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10867 MVT::v2f64, Load)),
10868 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10869 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10870 MVT::v2f64, Bias)));
10871 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10872 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10873 DAG.getIntPtrConstant(0));
10875 // Subtract the bias.
10876 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10878 // Handle final rounding.
10879 EVT DestVT = Op.getValueType();
10881 if (DestVT.bitsLT(MVT::f64))
10882 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10883 DAG.getIntPtrConstant(0));
10884 if (DestVT.bitsGT(MVT::f64))
10885 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10887 // Handle final rounding.
10891 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10892 SelectionDAG &DAG) const {
10893 SDValue N0 = Op.getOperand(0);
10894 MVT SVT = N0.getSimpleValueType();
10897 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10898 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10899 "Custom UINT_TO_FP is not supported!");
10901 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10902 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10903 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10906 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10907 SelectionDAG &DAG) const {
10908 SDValue N0 = Op.getOperand(0);
10911 if (Op.getValueType().isVector())
10912 return lowerUINT_TO_FP_vec(Op, DAG);
10914 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10915 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10916 // the optimization here.
10917 if (DAG.SignBitIsZero(N0))
10918 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10920 MVT SrcVT = N0.getSimpleValueType();
10921 MVT DstVT = Op.getSimpleValueType();
10922 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10923 return LowerUINT_TO_FP_i64(Op, DAG);
10924 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10925 return LowerUINT_TO_FP_i32(Op, DAG);
10926 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10929 // Make a 64-bit buffer, and use it to build an FILD.
10930 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10931 if (SrcVT == MVT::i32) {
10932 SDValue WordOff = DAG.getConstant(4, getPointerTy());
10933 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10934 getPointerTy(), StackSlot, WordOff);
10935 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10936 StackSlot, MachinePointerInfo(),
10938 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10939 OffsetSlot, MachinePointerInfo(),
10941 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10945 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10946 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10947 StackSlot, MachinePointerInfo(),
10949 // For i64 source, we need to add the appropriate power of 2 if the input
10950 // was negative. This is the same as the optimization in
10951 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10952 // we must be careful to do the computation in x87 extended precision, not
10953 // in SSE. (The generic code can't know it's OK to do this, or how to.)
10954 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10955 MachineMemOperand *MMO =
10956 DAG.getMachineFunction()
10957 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10958 MachineMemOperand::MOLoad, 8, 8);
10960 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10961 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10962 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10965 APInt FF(32, 0x5F800000ULL);
10967 // Check whether the sign bit is set.
10968 SDValue SignSet = DAG.getSetCC(dl,
10969 getSetCCResultType(*DAG.getContext(), MVT::i64),
10970 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10973 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10974 SDValue FudgePtr = DAG.getConstantPool(
10975 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10978 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10979 SDValue Zero = DAG.getIntPtrConstant(0);
10980 SDValue Four = DAG.getIntPtrConstant(4);
10981 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10983 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10985 // Load the value out, extending it from f32 to f80.
10986 // FIXME: Avoid the extend by constructing the right constant pool?
10987 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10988 FudgePtr, MachinePointerInfo::getConstantPool(),
10989 MVT::f32, false, false, 4);
10990 // Extend everything to 80 bits to force it to be done on x87.
10991 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10992 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10995 std::pair<SDValue,SDValue>
10996 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
10997 bool IsSigned, bool IsReplace) const {
11000 EVT DstTy = Op.getValueType();
11002 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11003 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11007 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11008 DstTy.getSimpleVT() >= MVT::i16 &&
11009 "Unknown FP_TO_INT to lower!");
11011 // These are really Legal.
11012 if (DstTy == MVT::i32 &&
11013 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11014 return std::make_pair(SDValue(), SDValue());
11015 if (Subtarget->is64Bit() &&
11016 DstTy == MVT::i64 &&
11017 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11018 return std::make_pair(SDValue(), SDValue());
11020 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11021 // stack slot, or into the FTOL runtime function.
11022 MachineFunction &MF = DAG.getMachineFunction();
11023 unsigned MemSize = DstTy.getSizeInBits()/8;
11024 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11025 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11028 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11029 Opc = X86ISD::WIN_FTOL;
11031 switch (DstTy.getSimpleVT().SimpleTy) {
11032 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11033 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11034 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11035 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11038 SDValue Chain = DAG.getEntryNode();
11039 SDValue Value = Op.getOperand(0);
11040 EVT TheVT = Op.getOperand(0).getValueType();
11041 // FIXME This causes a redundant load/store if the SSE-class value is already
11042 // in memory, such as if it is on the callstack.
11043 if (isScalarFPTypeInSSEReg(TheVT)) {
11044 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11045 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11046 MachinePointerInfo::getFixedStack(SSFI),
11048 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11050 Chain, StackSlot, DAG.getValueType(TheVT)
11053 MachineMemOperand *MMO =
11054 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11055 MachineMemOperand::MOLoad, MemSize, MemSize);
11056 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11057 Chain = Value.getValue(1);
11058 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11059 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11062 MachineMemOperand *MMO =
11063 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11064 MachineMemOperand::MOStore, MemSize, MemSize);
11066 if (Opc != X86ISD::WIN_FTOL) {
11067 // Build the FP_TO_INT*_IN_MEM
11068 SDValue Ops[] = { Chain, Value, StackSlot };
11069 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11071 return std::make_pair(FIST, StackSlot);
11073 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11074 DAG.getVTList(MVT::Other, MVT::Glue),
11076 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11077 MVT::i32, ftol.getValue(1));
11078 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11079 MVT::i32, eax.getValue(2));
11080 SDValue Ops[] = { eax, edx };
11081 SDValue pair = IsReplace
11082 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11083 : DAG.getMergeValues(Ops, DL);
11084 return std::make_pair(pair, SDValue());
11088 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11089 const X86Subtarget *Subtarget) {
11090 MVT VT = Op->getSimpleValueType(0);
11091 SDValue In = Op->getOperand(0);
11092 MVT InVT = In.getSimpleValueType();
11095 // Optimize vectors in AVX mode:
11098 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11099 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11100 // Concat upper and lower parts.
11103 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11104 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11105 // Concat upper and lower parts.
11108 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11109 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11110 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11113 if (Subtarget->hasInt256())
11114 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11116 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11117 SDValue Undef = DAG.getUNDEF(InVT);
11118 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11119 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11120 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11122 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11123 VT.getVectorNumElements()/2);
11125 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11126 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11128 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11131 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11132 SelectionDAG &DAG) {
11133 MVT VT = Op->getSimpleValueType(0);
11134 SDValue In = Op->getOperand(0);
11135 MVT InVT = In.getSimpleValueType();
11137 unsigned int NumElts = VT.getVectorNumElements();
11138 if (NumElts != 8 && NumElts != 16)
11141 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11142 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11144 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11145 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11146 // Now we have only mask extension
11147 assert(InVT.getVectorElementType() == MVT::i1);
11148 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11149 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11150 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11151 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11152 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11153 MachinePointerInfo::getConstantPool(),
11154 false, false, false, Alignment);
11156 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11157 if (VT.is512BitVector())
11159 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11162 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11163 SelectionDAG &DAG) {
11164 if (Subtarget->hasFp256()) {
11165 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11173 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11174 SelectionDAG &DAG) {
11176 MVT VT = Op.getSimpleValueType();
11177 SDValue In = Op.getOperand(0);
11178 MVT SVT = In.getSimpleValueType();
11180 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11181 return LowerZERO_EXTEND_AVX512(Op, DAG);
11183 if (Subtarget->hasFp256()) {
11184 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11189 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11190 VT.getVectorNumElements() != SVT.getVectorNumElements());
11194 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11196 MVT VT = Op.getSimpleValueType();
11197 SDValue In = Op.getOperand(0);
11198 MVT InVT = In.getSimpleValueType();
11200 if (VT == MVT::i1) {
11201 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11202 "Invalid scalar TRUNCATE operation");
11203 if (InVT == MVT::i32)
11205 if (InVT.getSizeInBits() == 64)
11206 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11207 else if (InVT.getSizeInBits() < 32)
11208 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11209 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11211 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11212 "Invalid TRUNCATE operation");
11214 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11215 if (VT.getVectorElementType().getSizeInBits() >=8)
11216 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11218 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11219 unsigned NumElts = InVT.getVectorNumElements();
11220 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11221 if (InVT.getSizeInBits() < 512) {
11222 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11223 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11227 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11228 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11229 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11230 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11231 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11232 MachinePointerInfo::getConstantPool(),
11233 false, false, false, Alignment);
11234 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11235 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11236 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11239 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11240 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11241 if (Subtarget->hasInt256()) {
11242 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11243 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11244 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11246 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11247 DAG.getIntPtrConstant(0));
11250 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11251 DAG.getIntPtrConstant(0));
11252 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11253 DAG.getIntPtrConstant(2));
11254 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11255 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11256 static const int ShufMask[] = {0, 2, 4, 6};
11257 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11260 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11261 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11262 if (Subtarget->hasInt256()) {
11263 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11265 SmallVector<SDValue,32> pshufbMask;
11266 for (unsigned i = 0; i < 2; ++i) {
11267 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11268 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11269 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11270 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11271 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11272 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11273 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11274 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11275 for (unsigned j = 0; j < 8; ++j)
11276 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11278 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11279 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11280 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11282 static const int ShufMask[] = {0, 2, -1, -1};
11283 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11285 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11286 DAG.getIntPtrConstant(0));
11287 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11290 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11291 DAG.getIntPtrConstant(0));
11293 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11294 DAG.getIntPtrConstant(4));
11296 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11297 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11299 // The PSHUFB mask:
11300 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11301 -1, -1, -1, -1, -1, -1, -1, -1};
11303 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11304 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11305 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11307 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11308 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11310 // The MOVLHPS Mask:
11311 static const int ShufMask2[] = {0, 1, 4, 5};
11312 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11313 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11316 // Handle truncation of V256 to V128 using shuffles.
11317 if (!VT.is128BitVector() || !InVT.is256BitVector())
11320 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11322 unsigned NumElems = VT.getVectorNumElements();
11323 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11325 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11326 // Prepare truncation shuffle mask
11327 for (unsigned i = 0; i != NumElems; ++i)
11328 MaskVec[i] = i * 2;
11329 SDValue V = DAG.getVectorShuffle(NVT, DL,
11330 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11331 DAG.getUNDEF(NVT), &MaskVec[0]);
11332 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11333 DAG.getIntPtrConstant(0));
11336 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11337 SelectionDAG &DAG) const {
11338 assert(!Op.getSimpleValueType().isVector());
11340 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11341 /*IsSigned=*/ true, /*IsReplace=*/ false);
11342 SDValue FIST = Vals.first, StackSlot = Vals.second;
11343 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11344 if (!FIST.getNode()) return Op;
11346 if (StackSlot.getNode())
11347 // Load the result.
11348 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11349 FIST, StackSlot, MachinePointerInfo(),
11350 false, false, false, 0);
11352 // The node is the result.
11356 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11357 SelectionDAG &DAG) const {
11358 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11359 /*IsSigned=*/ false, /*IsReplace=*/ false);
11360 SDValue FIST = Vals.first, StackSlot = Vals.second;
11361 assert(FIST.getNode() && "Unexpected failure");
11363 if (StackSlot.getNode())
11364 // Load the result.
11365 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11366 FIST, StackSlot, MachinePointerInfo(),
11367 false, false, false, 0);
11369 // The node is the result.
11373 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11375 MVT VT = Op.getSimpleValueType();
11376 SDValue In = Op.getOperand(0);
11377 MVT SVT = In.getSimpleValueType();
11379 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11381 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11382 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11383 In, DAG.getUNDEF(SVT)));
11386 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11387 LLVMContext *Context = DAG.getContext();
11389 MVT VT = Op.getSimpleValueType();
11391 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11392 if (VT.isVector()) {
11393 EltVT = VT.getVectorElementType();
11394 NumElts = VT.getVectorNumElements();
11397 if (EltVT == MVT::f64)
11398 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11399 APInt(64, ~(1ULL << 63))));
11401 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11402 APInt(32, ~(1U << 31))));
11403 C = ConstantVector::getSplat(NumElts, C);
11404 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11405 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11406 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11407 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11408 MachinePointerInfo::getConstantPool(),
11409 false, false, false, Alignment);
11410 if (VT.isVector()) {
11411 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11412 return DAG.getNode(ISD::BITCAST, dl, VT,
11413 DAG.getNode(ISD::AND, dl, ANDVT,
11414 DAG.getNode(ISD::BITCAST, dl, ANDVT,
11416 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11418 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11421 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11422 LLVMContext *Context = DAG.getContext();
11424 MVT VT = Op.getSimpleValueType();
11426 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11427 if (VT.isVector()) {
11428 EltVT = VT.getVectorElementType();
11429 NumElts = VT.getVectorNumElements();
11432 if (EltVT == MVT::f64)
11433 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11434 APInt(64, 1ULL << 63)));
11436 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11437 APInt(32, 1U << 31)));
11438 C = ConstantVector::getSplat(NumElts, C);
11439 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11440 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11441 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11442 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11443 MachinePointerInfo::getConstantPool(),
11444 false, false, false, Alignment);
11445 if (VT.isVector()) {
11446 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11447 return DAG.getNode(ISD::BITCAST, dl, VT,
11448 DAG.getNode(ISD::XOR, dl, XORVT,
11449 DAG.getNode(ISD::BITCAST, dl, XORVT,
11451 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11454 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11457 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11458 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11459 LLVMContext *Context = DAG.getContext();
11460 SDValue Op0 = Op.getOperand(0);
11461 SDValue Op1 = Op.getOperand(1);
11463 MVT VT = Op.getSimpleValueType();
11464 MVT SrcVT = Op1.getSimpleValueType();
11466 // If second operand is smaller, extend it first.
11467 if (SrcVT.bitsLT(VT)) {
11468 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11471 // And if it is bigger, shrink it first.
11472 if (SrcVT.bitsGT(VT)) {
11473 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11477 // At this point the operands and the result should have the same
11478 // type, and that won't be f80 since that is not custom lowered.
11480 // First get the sign bit of second operand.
11481 SmallVector<Constant*,4> CV;
11482 if (SrcVT == MVT::f64) {
11483 const fltSemantics &Sem = APFloat::IEEEdouble;
11484 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11485 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11487 const fltSemantics &Sem = APFloat::IEEEsingle;
11488 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11489 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11490 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11491 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11493 Constant *C = ConstantVector::get(CV);
11494 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11495 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11496 MachinePointerInfo::getConstantPool(),
11497 false, false, false, 16);
11498 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11500 // Shift sign bit right or left if the two operands have different types.
11501 if (SrcVT.bitsGT(VT)) {
11502 // Op0 is MVT::f32, Op1 is MVT::f64.
11503 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11504 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11505 DAG.getConstant(32, MVT::i32));
11506 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11507 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11508 DAG.getIntPtrConstant(0));
11511 // Clear first operand sign bit.
11513 if (VT == MVT::f64) {
11514 const fltSemantics &Sem = APFloat::IEEEdouble;
11515 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11516 APInt(64, ~(1ULL << 63)))));
11517 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11519 const fltSemantics &Sem = APFloat::IEEEsingle;
11520 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11521 APInt(32, ~(1U << 31)))));
11522 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11523 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11524 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11526 C = ConstantVector::get(CV);
11527 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11528 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11529 MachinePointerInfo::getConstantPool(),
11530 false, false, false, 16);
11531 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11533 // Or the value with the sign bit.
11534 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11537 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11538 SDValue N0 = Op.getOperand(0);
11540 MVT VT = Op.getSimpleValueType();
11542 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11543 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11544 DAG.getConstant(1, VT));
11545 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11548 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11550 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11551 SelectionDAG &DAG) {
11552 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11554 if (!Subtarget->hasSSE41())
11557 if (!Op->hasOneUse())
11560 SDNode *N = Op.getNode();
11563 SmallVector<SDValue, 8> Opnds;
11564 DenseMap<SDValue, unsigned> VecInMap;
11565 SmallVector<SDValue, 8> VecIns;
11566 EVT VT = MVT::Other;
11568 // Recognize a special case where a vector is casted into wide integer to
11570 Opnds.push_back(N->getOperand(0));
11571 Opnds.push_back(N->getOperand(1));
11573 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11574 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11575 // BFS traverse all OR'd operands.
11576 if (I->getOpcode() == ISD::OR) {
11577 Opnds.push_back(I->getOperand(0));
11578 Opnds.push_back(I->getOperand(1));
11579 // Re-evaluate the number of nodes to be traversed.
11580 e += 2; // 2 more nodes (LHS and RHS) are pushed.
11584 // Quit if a non-EXTRACT_VECTOR_ELT
11585 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11588 // Quit if without a constant index.
11589 SDValue Idx = I->getOperand(1);
11590 if (!isa<ConstantSDNode>(Idx))
11593 SDValue ExtractedFromVec = I->getOperand(0);
11594 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11595 if (M == VecInMap.end()) {
11596 VT = ExtractedFromVec.getValueType();
11597 // Quit if not 128/256-bit vector.
11598 if (!VT.is128BitVector() && !VT.is256BitVector())
11600 // Quit if not the same type.
11601 if (VecInMap.begin() != VecInMap.end() &&
11602 VT != VecInMap.begin()->first.getValueType())
11604 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11605 VecIns.push_back(ExtractedFromVec);
11607 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11610 assert((VT.is128BitVector() || VT.is256BitVector()) &&
11611 "Not extracted from 128-/256-bit vector.");
11613 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11615 for (DenseMap<SDValue, unsigned>::const_iterator
11616 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11617 // Quit if not all elements are used.
11618 if (I->second != FullMask)
11622 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11624 // Cast all vectors into TestVT for PTEST.
11625 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11626 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11628 // If more than one full vectors are evaluated, OR them first before PTEST.
11629 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11630 // Each iteration will OR 2 nodes and append the result until there is only
11631 // 1 node left, i.e. the final OR'd value of all vectors.
11632 SDValue LHS = VecIns[Slot];
11633 SDValue RHS = VecIns[Slot + 1];
11634 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11637 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11638 VecIns.back(), VecIns.back());
11641 /// \brief return true if \c Op has a use that doesn't just read flags.
11642 static bool hasNonFlagsUse(SDValue Op) {
11643 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11645 SDNode *User = *UI;
11646 unsigned UOpNo = UI.getOperandNo();
11647 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11648 // Look pass truncate.
11649 UOpNo = User->use_begin().getOperandNo();
11650 User = *User->use_begin();
11653 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11654 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11660 /// Emit nodes that will be selected as "test Op0,Op0", or something
11662 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11663 SelectionDAG &DAG) const {
11664 if (Op.getValueType() == MVT::i1)
11665 // KORTEST instruction should be selected
11666 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11667 DAG.getConstant(0, Op.getValueType()));
11669 // CF and OF aren't always set the way we want. Determine which
11670 // of these we need.
11671 bool NeedCF = false;
11672 bool NeedOF = false;
11675 case X86::COND_A: case X86::COND_AE:
11676 case X86::COND_B: case X86::COND_BE:
11679 case X86::COND_G: case X86::COND_GE:
11680 case X86::COND_L: case X86::COND_LE:
11681 case X86::COND_O: case X86::COND_NO: {
11682 // Check if we really need to set the
11683 // Overflow flag. If NoSignedWrap is present
11684 // that is not actually needed.
11685 switch (Op->getOpcode()) {
11690 const BinaryWithFlagsSDNode *BinNode =
11691 cast<BinaryWithFlagsSDNode>(Op.getNode());
11692 if (BinNode->hasNoSignedWrap())
11702 // See if we can use the EFLAGS value from the operand instead of
11703 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11704 // we prove that the arithmetic won't overflow, we can't use OF or CF.
11705 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11706 // Emit a CMP with 0, which is the TEST pattern.
11707 //if (Op.getValueType() == MVT::i1)
11708 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11709 // DAG.getConstant(0, MVT::i1));
11710 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11711 DAG.getConstant(0, Op.getValueType()));
11713 unsigned Opcode = 0;
11714 unsigned NumOperands = 0;
11716 // Truncate operations may prevent the merge of the SETCC instruction
11717 // and the arithmetic instruction before it. Attempt to truncate the operands
11718 // of the arithmetic instruction and use a reduced bit-width instruction.
11719 bool NeedTruncation = false;
11720 SDValue ArithOp = Op;
11721 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11722 SDValue Arith = Op->getOperand(0);
11723 // Both the trunc and the arithmetic op need to have one user each.
11724 if (Arith->hasOneUse())
11725 switch (Arith.getOpcode()) {
11732 NeedTruncation = true;
11738 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11739 // which may be the result of a CAST. We use the variable 'Op', which is the
11740 // non-casted variable when we check for possible users.
11741 switch (ArithOp.getOpcode()) {
11743 // Due to an isel shortcoming, be conservative if this add is likely to be
11744 // selected as part of a load-modify-store instruction. When the root node
11745 // in a match is a store, isel doesn't know how to remap non-chain non-flag
11746 // uses of other nodes in the match, such as the ADD in this case. This
11747 // leads to the ADD being left around and reselected, with the result being
11748 // two adds in the output. Alas, even if none our users are stores, that
11749 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
11750 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
11751 // climbing the DAG back to the root, and it doesn't seem to be worth the
11753 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11754 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11755 if (UI->getOpcode() != ISD::CopyToReg &&
11756 UI->getOpcode() != ISD::SETCC &&
11757 UI->getOpcode() != ISD::STORE)
11760 if (ConstantSDNode *C =
11761 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11762 // An add of one will be selected as an INC.
11763 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11764 Opcode = X86ISD::INC;
11769 // An add of negative one (subtract of one) will be selected as a DEC.
11770 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11771 Opcode = X86ISD::DEC;
11777 // Otherwise use a regular EFLAGS-setting add.
11778 Opcode = X86ISD::ADD;
11783 // If we have a constant logical shift that's only used in a comparison
11784 // against zero turn it into an equivalent AND. This allows turning it into
11785 // a TEST instruction later.
11786 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11787 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11788 EVT VT = Op.getValueType();
11789 unsigned BitWidth = VT.getSizeInBits();
11790 unsigned ShAmt = Op->getConstantOperandVal(1);
11791 if (ShAmt >= BitWidth) // Avoid undefined shifts.
11793 APInt Mask = ArithOp.getOpcode() == ISD::SRL
11794 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11795 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11796 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11798 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11799 DAG.getConstant(Mask, VT));
11800 DAG.ReplaceAllUsesWith(Op, New);
11806 // If the primary and result isn't used, don't bother using X86ISD::AND,
11807 // because a TEST instruction will be better.
11808 if (!hasNonFlagsUse(Op))
11814 // Due to the ISEL shortcoming noted above, be conservative if this op is
11815 // likely to be selected as part of a load-modify-store instruction.
11816 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11817 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11818 if (UI->getOpcode() == ISD::STORE)
11821 // Otherwise use a regular EFLAGS-setting instruction.
11822 switch (ArithOp.getOpcode()) {
11823 default: llvm_unreachable("unexpected operator!");
11824 case ISD::SUB: Opcode = X86ISD::SUB; break;
11825 case ISD::XOR: Opcode = X86ISD::XOR; break;
11826 case ISD::AND: Opcode = X86ISD::AND; break;
11828 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11829 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11830 if (EFLAGS.getNode())
11833 Opcode = X86ISD::OR;
11847 return SDValue(Op.getNode(), 1);
11853 // If we found that truncation is beneficial, perform the truncation and
11855 if (NeedTruncation) {
11856 EVT VT = Op.getValueType();
11857 SDValue WideVal = Op->getOperand(0);
11858 EVT WideVT = WideVal.getValueType();
11859 unsigned ConvertedOp = 0;
11860 // Use a target machine opcode to prevent further DAGCombine
11861 // optimizations that may separate the arithmetic operations
11862 // from the setcc node.
11863 switch (WideVal.getOpcode()) {
11865 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11866 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11867 case ISD::AND: ConvertedOp = X86ISD::AND; break;
11868 case ISD::OR: ConvertedOp = X86ISD::OR; break;
11869 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11873 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11874 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11875 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11876 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11877 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11883 // Emit a CMP with 0, which is the TEST pattern.
11884 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11885 DAG.getConstant(0, Op.getValueType()));
11887 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11888 SmallVector<SDValue, 4> Ops;
11889 for (unsigned i = 0; i != NumOperands; ++i)
11890 Ops.push_back(Op.getOperand(i));
11892 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11893 DAG.ReplaceAllUsesWith(Op, New);
11894 return SDValue(New.getNode(), 1);
11897 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11899 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11900 SDLoc dl, SelectionDAG &DAG) const {
11901 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11902 if (C->getAPIntValue() == 0)
11903 return EmitTest(Op0, X86CC, dl, DAG);
11905 if (Op0.getValueType() == MVT::i1)
11906 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11909 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11910 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11911 // Do the comparison at i32 if it's smaller, besides the Atom case.
11912 // This avoids subregister aliasing issues. Keep the smaller reference
11913 // if we're optimizing for size, however, as that'll allow better folding
11914 // of memory operations.
11915 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11916 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11917 AttributeSet::FunctionIndex, Attribute::MinSize) &&
11918 !Subtarget->isAtom()) {
11919 unsigned ExtendOp =
11920 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11921 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11922 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11924 // Use SUB instead of CMP to enable CSE between SUB and CMP.
11925 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11926 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11928 return SDValue(Sub.getNode(), 1);
11930 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11933 /// Convert a comparison if required by the subtarget.
11934 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11935 SelectionDAG &DAG) const {
11936 // If the subtarget does not support the FUCOMI instruction, floating-point
11937 // comparisons have to be converted.
11938 if (Subtarget->hasCMov() ||
11939 Cmp.getOpcode() != X86ISD::CMP ||
11940 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11941 !Cmp.getOperand(1).getValueType().isFloatingPoint())
11944 // The instruction selector will select an FUCOM instruction instead of
11945 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11946 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11947 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11949 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11950 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11951 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11952 DAG.getConstant(8, MVT::i8));
11953 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11954 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11957 static bool isAllOnes(SDValue V) {
11958 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11959 return C && C->isAllOnesValue();
11962 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11963 /// if it's possible.
11964 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11965 SDLoc dl, SelectionDAG &DAG) const {
11966 SDValue Op0 = And.getOperand(0);
11967 SDValue Op1 = And.getOperand(1);
11968 if (Op0.getOpcode() == ISD::TRUNCATE)
11969 Op0 = Op0.getOperand(0);
11970 if (Op1.getOpcode() == ISD::TRUNCATE)
11971 Op1 = Op1.getOperand(0);
11974 if (Op1.getOpcode() == ISD::SHL)
11975 std::swap(Op0, Op1);
11976 if (Op0.getOpcode() == ISD::SHL) {
11977 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11978 if (And00C->getZExtValue() == 1) {
11979 // If we looked past a truncate, check that it's only truncating away
11981 unsigned BitWidth = Op0.getValueSizeInBits();
11982 unsigned AndBitWidth = And.getValueSizeInBits();
11983 if (BitWidth > AndBitWidth) {
11985 DAG.computeKnownBits(Op0, Zeros, Ones);
11986 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11990 RHS = Op0.getOperand(1);
11992 } else if (Op1.getOpcode() == ISD::Constant) {
11993 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11994 uint64_t AndRHSVal = AndRHS->getZExtValue();
11995 SDValue AndLHS = Op0;
11997 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
11998 LHS = AndLHS.getOperand(0);
11999 RHS = AndLHS.getOperand(1);
12002 // Use BT if the immediate can't be encoded in a TEST instruction.
12003 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12005 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12009 if (LHS.getNode()) {
12010 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12011 // instruction. Since the shift amount is in-range-or-undefined, we know
12012 // that doing a bittest on the i32 value is ok. We extend to i32 because
12013 // the encoding for the i16 version is larger than the i32 version.
12014 // Also promote i16 to i32 for performance / code size reason.
12015 if (LHS.getValueType() == MVT::i8 ||
12016 LHS.getValueType() == MVT::i16)
12017 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12019 // If the operand types disagree, extend the shift amount to match. Since
12020 // BT ignores high bits (like shifts) we can use anyextend.
12021 if (LHS.getValueType() != RHS.getValueType())
12022 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12024 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12025 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12026 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12027 DAG.getConstant(Cond, MVT::i8), BT);
12033 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12035 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12040 // SSE Condition code mapping:
12049 switch (SetCCOpcode) {
12050 default: llvm_unreachable("Unexpected SETCC condition");
12052 case ISD::SETEQ: SSECC = 0; break;
12054 case ISD::SETGT: Swap = true; // Fallthrough
12056 case ISD::SETOLT: SSECC = 1; break;
12058 case ISD::SETGE: Swap = true; // Fallthrough
12060 case ISD::SETOLE: SSECC = 2; break;
12061 case ISD::SETUO: SSECC = 3; break;
12063 case ISD::SETNE: SSECC = 4; break;
12064 case ISD::SETULE: Swap = true; // Fallthrough
12065 case ISD::SETUGE: SSECC = 5; break;
12066 case ISD::SETULT: Swap = true; // Fallthrough
12067 case ISD::SETUGT: SSECC = 6; break;
12068 case ISD::SETO: SSECC = 7; break;
12070 case ISD::SETONE: SSECC = 8; break;
12073 std::swap(Op0, Op1);
12078 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12079 // ones, and then concatenate the result back.
12080 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12081 MVT VT = Op.getSimpleValueType();
12083 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12084 "Unsupported value type for operation");
12086 unsigned NumElems = VT.getVectorNumElements();
12088 SDValue CC = Op.getOperand(2);
12090 // Extract the LHS vectors
12091 SDValue LHS = Op.getOperand(0);
12092 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12093 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12095 // Extract the RHS vectors
12096 SDValue RHS = Op.getOperand(1);
12097 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12098 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12100 // Issue the operation on the smaller types and concatenate the result back
12101 MVT EltVT = VT.getVectorElementType();
12102 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12103 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12104 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12105 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12108 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12109 const X86Subtarget *Subtarget) {
12110 SDValue Op0 = Op.getOperand(0);
12111 SDValue Op1 = Op.getOperand(1);
12112 SDValue CC = Op.getOperand(2);
12113 MVT VT = Op.getSimpleValueType();
12116 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12117 Op.getValueType().getScalarType() == MVT::i1 &&
12118 "Cannot set masked compare for this operation");
12120 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12122 bool Unsigned = false;
12125 switch (SetCCOpcode) {
12126 default: llvm_unreachable("Unexpected SETCC condition");
12127 case ISD::SETNE: SSECC = 4; break;
12128 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12129 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12130 case ISD::SETLT: Swap = true; //fall-through
12131 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12132 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12133 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12134 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12135 case ISD::SETULE: Unsigned = true; //fall-through
12136 case ISD::SETLE: SSECC = 2; break;
12140 std::swap(Op0, Op1);
12142 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12143 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12144 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12145 DAG.getConstant(SSECC, MVT::i8));
12148 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12149 /// operand \p Op1. If non-trivial (for example because it's not constant)
12150 /// return an empty value.
12151 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12153 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12157 MVT VT = Op1.getSimpleValueType();
12158 MVT EVT = VT.getVectorElementType();
12159 unsigned n = VT.getVectorNumElements();
12160 SmallVector<SDValue, 8> ULTOp1;
12162 for (unsigned i = 0; i < n; ++i) {
12163 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12164 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12167 // Avoid underflow.
12168 APInt Val = Elt->getAPIntValue();
12172 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12175 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12178 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12179 SelectionDAG &DAG) {
12180 SDValue Op0 = Op.getOperand(0);
12181 SDValue Op1 = Op.getOperand(1);
12182 SDValue CC = Op.getOperand(2);
12183 MVT VT = Op.getSimpleValueType();
12184 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12185 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12190 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12191 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12194 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12195 unsigned Opc = X86ISD::CMPP;
12196 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12197 assert(VT.getVectorNumElements() <= 16);
12198 Opc = X86ISD::CMPM;
12200 // In the two special cases we can't handle, emit two comparisons.
12203 unsigned CombineOpc;
12204 if (SetCCOpcode == ISD::SETUEQ) {
12205 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12207 assert(SetCCOpcode == ISD::SETONE);
12208 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12211 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12212 DAG.getConstant(CC0, MVT::i8));
12213 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12214 DAG.getConstant(CC1, MVT::i8));
12215 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12217 // Handle all other FP comparisons here.
12218 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12219 DAG.getConstant(SSECC, MVT::i8));
12222 // Break 256-bit integer vector compare into smaller ones.
12223 if (VT.is256BitVector() && !Subtarget->hasInt256())
12224 return Lower256IntVSETCC(Op, DAG);
12226 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12227 EVT OpVT = Op1.getValueType();
12228 if (Subtarget->hasAVX512()) {
12229 if (Op1.getValueType().is512BitVector() ||
12230 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12231 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12233 // In AVX-512 architecture setcc returns mask with i1 elements,
12234 // But there is no compare instruction for i8 and i16 elements.
12235 // We are not talking about 512-bit operands in this case, these
12236 // types are illegal.
12238 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12239 OpVT.getVectorElementType().getSizeInBits() >= 8))
12240 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12241 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12244 // We are handling one of the integer comparisons here. Since SSE only has
12245 // GT and EQ comparisons for integer, swapping operands and multiple
12246 // operations may be required for some comparisons.
12248 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12249 bool Subus = false;
12251 switch (SetCCOpcode) {
12252 default: llvm_unreachable("Unexpected SETCC condition");
12253 case ISD::SETNE: Invert = true;
12254 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12255 case ISD::SETLT: Swap = true;
12256 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12257 case ISD::SETGE: Swap = true;
12258 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12259 Invert = true; break;
12260 case ISD::SETULT: Swap = true;
12261 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12262 FlipSigns = true; break;
12263 case ISD::SETUGE: Swap = true;
12264 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12265 FlipSigns = true; Invert = true; break;
12268 // Special case: Use min/max operations for SETULE/SETUGE
12269 MVT VET = VT.getVectorElementType();
12271 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12272 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12275 switch (SetCCOpcode) {
12277 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12278 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12281 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12284 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12285 if (!MinMax && hasSubus) {
12286 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12288 // t = psubus Op0, Op1
12289 // pcmpeq t, <0..0>
12290 switch (SetCCOpcode) {
12292 case ISD::SETULT: {
12293 // If the comparison is against a constant we can turn this into a
12294 // setule. With psubus, setule does not require a swap. This is
12295 // beneficial because the constant in the register is no longer
12296 // destructed as the destination so it can be hoisted out of a loop.
12297 // Only do this pre-AVX since vpcmp* is no longer destructive.
12298 if (Subtarget->hasAVX())
12300 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12301 if (ULEOp1.getNode()) {
12303 Subus = true; Invert = false; Swap = false;
12307 // Psubus is better than flip-sign because it requires no inversion.
12308 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
12309 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12313 Opc = X86ISD::SUBUS;
12319 std::swap(Op0, Op1);
12321 // Check that the operation in question is available (most are plain SSE2,
12322 // but PCMPGTQ and PCMPEQQ have different requirements).
12323 if (VT == MVT::v2i64) {
12324 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12325 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12327 // First cast everything to the right type.
12328 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12329 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12331 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12332 // bits of the inputs before performing those operations. The lower
12333 // compare is always unsigned.
12336 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12338 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12339 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12340 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12341 Sign, Zero, Sign, Zero);
12343 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12344 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12346 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12347 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12348 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12350 // Create masks for only the low parts/high parts of the 64 bit integers.
12351 static const int MaskHi[] = { 1, 1, 3, 3 };
12352 static const int MaskLo[] = { 0, 0, 2, 2 };
12353 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12354 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12355 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12357 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12358 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12361 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12363 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12366 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12367 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12368 // pcmpeqd + pshufd + pand.
12369 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12371 // First cast everything to the right type.
12372 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12373 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12376 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12378 // Make sure the lower and upper halves are both all-ones.
12379 static const int Mask[] = { 1, 0, 3, 2 };
12380 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12381 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12384 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12386 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12390 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12391 // bits of the inputs before performing those operations.
12393 EVT EltVT = VT.getVectorElementType();
12394 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12395 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12396 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12399 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12401 // If the logical-not of the result is required, perform that now.
12403 Result = DAG.getNOT(dl, Result, VT);
12406 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12409 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12410 getZeroVector(VT, Subtarget, DAG, dl));
12415 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12417 MVT VT = Op.getSimpleValueType();
12419 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12421 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12422 && "SetCC type must be 8-bit or 1-bit integer");
12423 SDValue Op0 = Op.getOperand(0);
12424 SDValue Op1 = Op.getOperand(1);
12426 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12428 // Optimize to BT if possible.
12429 // Lower (X & (1 << N)) == 0 to BT(X, N).
12430 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12431 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12432 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12433 Op1.getOpcode() == ISD::Constant &&
12434 cast<ConstantSDNode>(Op1)->isNullValue() &&
12435 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12436 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12437 if (NewSetCC.getNode())
12441 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
12443 if (Op1.getOpcode() == ISD::Constant &&
12444 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12445 cast<ConstantSDNode>(Op1)->isNullValue()) &&
12446 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12448 // If the input is a setcc, then reuse the input setcc or use a new one with
12449 // the inverted condition.
12450 if (Op0.getOpcode() == X86ISD::SETCC) {
12451 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12452 bool Invert = (CC == ISD::SETNE) ^
12453 cast<ConstantSDNode>(Op1)->isNullValue();
12457 CCode = X86::GetOppositeBranchCondition(CCode);
12458 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12459 DAG.getConstant(CCode, MVT::i8),
12460 Op0.getOperand(1));
12462 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12466 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12467 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12468 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12470 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12471 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12474 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12475 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12476 if (X86CC == X86::COND_INVALID)
12479 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12480 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12481 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12482 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12484 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12488 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12489 static bool isX86LogicalCmp(SDValue Op) {
12490 unsigned Opc = Op.getNode()->getOpcode();
12491 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12492 Opc == X86ISD::SAHF)
12494 if (Op.getResNo() == 1 &&
12495 (Opc == X86ISD::ADD ||
12496 Opc == X86ISD::SUB ||
12497 Opc == X86ISD::ADC ||
12498 Opc == X86ISD::SBB ||
12499 Opc == X86ISD::SMUL ||
12500 Opc == X86ISD::UMUL ||
12501 Opc == X86ISD::INC ||
12502 Opc == X86ISD::DEC ||
12503 Opc == X86ISD::OR ||
12504 Opc == X86ISD::XOR ||
12505 Opc == X86ISD::AND))
12508 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12514 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12515 if (V.getOpcode() != ISD::TRUNCATE)
12518 SDValue VOp0 = V.getOperand(0);
12519 unsigned InBits = VOp0.getValueSizeInBits();
12520 unsigned Bits = V.getValueSizeInBits();
12521 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12524 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12525 bool addTest = true;
12526 SDValue Cond = Op.getOperand(0);
12527 SDValue Op1 = Op.getOperand(1);
12528 SDValue Op2 = Op.getOperand(2);
12530 EVT VT = Op1.getValueType();
12533 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12534 // are available. Otherwise fp cmovs get lowered into a less efficient branch
12535 // sequence later on.
12536 if (Cond.getOpcode() == ISD::SETCC &&
12537 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12538 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12539 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12540 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12541 int SSECC = translateX86FSETCC(
12542 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12545 if (Subtarget->hasAVX512()) {
12546 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12547 DAG.getConstant(SSECC, MVT::i8));
12548 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12550 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12551 DAG.getConstant(SSECC, MVT::i8));
12552 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12553 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12554 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12558 if (Cond.getOpcode() == ISD::SETCC) {
12559 SDValue NewCond = LowerSETCC(Cond, DAG);
12560 if (NewCond.getNode())
12564 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12565 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12566 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12567 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12568 if (Cond.getOpcode() == X86ISD::SETCC &&
12569 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12570 isZero(Cond.getOperand(1).getOperand(1))) {
12571 SDValue Cmp = Cond.getOperand(1);
12573 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12575 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12576 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12577 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12579 SDValue CmpOp0 = Cmp.getOperand(0);
12580 // Apply further optimizations for special cases
12581 // (select (x != 0), -1, 0) -> neg & sbb
12582 // (select (x == 0), 0, -1) -> neg & sbb
12583 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12584 if (YC->isNullValue() &&
12585 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12586 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12587 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12588 DAG.getConstant(0, CmpOp0.getValueType()),
12590 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12591 DAG.getConstant(X86::COND_B, MVT::i8),
12592 SDValue(Neg.getNode(), 1));
12596 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12597 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12598 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12600 SDValue Res = // Res = 0 or -1.
12601 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12602 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12604 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12605 Res = DAG.getNOT(DL, Res, Res.getValueType());
12607 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12608 if (!N2C || !N2C->isNullValue())
12609 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12614 // Look past (and (setcc_carry (cmp ...)), 1).
12615 if (Cond.getOpcode() == ISD::AND &&
12616 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12617 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12618 if (C && C->getAPIntValue() == 1)
12619 Cond = Cond.getOperand(0);
12622 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12623 // setting operand in place of the X86ISD::SETCC.
12624 unsigned CondOpcode = Cond.getOpcode();
12625 if (CondOpcode == X86ISD::SETCC ||
12626 CondOpcode == X86ISD::SETCC_CARRY) {
12627 CC = Cond.getOperand(0);
12629 SDValue Cmp = Cond.getOperand(1);
12630 unsigned Opc = Cmp.getOpcode();
12631 MVT VT = Op.getSimpleValueType();
12633 bool IllegalFPCMov = false;
12634 if (VT.isFloatingPoint() && !VT.isVector() &&
12635 !isScalarFPTypeInSSEReg(VT)) // FPStack?
12636 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12638 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12639 Opc == X86ISD::BT) { // FIXME
12643 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12644 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12645 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12646 Cond.getOperand(0).getValueType() != MVT::i8)) {
12647 SDValue LHS = Cond.getOperand(0);
12648 SDValue RHS = Cond.getOperand(1);
12649 unsigned X86Opcode;
12652 switch (CondOpcode) {
12653 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12654 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12655 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12656 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12657 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12658 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12659 default: llvm_unreachable("unexpected overflowing operator");
12661 if (CondOpcode == ISD::UMULO)
12662 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12665 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12667 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12669 if (CondOpcode == ISD::UMULO)
12670 Cond = X86Op.getValue(2);
12672 Cond = X86Op.getValue(1);
12674 CC = DAG.getConstant(X86Cond, MVT::i8);
12679 // Look pass the truncate if the high bits are known zero.
12680 if (isTruncWithZeroHighBitsInput(Cond, DAG))
12681 Cond = Cond.getOperand(0);
12683 // We know the result of AND is compared against zero. Try to match
12685 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12686 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12687 if (NewSetCC.getNode()) {
12688 CC = NewSetCC.getOperand(0);
12689 Cond = NewSetCC.getOperand(1);
12696 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12697 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12700 // a < b ? -1 : 0 -> RES = ~setcc_carry
12701 // a < b ? 0 : -1 -> RES = setcc_carry
12702 // a >= b ? -1 : 0 -> RES = setcc_carry
12703 // a >= b ? 0 : -1 -> RES = ~setcc_carry
12704 if (Cond.getOpcode() == X86ISD::SUB) {
12705 Cond = ConvertCmpIfNecessary(Cond, DAG);
12706 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12708 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12709 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12710 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12711 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12712 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12713 return DAG.getNOT(DL, Res, Res.getValueType());
12718 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12719 // widen the cmov and push the truncate through. This avoids introducing a new
12720 // branch during isel and doesn't add any extensions.
12721 if (Op.getValueType() == MVT::i8 &&
12722 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12723 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12724 if (T1.getValueType() == T2.getValueType() &&
12725 // Blacklist CopyFromReg to avoid partial register stalls.
12726 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12727 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12728 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12729 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12733 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12734 // condition is true.
12735 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12736 SDValue Ops[] = { Op2, Op1, CC, Cond };
12737 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12740 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12741 MVT VT = Op->getSimpleValueType(0);
12742 SDValue In = Op->getOperand(0);
12743 MVT InVT = In.getSimpleValueType();
12746 unsigned int NumElts = VT.getVectorNumElements();
12747 if (NumElts != 8 && NumElts != 16)
12750 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12751 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12753 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12754 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12756 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12757 Constant *C = ConstantInt::get(*DAG.getContext(),
12758 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12760 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12761 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12762 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12763 MachinePointerInfo::getConstantPool(),
12764 false, false, false, Alignment);
12765 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12766 if (VT.is512BitVector())
12768 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12771 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12772 SelectionDAG &DAG) {
12773 MVT VT = Op->getSimpleValueType(0);
12774 SDValue In = Op->getOperand(0);
12775 MVT InVT = In.getSimpleValueType();
12778 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12779 return LowerSIGN_EXTEND_AVX512(Op, DAG);
12781 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12782 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12783 (VT != MVT::v16i16 || InVT != MVT::v16i8))
12786 if (Subtarget->hasInt256())
12787 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12789 // Optimize vectors in AVX mode
12790 // Sign extend v8i16 to v8i32 and
12793 // Divide input vector into two parts
12794 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12795 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12796 // concat the vectors to original VT
12798 unsigned NumElems = InVT.getVectorNumElements();
12799 SDValue Undef = DAG.getUNDEF(InVT);
12801 SmallVector<int,8> ShufMask1(NumElems, -1);
12802 for (unsigned i = 0; i != NumElems/2; ++i)
12805 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12807 SmallVector<int,8> ShufMask2(NumElems, -1);
12808 for (unsigned i = 0; i != NumElems/2; ++i)
12809 ShufMask2[i] = i + NumElems/2;
12811 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12813 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12814 VT.getVectorNumElements()/2);
12816 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12817 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12819 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12822 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12823 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12824 // from the AND / OR.
12825 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12826 Opc = Op.getOpcode();
12827 if (Opc != ISD::OR && Opc != ISD::AND)
12829 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12830 Op.getOperand(0).hasOneUse() &&
12831 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12832 Op.getOperand(1).hasOneUse());
12835 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12836 // 1 and that the SETCC node has a single use.
12837 static bool isXor1OfSetCC(SDValue Op) {
12838 if (Op.getOpcode() != ISD::XOR)
12840 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12841 if (N1C && N1C->getAPIntValue() == 1) {
12842 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12843 Op.getOperand(0).hasOneUse();
12848 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12849 bool addTest = true;
12850 SDValue Chain = Op.getOperand(0);
12851 SDValue Cond = Op.getOperand(1);
12852 SDValue Dest = Op.getOperand(2);
12855 bool Inverted = false;
12857 if (Cond.getOpcode() == ISD::SETCC) {
12858 // Check for setcc([su]{add,sub,mul}o == 0).
12859 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12860 isa<ConstantSDNode>(Cond.getOperand(1)) &&
12861 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12862 Cond.getOperand(0).getResNo() == 1 &&
12863 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12864 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12865 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12866 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12867 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12868 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12870 Cond = Cond.getOperand(0);
12872 SDValue NewCond = LowerSETCC(Cond, DAG);
12873 if (NewCond.getNode())
12878 // FIXME: LowerXALUO doesn't handle these!!
12879 else if (Cond.getOpcode() == X86ISD::ADD ||
12880 Cond.getOpcode() == X86ISD::SUB ||
12881 Cond.getOpcode() == X86ISD::SMUL ||
12882 Cond.getOpcode() == X86ISD::UMUL)
12883 Cond = LowerXALUO(Cond, DAG);
12886 // Look pass (and (setcc_carry (cmp ...)), 1).
12887 if (Cond.getOpcode() == ISD::AND &&
12888 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12889 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12890 if (C && C->getAPIntValue() == 1)
12891 Cond = Cond.getOperand(0);
12894 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12895 // setting operand in place of the X86ISD::SETCC.
12896 unsigned CondOpcode = Cond.getOpcode();
12897 if (CondOpcode == X86ISD::SETCC ||
12898 CondOpcode == X86ISD::SETCC_CARRY) {
12899 CC = Cond.getOperand(0);
12901 SDValue Cmp = Cond.getOperand(1);
12902 unsigned Opc = Cmp.getOpcode();
12903 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12904 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12908 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12912 // These can only come from an arithmetic instruction with overflow,
12913 // e.g. SADDO, UADDO.
12914 Cond = Cond.getNode()->getOperand(1);
12920 CondOpcode = Cond.getOpcode();
12921 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12922 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12923 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12924 Cond.getOperand(0).getValueType() != MVT::i8)) {
12925 SDValue LHS = Cond.getOperand(0);
12926 SDValue RHS = Cond.getOperand(1);
12927 unsigned X86Opcode;
12930 // Keep this in sync with LowerXALUO, otherwise we might create redundant
12931 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12933 switch (CondOpcode) {
12934 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12936 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12938 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12941 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12942 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12944 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12946 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12949 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12950 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12951 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12952 default: llvm_unreachable("unexpected overflowing operator");
12955 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12956 if (CondOpcode == ISD::UMULO)
12957 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12960 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12962 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12964 if (CondOpcode == ISD::UMULO)
12965 Cond = X86Op.getValue(2);
12967 Cond = X86Op.getValue(1);
12969 CC = DAG.getConstant(X86Cond, MVT::i8);
12973 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12974 SDValue Cmp = Cond.getOperand(0).getOperand(1);
12975 if (CondOpc == ISD::OR) {
12976 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12977 // two branches instead of an explicit OR instruction with a
12979 if (Cmp == Cond.getOperand(1).getOperand(1) &&
12980 isX86LogicalCmp(Cmp)) {
12981 CC = Cond.getOperand(0).getOperand(0);
12982 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12983 Chain, Dest, CC, Cmp);
12984 CC = Cond.getOperand(1).getOperand(0);
12988 } else { // ISD::AND
12989 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12990 // two branches instead of an explicit AND instruction with a
12991 // separate test. However, we only do this if this block doesn't
12992 // have a fall-through edge, because this requires an explicit
12993 // jmp when the condition is false.
12994 if (Cmp == Cond.getOperand(1).getOperand(1) &&
12995 isX86LogicalCmp(Cmp) &&
12996 Op.getNode()->hasOneUse()) {
12997 X86::CondCode CCode =
12998 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12999 CCode = X86::GetOppositeBranchCondition(CCode);
13000 CC = DAG.getConstant(CCode, MVT::i8);
13001 SDNode *User = *Op.getNode()->use_begin();
13002 // Look for an unconditional branch following this conditional branch.
13003 // We need this because we need to reverse the successors in order
13004 // to implement FCMP_OEQ.
13005 if (User->getOpcode() == ISD::BR) {
13006 SDValue FalseBB = User->getOperand(1);
13008 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13009 assert(NewBR == User);
13013 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13014 Chain, Dest, CC, Cmp);
13015 X86::CondCode CCode =
13016 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13017 CCode = X86::GetOppositeBranchCondition(CCode);
13018 CC = DAG.getConstant(CCode, MVT::i8);
13024 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13025 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13026 // It should be transformed during dag combiner except when the condition
13027 // is set by a arithmetics with overflow node.
13028 X86::CondCode CCode =
13029 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13030 CCode = X86::GetOppositeBranchCondition(CCode);
13031 CC = DAG.getConstant(CCode, MVT::i8);
13032 Cond = Cond.getOperand(0).getOperand(1);
13034 } else if (Cond.getOpcode() == ISD::SETCC &&
13035 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13036 // For FCMP_OEQ, we can emit
13037 // two branches instead of an explicit AND instruction with a
13038 // separate test. However, we only do this if this block doesn't
13039 // have a fall-through edge, because this requires an explicit
13040 // jmp when the condition is false.
13041 if (Op.getNode()->hasOneUse()) {
13042 SDNode *User = *Op.getNode()->use_begin();
13043 // Look for an unconditional branch following this conditional branch.
13044 // We need this because we need to reverse the successors in order
13045 // to implement FCMP_OEQ.
13046 if (User->getOpcode() == ISD::BR) {
13047 SDValue FalseBB = User->getOperand(1);
13049 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13050 assert(NewBR == User);
13054 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13055 Cond.getOperand(0), Cond.getOperand(1));
13056 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13057 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13058 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13059 Chain, Dest, CC, Cmp);
13060 CC = DAG.getConstant(X86::COND_P, MVT::i8);
13065 } else if (Cond.getOpcode() == ISD::SETCC &&
13066 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13067 // For FCMP_UNE, we can emit
13068 // two branches instead of an explicit AND instruction with a
13069 // separate test. However, we only do this if this block doesn't
13070 // have a fall-through edge, because this requires an explicit
13071 // jmp when the condition is false.
13072 if (Op.getNode()->hasOneUse()) {
13073 SDNode *User = *Op.getNode()->use_begin();
13074 // Look for an unconditional branch following this conditional branch.
13075 // We need this because we need to reverse the successors in order
13076 // to implement FCMP_UNE.
13077 if (User->getOpcode() == ISD::BR) {
13078 SDValue FalseBB = User->getOperand(1);
13080 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13081 assert(NewBR == User);
13084 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13085 Cond.getOperand(0), Cond.getOperand(1));
13086 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13087 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13088 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13089 Chain, Dest, CC, Cmp);
13090 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13100 // Look pass the truncate if the high bits are known zero.
13101 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13102 Cond = Cond.getOperand(0);
13104 // We know the result of AND is compared against zero. Try to match
13106 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13107 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13108 if (NewSetCC.getNode()) {
13109 CC = NewSetCC.getOperand(0);
13110 Cond = NewSetCC.getOperand(1);
13117 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13118 CC = DAG.getConstant(X86Cond, MVT::i8);
13119 Cond = EmitTest(Cond, X86Cond, dl, DAG);
13121 Cond = ConvertCmpIfNecessary(Cond, DAG);
13122 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13123 Chain, Dest, CC, Cond);
13126 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13127 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13128 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13129 // that the guard pages used by the OS virtual memory manager are allocated in
13130 // correct sequence.
13132 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13133 SelectionDAG &DAG) const {
13134 MachineFunction &MF = DAG.getMachineFunction();
13135 bool SplitStack = MF.shouldSplitStack();
13136 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13141 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13142 SDNode* Node = Op.getNode();
13144 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13145 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13146 " not tell us which reg is the stack pointer!");
13147 EVT VT = Node->getValueType(0);
13148 SDValue Tmp1 = SDValue(Node, 0);
13149 SDValue Tmp2 = SDValue(Node, 1);
13150 SDValue Tmp3 = Node->getOperand(2);
13151 SDValue Chain = Tmp1.getOperand(0);
13153 // Chain the dynamic stack allocation so that it doesn't modify the stack
13154 // pointer when other instructions are using the stack.
13155 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13158 SDValue Size = Tmp2.getOperand(1);
13159 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13160 Chain = SP.getValue(1);
13161 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13162 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13163 unsigned StackAlign = TFI.getStackAlignment();
13164 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13165 if (Align > StackAlign)
13166 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13167 DAG.getConstant(-(uint64_t)Align, VT));
13168 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13170 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13171 DAG.getIntPtrConstant(0, true), SDValue(),
13174 SDValue Ops[2] = { Tmp1, Tmp2 };
13175 return DAG.getMergeValues(Ops, dl);
13179 SDValue Chain = Op.getOperand(0);
13180 SDValue Size = Op.getOperand(1);
13181 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13182 EVT VT = Op.getNode()->getValueType(0);
13184 bool Is64Bit = Subtarget->is64Bit();
13185 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13188 MachineRegisterInfo &MRI = MF.getRegInfo();
13191 // The 64 bit implementation of segmented stacks needs to clobber both r10
13192 // r11. This makes it impossible to use it along with nested parameters.
13193 const Function *F = MF.getFunction();
13195 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13197 if (I->hasNestAttr())
13198 report_fatal_error("Cannot use segmented stacks with functions that "
13199 "have nested arguments.");
13202 const TargetRegisterClass *AddrRegClass =
13203 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13204 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13205 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13206 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13207 DAG.getRegister(Vreg, SPTy));
13208 SDValue Ops1[2] = { Value, Chain };
13209 return DAG.getMergeValues(Ops1, dl);
13212 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13214 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13215 Flag = Chain.getValue(1);
13216 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13218 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13220 const X86RegisterInfo *RegInfo =
13221 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13222 unsigned SPReg = RegInfo->getStackRegister();
13223 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13224 Chain = SP.getValue(1);
13227 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13228 DAG.getConstant(-(uint64_t)Align, VT));
13229 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13232 SDValue Ops1[2] = { SP, Chain };
13233 return DAG.getMergeValues(Ops1, dl);
13237 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13238 MachineFunction &MF = DAG.getMachineFunction();
13239 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13241 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13244 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13245 // vastart just stores the address of the VarArgsFrameIndex slot into the
13246 // memory location argument.
13247 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13249 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13250 MachinePointerInfo(SV), false, false, 0);
13254 // gp_offset (0 - 6 * 8)
13255 // fp_offset (48 - 48 + 8 * 16)
13256 // overflow_arg_area (point to parameters coming in memory).
13258 SmallVector<SDValue, 8> MemOps;
13259 SDValue FIN = Op.getOperand(1);
13261 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13262 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13264 FIN, MachinePointerInfo(SV), false, false, 0);
13265 MemOps.push_back(Store);
13268 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13269 FIN, DAG.getIntPtrConstant(4));
13270 Store = DAG.getStore(Op.getOperand(0), DL,
13271 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13273 FIN, MachinePointerInfo(SV, 4), false, false, 0);
13274 MemOps.push_back(Store);
13276 // Store ptr to overflow_arg_area
13277 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13278 FIN, DAG.getIntPtrConstant(4));
13279 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13281 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13282 MachinePointerInfo(SV, 8),
13284 MemOps.push_back(Store);
13286 // Store ptr to reg_save_area.
13287 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13288 FIN, DAG.getIntPtrConstant(8));
13289 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13291 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13292 MachinePointerInfo(SV, 16), false, false, 0);
13293 MemOps.push_back(Store);
13294 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13297 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13298 assert(Subtarget->is64Bit() &&
13299 "LowerVAARG only handles 64-bit va_arg!");
13300 assert((Subtarget->isTargetLinux() ||
13301 Subtarget->isTargetDarwin()) &&
13302 "Unhandled target in LowerVAARG");
13303 assert(Op.getNode()->getNumOperands() == 4);
13304 SDValue Chain = Op.getOperand(0);
13305 SDValue SrcPtr = Op.getOperand(1);
13306 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13307 unsigned Align = Op.getConstantOperandVal(3);
13310 EVT ArgVT = Op.getNode()->getValueType(0);
13311 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13312 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13315 // Decide which area this value should be read from.
13316 // TODO: Implement the AMD64 ABI in its entirety. This simple
13317 // selection mechanism works only for the basic types.
13318 if (ArgVT == MVT::f80) {
13319 llvm_unreachable("va_arg for f80 not yet implemented");
13320 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13321 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
13322 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13323 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
13325 llvm_unreachable("Unhandled argument type in LowerVAARG");
13328 if (ArgMode == 2) {
13329 // Sanity Check: Make sure using fp_offset makes sense.
13330 assert(!DAG.getTarget().Options.UseSoftFloat &&
13331 !(DAG.getMachineFunction()
13332 .getFunction()->getAttributes()
13333 .hasAttribute(AttributeSet::FunctionIndex,
13334 Attribute::NoImplicitFloat)) &&
13335 Subtarget->hasSSE1());
13338 // Insert VAARG_64 node into the DAG
13339 // VAARG_64 returns two values: Variable Argument Address, Chain
13340 SmallVector<SDValue, 11> InstOps;
13341 InstOps.push_back(Chain);
13342 InstOps.push_back(SrcPtr);
13343 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13344 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13345 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13346 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13347 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13348 VTs, InstOps, MVT::i64,
13349 MachinePointerInfo(SV),
13351 /*Volatile=*/false,
13353 /*WriteMem=*/true);
13354 Chain = VAARG.getValue(1);
13356 // Load the next argument and return it
13357 return DAG.getLoad(ArgVT, dl,
13360 MachinePointerInfo(),
13361 false, false, false, 0);
13364 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13365 SelectionDAG &DAG) {
13366 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13367 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13368 SDValue Chain = Op.getOperand(0);
13369 SDValue DstPtr = Op.getOperand(1);
13370 SDValue SrcPtr = Op.getOperand(2);
13371 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13372 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13375 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13376 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13378 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13381 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13382 // amount is a constant. Takes immediate version of shift as input.
13383 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13384 SDValue SrcOp, uint64_t ShiftAmt,
13385 SelectionDAG &DAG) {
13386 MVT ElementType = VT.getVectorElementType();
13388 // Fold this packed shift into its first operand if ShiftAmt is 0.
13392 // Check for ShiftAmt >= element width
13393 if (ShiftAmt >= ElementType.getSizeInBits()) {
13394 if (Opc == X86ISD::VSRAI)
13395 ShiftAmt = ElementType.getSizeInBits() - 1;
13397 return DAG.getConstant(0, VT);
13400 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13401 && "Unknown target vector shift-by-constant node");
13403 // Fold this packed vector shift into a build vector if SrcOp is a
13404 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13405 if (VT == SrcOp.getSimpleValueType() &&
13406 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13407 SmallVector<SDValue, 8> Elts;
13408 unsigned NumElts = SrcOp->getNumOperands();
13409 ConstantSDNode *ND;
13412 default: llvm_unreachable(nullptr);
13413 case X86ISD::VSHLI:
13414 for (unsigned i=0; i!=NumElts; ++i) {
13415 SDValue CurrentOp = SrcOp->getOperand(i);
13416 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13417 Elts.push_back(CurrentOp);
13420 ND = cast<ConstantSDNode>(CurrentOp);
13421 const APInt &C = ND->getAPIntValue();
13422 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13425 case X86ISD::VSRLI:
13426 for (unsigned i=0; i!=NumElts; ++i) {
13427 SDValue CurrentOp = SrcOp->getOperand(i);
13428 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13429 Elts.push_back(CurrentOp);
13432 ND = cast<ConstantSDNode>(CurrentOp);
13433 const APInt &C = ND->getAPIntValue();
13434 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13437 case X86ISD::VSRAI:
13438 for (unsigned i=0; i!=NumElts; ++i) {
13439 SDValue CurrentOp = SrcOp->getOperand(i);
13440 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13441 Elts.push_back(CurrentOp);
13444 ND = cast<ConstantSDNode>(CurrentOp);
13445 const APInt &C = ND->getAPIntValue();
13446 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13451 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13454 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13457 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13458 // may or may not be a constant. Takes immediate version of shift as input.
13459 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13460 SDValue SrcOp, SDValue ShAmt,
13461 SelectionDAG &DAG) {
13462 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13464 // Catch shift-by-constant.
13465 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13466 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13467 CShAmt->getZExtValue(), DAG);
13469 // Change opcode to non-immediate version
13471 default: llvm_unreachable("Unknown target vector shift node");
13472 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13473 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13474 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13477 // Need to build a vector containing shift amount
13478 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13481 ShOps[1] = DAG.getConstant(0, MVT::i32);
13482 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13483 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13485 // The return type has to be a 128-bit type with the same element
13486 // type as the input type.
13487 MVT EltVT = VT.getVectorElementType();
13488 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13490 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13491 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13494 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13496 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13498 default: return SDValue(); // Don't custom lower most intrinsics.
13499 // Comparison intrinsics.
13500 case Intrinsic::x86_sse_comieq_ss:
13501 case Intrinsic::x86_sse_comilt_ss:
13502 case Intrinsic::x86_sse_comile_ss:
13503 case Intrinsic::x86_sse_comigt_ss:
13504 case Intrinsic::x86_sse_comige_ss:
13505 case Intrinsic::x86_sse_comineq_ss:
13506 case Intrinsic::x86_sse_ucomieq_ss:
13507 case Intrinsic::x86_sse_ucomilt_ss:
13508 case Intrinsic::x86_sse_ucomile_ss:
13509 case Intrinsic::x86_sse_ucomigt_ss:
13510 case Intrinsic::x86_sse_ucomige_ss:
13511 case Intrinsic::x86_sse_ucomineq_ss:
13512 case Intrinsic::x86_sse2_comieq_sd:
13513 case Intrinsic::x86_sse2_comilt_sd:
13514 case Intrinsic::x86_sse2_comile_sd:
13515 case Intrinsic::x86_sse2_comigt_sd:
13516 case Intrinsic::x86_sse2_comige_sd:
13517 case Intrinsic::x86_sse2_comineq_sd:
13518 case Intrinsic::x86_sse2_ucomieq_sd:
13519 case Intrinsic::x86_sse2_ucomilt_sd:
13520 case Intrinsic::x86_sse2_ucomile_sd:
13521 case Intrinsic::x86_sse2_ucomigt_sd:
13522 case Intrinsic::x86_sse2_ucomige_sd:
13523 case Intrinsic::x86_sse2_ucomineq_sd: {
13527 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13528 case Intrinsic::x86_sse_comieq_ss:
13529 case Intrinsic::x86_sse2_comieq_sd:
13530 Opc = X86ISD::COMI;
13533 case Intrinsic::x86_sse_comilt_ss:
13534 case Intrinsic::x86_sse2_comilt_sd:
13535 Opc = X86ISD::COMI;
13538 case Intrinsic::x86_sse_comile_ss:
13539 case Intrinsic::x86_sse2_comile_sd:
13540 Opc = X86ISD::COMI;
13543 case Intrinsic::x86_sse_comigt_ss:
13544 case Intrinsic::x86_sse2_comigt_sd:
13545 Opc = X86ISD::COMI;
13548 case Intrinsic::x86_sse_comige_ss:
13549 case Intrinsic::x86_sse2_comige_sd:
13550 Opc = X86ISD::COMI;
13553 case Intrinsic::x86_sse_comineq_ss:
13554 case Intrinsic::x86_sse2_comineq_sd:
13555 Opc = X86ISD::COMI;
13558 case Intrinsic::x86_sse_ucomieq_ss:
13559 case Intrinsic::x86_sse2_ucomieq_sd:
13560 Opc = X86ISD::UCOMI;
13563 case Intrinsic::x86_sse_ucomilt_ss:
13564 case Intrinsic::x86_sse2_ucomilt_sd:
13565 Opc = X86ISD::UCOMI;
13568 case Intrinsic::x86_sse_ucomile_ss:
13569 case Intrinsic::x86_sse2_ucomile_sd:
13570 Opc = X86ISD::UCOMI;
13573 case Intrinsic::x86_sse_ucomigt_ss:
13574 case Intrinsic::x86_sse2_ucomigt_sd:
13575 Opc = X86ISD::UCOMI;
13578 case Intrinsic::x86_sse_ucomige_ss:
13579 case Intrinsic::x86_sse2_ucomige_sd:
13580 Opc = X86ISD::UCOMI;
13583 case Intrinsic::x86_sse_ucomineq_ss:
13584 case Intrinsic::x86_sse2_ucomineq_sd:
13585 Opc = X86ISD::UCOMI;
13590 SDValue LHS = Op.getOperand(1);
13591 SDValue RHS = Op.getOperand(2);
13592 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13593 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13594 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13595 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13596 DAG.getConstant(X86CC, MVT::i8), Cond);
13597 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13600 // Arithmetic intrinsics.
13601 case Intrinsic::x86_sse2_pmulu_dq:
13602 case Intrinsic::x86_avx2_pmulu_dq:
13603 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13604 Op.getOperand(1), Op.getOperand(2));
13606 case Intrinsic::x86_sse41_pmuldq:
13607 case Intrinsic::x86_avx2_pmul_dq:
13608 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13609 Op.getOperand(1), Op.getOperand(2));
13611 case Intrinsic::x86_sse2_pmulhu_w:
13612 case Intrinsic::x86_avx2_pmulhu_w:
13613 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13614 Op.getOperand(1), Op.getOperand(2));
13616 case Intrinsic::x86_sse2_pmulh_w:
13617 case Intrinsic::x86_avx2_pmulh_w:
13618 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13619 Op.getOperand(1), Op.getOperand(2));
13621 // SSE2/AVX2 sub with unsigned saturation intrinsics
13622 case Intrinsic::x86_sse2_psubus_b:
13623 case Intrinsic::x86_sse2_psubus_w:
13624 case Intrinsic::x86_avx2_psubus_b:
13625 case Intrinsic::x86_avx2_psubus_w:
13626 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13627 Op.getOperand(1), Op.getOperand(2));
13629 // SSE3/AVX horizontal add/sub intrinsics
13630 case Intrinsic::x86_sse3_hadd_ps:
13631 case Intrinsic::x86_sse3_hadd_pd:
13632 case Intrinsic::x86_avx_hadd_ps_256:
13633 case Intrinsic::x86_avx_hadd_pd_256:
13634 case Intrinsic::x86_sse3_hsub_ps:
13635 case Intrinsic::x86_sse3_hsub_pd:
13636 case Intrinsic::x86_avx_hsub_ps_256:
13637 case Intrinsic::x86_avx_hsub_pd_256:
13638 case Intrinsic::x86_ssse3_phadd_w_128:
13639 case Intrinsic::x86_ssse3_phadd_d_128:
13640 case Intrinsic::x86_avx2_phadd_w:
13641 case Intrinsic::x86_avx2_phadd_d:
13642 case Intrinsic::x86_ssse3_phsub_w_128:
13643 case Intrinsic::x86_ssse3_phsub_d_128:
13644 case Intrinsic::x86_avx2_phsub_w:
13645 case Intrinsic::x86_avx2_phsub_d: {
13648 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13649 case Intrinsic::x86_sse3_hadd_ps:
13650 case Intrinsic::x86_sse3_hadd_pd:
13651 case Intrinsic::x86_avx_hadd_ps_256:
13652 case Intrinsic::x86_avx_hadd_pd_256:
13653 Opcode = X86ISD::FHADD;
13655 case Intrinsic::x86_sse3_hsub_ps:
13656 case Intrinsic::x86_sse3_hsub_pd:
13657 case Intrinsic::x86_avx_hsub_ps_256:
13658 case Intrinsic::x86_avx_hsub_pd_256:
13659 Opcode = X86ISD::FHSUB;
13661 case Intrinsic::x86_ssse3_phadd_w_128:
13662 case Intrinsic::x86_ssse3_phadd_d_128:
13663 case Intrinsic::x86_avx2_phadd_w:
13664 case Intrinsic::x86_avx2_phadd_d:
13665 Opcode = X86ISD::HADD;
13667 case Intrinsic::x86_ssse3_phsub_w_128:
13668 case Intrinsic::x86_ssse3_phsub_d_128:
13669 case Intrinsic::x86_avx2_phsub_w:
13670 case Intrinsic::x86_avx2_phsub_d:
13671 Opcode = X86ISD::HSUB;
13674 return DAG.getNode(Opcode, dl, Op.getValueType(),
13675 Op.getOperand(1), Op.getOperand(2));
13678 // SSE2/SSE41/AVX2 integer max/min intrinsics.
13679 case Intrinsic::x86_sse2_pmaxu_b:
13680 case Intrinsic::x86_sse41_pmaxuw:
13681 case Intrinsic::x86_sse41_pmaxud:
13682 case Intrinsic::x86_avx2_pmaxu_b:
13683 case Intrinsic::x86_avx2_pmaxu_w:
13684 case Intrinsic::x86_avx2_pmaxu_d:
13685 case Intrinsic::x86_sse2_pminu_b:
13686 case Intrinsic::x86_sse41_pminuw:
13687 case Intrinsic::x86_sse41_pminud:
13688 case Intrinsic::x86_avx2_pminu_b:
13689 case Intrinsic::x86_avx2_pminu_w:
13690 case Intrinsic::x86_avx2_pminu_d:
13691 case Intrinsic::x86_sse41_pmaxsb:
13692 case Intrinsic::x86_sse2_pmaxs_w:
13693 case Intrinsic::x86_sse41_pmaxsd:
13694 case Intrinsic::x86_avx2_pmaxs_b:
13695 case Intrinsic::x86_avx2_pmaxs_w:
13696 case Intrinsic::x86_avx2_pmaxs_d:
13697 case Intrinsic::x86_sse41_pminsb:
13698 case Intrinsic::x86_sse2_pmins_w:
13699 case Intrinsic::x86_sse41_pminsd:
13700 case Intrinsic::x86_avx2_pmins_b:
13701 case Intrinsic::x86_avx2_pmins_w:
13702 case Intrinsic::x86_avx2_pmins_d: {
13705 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13706 case Intrinsic::x86_sse2_pmaxu_b:
13707 case Intrinsic::x86_sse41_pmaxuw:
13708 case Intrinsic::x86_sse41_pmaxud:
13709 case Intrinsic::x86_avx2_pmaxu_b:
13710 case Intrinsic::x86_avx2_pmaxu_w:
13711 case Intrinsic::x86_avx2_pmaxu_d:
13712 Opcode = X86ISD::UMAX;
13714 case Intrinsic::x86_sse2_pminu_b:
13715 case Intrinsic::x86_sse41_pminuw:
13716 case Intrinsic::x86_sse41_pminud:
13717 case Intrinsic::x86_avx2_pminu_b:
13718 case Intrinsic::x86_avx2_pminu_w:
13719 case Intrinsic::x86_avx2_pminu_d:
13720 Opcode = X86ISD::UMIN;
13722 case Intrinsic::x86_sse41_pmaxsb:
13723 case Intrinsic::x86_sse2_pmaxs_w:
13724 case Intrinsic::x86_sse41_pmaxsd:
13725 case Intrinsic::x86_avx2_pmaxs_b:
13726 case Intrinsic::x86_avx2_pmaxs_w:
13727 case Intrinsic::x86_avx2_pmaxs_d:
13728 Opcode = X86ISD::SMAX;
13730 case Intrinsic::x86_sse41_pminsb:
13731 case Intrinsic::x86_sse2_pmins_w:
13732 case Intrinsic::x86_sse41_pminsd:
13733 case Intrinsic::x86_avx2_pmins_b:
13734 case Intrinsic::x86_avx2_pmins_w:
13735 case Intrinsic::x86_avx2_pmins_d:
13736 Opcode = X86ISD::SMIN;
13739 return DAG.getNode(Opcode, dl, Op.getValueType(),
13740 Op.getOperand(1), Op.getOperand(2));
13743 // SSE/SSE2/AVX floating point max/min intrinsics.
13744 case Intrinsic::x86_sse_max_ps:
13745 case Intrinsic::x86_sse2_max_pd:
13746 case Intrinsic::x86_avx_max_ps_256:
13747 case Intrinsic::x86_avx_max_pd_256:
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: {
13754 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13755 case Intrinsic::x86_sse_max_ps:
13756 case Intrinsic::x86_sse2_max_pd:
13757 case Intrinsic::x86_avx_max_ps_256:
13758 case Intrinsic::x86_avx_max_pd_256:
13759 Opcode = X86ISD::FMAX;
13761 case Intrinsic::x86_sse_min_ps:
13762 case Intrinsic::x86_sse2_min_pd:
13763 case Intrinsic::x86_avx_min_ps_256:
13764 case Intrinsic::x86_avx_min_pd_256:
13765 Opcode = X86ISD::FMIN;
13768 return DAG.getNode(Opcode, dl, Op.getValueType(),
13769 Op.getOperand(1), Op.getOperand(2));
13772 // AVX2 variable shift intrinsics
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:
13777 case Intrinsic::x86_avx2_psrlv_d:
13778 case Intrinsic::x86_avx2_psrlv_q:
13779 case Intrinsic::x86_avx2_psrlv_d_256:
13780 case Intrinsic::x86_avx2_psrlv_q_256:
13781 case Intrinsic::x86_avx2_psrav_d:
13782 case Intrinsic::x86_avx2_psrav_d_256: {
13785 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13786 case Intrinsic::x86_avx2_psllv_d:
13787 case Intrinsic::x86_avx2_psllv_q:
13788 case Intrinsic::x86_avx2_psllv_d_256:
13789 case Intrinsic::x86_avx2_psllv_q_256:
13792 case Intrinsic::x86_avx2_psrlv_d:
13793 case Intrinsic::x86_avx2_psrlv_q:
13794 case Intrinsic::x86_avx2_psrlv_d_256:
13795 case Intrinsic::x86_avx2_psrlv_q_256:
13798 case Intrinsic::x86_avx2_psrav_d:
13799 case Intrinsic::x86_avx2_psrav_d_256:
13803 return DAG.getNode(Opcode, dl, Op.getValueType(),
13804 Op.getOperand(1), Op.getOperand(2));
13807 case Intrinsic::x86_sse2_packssdw_128:
13808 case Intrinsic::x86_sse2_packsswb_128:
13809 case Intrinsic::x86_avx2_packssdw:
13810 case Intrinsic::x86_avx2_packsswb:
13811 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13812 Op.getOperand(1), Op.getOperand(2));
13814 case Intrinsic::x86_sse2_packuswb_128:
13815 case Intrinsic::x86_sse41_packusdw:
13816 case Intrinsic::x86_avx2_packuswb:
13817 case Intrinsic::x86_avx2_packusdw:
13818 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13819 Op.getOperand(1), Op.getOperand(2));
13821 case Intrinsic::x86_ssse3_pshuf_b_128:
13822 case Intrinsic::x86_avx2_pshuf_b:
13823 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13824 Op.getOperand(1), Op.getOperand(2));
13826 case Intrinsic::x86_sse2_pshuf_d:
13827 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13828 Op.getOperand(1), Op.getOperand(2));
13830 case Intrinsic::x86_sse2_pshufl_w:
13831 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13832 Op.getOperand(1), Op.getOperand(2));
13834 case Intrinsic::x86_sse2_pshufh_w:
13835 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13836 Op.getOperand(1), Op.getOperand(2));
13838 case Intrinsic::x86_ssse3_psign_b_128:
13839 case Intrinsic::x86_ssse3_psign_w_128:
13840 case Intrinsic::x86_ssse3_psign_d_128:
13841 case Intrinsic::x86_avx2_psign_b:
13842 case Intrinsic::x86_avx2_psign_w:
13843 case Intrinsic::x86_avx2_psign_d:
13844 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13845 Op.getOperand(1), Op.getOperand(2));
13847 case Intrinsic::x86_sse41_insertps:
13848 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13849 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13851 case Intrinsic::x86_avx_vperm2f128_ps_256:
13852 case Intrinsic::x86_avx_vperm2f128_pd_256:
13853 case Intrinsic::x86_avx_vperm2f128_si_256:
13854 case Intrinsic::x86_avx2_vperm2i128:
13855 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13856 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13858 case Intrinsic::x86_avx2_permd:
13859 case Intrinsic::x86_avx2_permps:
13860 // Operands intentionally swapped. Mask is last operand to intrinsic,
13861 // but second operand for node/instruction.
13862 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13863 Op.getOperand(2), Op.getOperand(1));
13865 case Intrinsic::x86_sse_sqrt_ps:
13866 case Intrinsic::x86_sse2_sqrt_pd:
13867 case Intrinsic::x86_avx_sqrt_ps_256:
13868 case Intrinsic::x86_avx_sqrt_pd_256:
13869 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13871 // ptest and testp intrinsics. The intrinsic these come from are designed to
13872 // return an integer value, not just an instruction so lower it to the ptest
13873 // or testp pattern and a setcc for the result.
13874 case Intrinsic::x86_sse41_ptestz:
13875 case Intrinsic::x86_sse41_ptestc:
13876 case Intrinsic::x86_sse41_ptestnzc:
13877 case Intrinsic::x86_avx_ptestz_256:
13878 case Intrinsic::x86_avx_ptestc_256:
13879 case Intrinsic::x86_avx_ptestnzc_256:
13880 case Intrinsic::x86_avx_vtestz_ps:
13881 case Intrinsic::x86_avx_vtestc_ps:
13882 case Intrinsic::x86_avx_vtestnzc_ps:
13883 case Intrinsic::x86_avx_vtestz_pd:
13884 case Intrinsic::x86_avx_vtestc_pd:
13885 case Intrinsic::x86_avx_vtestnzc_pd:
13886 case Intrinsic::x86_avx_vtestz_ps_256:
13887 case Intrinsic::x86_avx_vtestc_ps_256:
13888 case Intrinsic::x86_avx_vtestnzc_ps_256:
13889 case Intrinsic::x86_avx_vtestz_pd_256:
13890 case Intrinsic::x86_avx_vtestc_pd_256:
13891 case Intrinsic::x86_avx_vtestnzc_pd_256: {
13892 bool IsTestPacked = false;
13895 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13896 case Intrinsic::x86_avx_vtestz_ps:
13897 case Intrinsic::x86_avx_vtestz_pd:
13898 case Intrinsic::x86_avx_vtestz_ps_256:
13899 case Intrinsic::x86_avx_vtestz_pd_256:
13900 IsTestPacked = true; // Fallthrough
13901 case Intrinsic::x86_sse41_ptestz:
13902 case Intrinsic::x86_avx_ptestz_256:
13904 X86CC = X86::COND_E;
13906 case Intrinsic::x86_avx_vtestc_ps:
13907 case Intrinsic::x86_avx_vtestc_pd:
13908 case Intrinsic::x86_avx_vtestc_ps_256:
13909 case Intrinsic::x86_avx_vtestc_pd_256:
13910 IsTestPacked = true; // Fallthrough
13911 case Intrinsic::x86_sse41_ptestc:
13912 case Intrinsic::x86_avx_ptestc_256:
13914 X86CC = X86::COND_B;
13916 case Intrinsic::x86_avx_vtestnzc_ps:
13917 case Intrinsic::x86_avx_vtestnzc_pd:
13918 case Intrinsic::x86_avx_vtestnzc_ps_256:
13919 case Intrinsic::x86_avx_vtestnzc_pd_256:
13920 IsTestPacked = true; // Fallthrough
13921 case Intrinsic::x86_sse41_ptestnzc:
13922 case Intrinsic::x86_avx_ptestnzc_256:
13924 X86CC = X86::COND_A;
13928 SDValue LHS = Op.getOperand(1);
13929 SDValue RHS = Op.getOperand(2);
13930 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13931 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13932 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13933 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13934 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13936 case Intrinsic::x86_avx512_kortestz_w:
13937 case Intrinsic::x86_avx512_kortestc_w: {
13938 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13939 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13940 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13941 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13942 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13943 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13944 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13947 // SSE/AVX shift intrinsics
13948 case Intrinsic::x86_sse2_psll_w:
13949 case Intrinsic::x86_sse2_psll_d:
13950 case Intrinsic::x86_sse2_psll_q:
13951 case Intrinsic::x86_avx2_psll_w:
13952 case Intrinsic::x86_avx2_psll_d:
13953 case Intrinsic::x86_avx2_psll_q:
13954 case Intrinsic::x86_sse2_psrl_w:
13955 case Intrinsic::x86_sse2_psrl_d:
13956 case Intrinsic::x86_sse2_psrl_q:
13957 case Intrinsic::x86_avx2_psrl_w:
13958 case Intrinsic::x86_avx2_psrl_d:
13959 case Intrinsic::x86_avx2_psrl_q:
13960 case Intrinsic::x86_sse2_psra_w:
13961 case Intrinsic::x86_sse2_psra_d:
13962 case Intrinsic::x86_avx2_psra_w:
13963 case Intrinsic::x86_avx2_psra_d: {
13966 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13967 case Intrinsic::x86_sse2_psll_w:
13968 case Intrinsic::x86_sse2_psll_d:
13969 case Intrinsic::x86_sse2_psll_q:
13970 case Intrinsic::x86_avx2_psll_w:
13971 case Intrinsic::x86_avx2_psll_d:
13972 case Intrinsic::x86_avx2_psll_q:
13973 Opcode = X86ISD::VSHL;
13975 case Intrinsic::x86_sse2_psrl_w:
13976 case Intrinsic::x86_sse2_psrl_d:
13977 case Intrinsic::x86_sse2_psrl_q:
13978 case Intrinsic::x86_avx2_psrl_w:
13979 case Intrinsic::x86_avx2_psrl_d:
13980 case Intrinsic::x86_avx2_psrl_q:
13981 Opcode = X86ISD::VSRL;
13983 case Intrinsic::x86_sse2_psra_w:
13984 case Intrinsic::x86_sse2_psra_d:
13985 case Intrinsic::x86_avx2_psra_w:
13986 case Intrinsic::x86_avx2_psra_d:
13987 Opcode = X86ISD::VSRA;
13990 return DAG.getNode(Opcode, dl, Op.getValueType(),
13991 Op.getOperand(1), Op.getOperand(2));
13994 // SSE/AVX immediate shift intrinsics
13995 case Intrinsic::x86_sse2_pslli_w:
13996 case Intrinsic::x86_sse2_pslli_d:
13997 case Intrinsic::x86_sse2_pslli_q:
13998 case Intrinsic::x86_avx2_pslli_w:
13999 case Intrinsic::x86_avx2_pslli_d:
14000 case Intrinsic::x86_avx2_pslli_q:
14001 case Intrinsic::x86_sse2_psrli_w:
14002 case Intrinsic::x86_sse2_psrli_d:
14003 case Intrinsic::x86_sse2_psrli_q:
14004 case Intrinsic::x86_avx2_psrli_w:
14005 case Intrinsic::x86_avx2_psrli_d:
14006 case Intrinsic::x86_avx2_psrli_q:
14007 case Intrinsic::x86_sse2_psrai_w:
14008 case Intrinsic::x86_sse2_psrai_d:
14009 case Intrinsic::x86_avx2_psrai_w:
14010 case Intrinsic::x86_avx2_psrai_d: {
14013 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14014 case Intrinsic::x86_sse2_pslli_w:
14015 case Intrinsic::x86_sse2_pslli_d:
14016 case Intrinsic::x86_sse2_pslli_q:
14017 case Intrinsic::x86_avx2_pslli_w:
14018 case Intrinsic::x86_avx2_pslli_d:
14019 case Intrinsic::x86_avx2_pslli_q:
14020 Opcode = X86ISD::VSHLI;
14022 case Intrinsic::x86_sse2_psrli_w:
14023 case Intrinsic::x86_sse2_psrli_d:
14024 case Intrinsic::x86_sse2_psrli_q:
14025 case Intrinsic::x86_avx2_psrli_w:
14026 case Intrinsic::x86_avx2_psrli_d:
14027 case Intrinsic::x86_avx2_psrli_q:
14028 Opcode = X86ISD::VSRLI;
14030 case Intrinsic::x86_sse2_psrai_w:
14031 case Intrinsic::x86_sse2_psrai_d:
14032 case Intrinsic::x86_avx2_psrai_w:
14033 case Intrinsic::x86_avx2_psrai_d:
14034 Opcode = X86ISD::VSRAI;
14037 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14038 Op.getOperand(1), Op.getOperand(2), DAG);
14041 case Intrinsic::x86_sse42_pcmpistria128:
14042 case Intrinsic::x86_sse42_pcmpestria128:
14043 case Intrinsic::x86_sse42_pcmpistric128:
14044 case Intrinsic::x86_sse42_pcmpestric128:
14045 case Intrinsic::x86_sse42_pcmpistrio128:
14046 case Intrinsic::x86_sse42_pcmpestrio128:
14047 case Intrinsic::x86_sse42_pcmpistris128:
14048 case Intrinsic::x86_sse42_pcmpestris128:
14049 case Intrinsic::x86_sse42_pcmpistriz128:
14050 case Intrinsic::x86_sse42_pcmpestriz128: {
14054 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14055 case Intrinsic::x86_sse42_pcmpistria128:
14056 Opcode = X86ISD::PCMPISTRI;
14057 X86CC = X86::COND_A;
14059 case Intrinsic::x86_sse42_pcmpestria128:
14060 Opcode = X86ISD::PCMPESTRI;
14061 X86CC = X86::COND_A;
14063 case Intrinsic::x86_sse42_pcmpistric128:
14064 Opcode = X86ISD::PCMPISTRI;
14065 X86CC = X86::COND_B;
14067 case Intrinsic::x86_sse42_pcmpestric128:
14068 Opcode = X86ISD::PCMPESTRI;
14069 X86CC = X86::COND_B;
14071 case Intrinsic::x86_sse42_pcmpistrio128:
14072 Opcode = X86ISD::PCMPISTRI;
14073 X86CC = X86::COND_O;
14075 case Intrinsic::x86_sse42_pcmpestrio128:
14076 Opcode = X86ISD::PCMPESTRI;
14077 X86CC = X86::COND_O;
14079 case Intrinsic::x86_sse42_pcmpistris128:
14080 Opcode = X86ISD::PCMPISTRI;
14081 X86CC = X86::COND_S;
14083 case Intrinsic::x86_sse42_pcmpestris128:
14084 Opcode = X86ISD::PCMPESTRI;
14085 X86CC = X86::COND_S;
14087 case Intrinsic::x86_sse42_pcmpistriz128:
14088 Opcode = X86ISD::PCMPISTRI;
14089 X86CC = X86::COND_E;
14091 case Intrinsic::x86_sse42_pcmpestriz128:
14092 Opcode = X86ISD::PCMPESTRI;
14093 X86CC = X86::COND_E;
14096 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14097 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14098 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14099 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14100 DAG.getConstant(X86CC, MVT::i8),
14101 SDValue(PCMP.getNode(), 1));
14102 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14105 case Intrinsic::x86_sse42_pcmpistri128:
14106 case Intrinsic::x86_sse42_pcmpestri128: {
14108 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14109 Opcode = X86ISD::PCMPISTRI;
14111 Opcode = X86ISD::PCMPESTRI;
14113 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14114 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14115 return DAG.getNode(Opcode, dl, VTs, NewOps);
14117 case Intrinsic::x86_fma_vfmadd_ps:
14118 case Intrinsic::x86_fma_vfmadd_pd:
14119 case Intrinsic::x86_fma_vfmsub_ps:
14120 case Intrinsic::x86_fma_vfmsub_pd:
14121 case Intrinsic::x86_fma_vfnmadd_ps:
14122 case Intrinsic::x86_fma_vfnmadd_pd:
14123 case Intrinsic::x86_fma_vfnmsub_ps:
14124 case Intrinsic::x86_fma_vfnmsub_pd:
14125 case Intrinsic::x86_fma_vfmaddsub_ps:
14126 case Intrinsic::x86_fma_vfmaddsub_pd:
14127 case Intrinsic::x86_fma_vfmsubadd_ps:
14128 case Intrinsic::x86_fma_vfmsubadd_pd:
14129 case Intrinsic::x86_fma_vfmadd_ps_256:
14130 case Intrinsic::x86_fma_vfmadd_pd_256:
14131 case Intrinsic::x86_fma_vfmsub_ps_256:
14132 case Intrinsic::x86_fma_vfmsub_pd_256:
14133 case Intrinsic::x86_fma_vfnmadd_ps_256:
14134 case Intrinsic::x86_fma_vfnmadd_pd_256:
14135 case Intrinsic::x86_fma_vfnmsub_ps_256:
14136 case Intrinsic::x86_fma_vfnmsub_pd_256:
14137 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14138 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14139 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14140 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14141 case Intrinsic::x86_fma_vfmadd_ps_512:
14142 case Intrinsic::x86_fma_vfmadd_pd_512:
14143 case Intrinsic::x86_fma_vfmsub_ps_512:
14144 case Intrinsic::x86_fma_vfmsub_pd_512:
14145 case Intrinsic::x86_fma_vfnmadd_ps_512:
14146 case Intrinsic::x86_fma_vfnmadd_pd_512:
14147 case Intrinsic::x86_fma_vfnmsub_ps_512:
14148 case Intrinsic::x86_fma_vfnmsub_pd_512:
14149 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14150 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14151 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14152 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14155 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14156 case Intrinsic::x86_fma_vfmadd_ps:
14157 case Intrinsic::x86_fma_vfmadd_pd:
14158 case Intrinsic::x86_fma_vfmadd_ps_256:
14159 case Intrinsic::x86_fma_vfmadd_pd_256:
14160 case Intrinsic::x86_fma_vfmadd_ps_512:
14161 case Intrinsic::x86_fma_vfmadd_pd_512:
14162 Opc = X86ISD::FMADD;
14164 case Intrinsic::x86_fma_vfmsub_ps:
14165 case Intrinsic::x86_fma_vfmsub_pd:
14166 case Intrinsic::x86_fma_vfmsub_ps_256:
14167 case Intrinsic::x86_fma_vfmsub_pd_256:
14168 case Intrinsic::x86_fma_vfmsub_ps_512:
14169 case Intrinsic::x86_fma_vfmsub_pd_512:
14170 Opc = X86ISD::FMSUB;
14172 case Intrinsic::x86_fma_vfnmadd_ps:
14173 case Intrinsic::x86_fma_vfnmadd_pd:
14174 case Intrinsic::x86_fma_vfnmadd_ps_256:
14175 case Intrinsic::x86_fma_vfnmadd_pd_256:
14176 case Intrinsic::x86_fma_vfnmadd_ps_512:
14177 case Intrinsic::x86_fma_vfnmadd_pd_512:
14178 Opc = X86ISD::FNMADD;
14180 case Intrinsic::x86_fma_vfnmsub_ps:
14181 case Intrinsic::x86_fma_vfnmsub_pd:
14182 case Intrinsic::x86_fma_vfnmsub_ps_256:
14183 case Intrinsic::x86_fma_vfnmsub_pd_256:
14184 case Intrinsic::x86_fma_vfnmsub_ps_512:
14185 case Intrinsic::x86_fma_vfnmsub_pd_512:
14186 Opc = X86ISD::FNMSUB;
14188 case Intrinsic::x86_fma_vfmaddsub_ps:
14189 case Intrinsic::x86_fma_vfmaddsub_pd:
14190 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14191 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14192 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14193 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14194 Opc = X86ISD::FMADDSUB;
14196 case Intrinsic::x86_fma_vfmsubadd_ps:
14197 case Intrinsic::x86_fma_vfmsubadd_pd:
14198 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14199 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14200 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14201 case Intrinsic::x86_fma_vfmsubadd_pd_512:
14202 Opc = X86ISD::FMSUBADD;
14206 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14207 Op.getOperand(2), Op.getOperand(3));
14212 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14213 SDValue Src, SDValue Mask, SDValue Base,
14214 SDValue Index, SDValue ScaleOp, SDValue Chain,
14215 const X86Subtarget * Subtarget) {
14217 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14218 assert(C && "Invalid scale type");
14219 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14220 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14221 Index.getSimpleValueType().getVectorNumElements());
14223 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14225 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14227 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14228 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14229 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14230 SDValue Segment = DAG.getRegister(0, MVT::i32);
14231 if (Src.getOpcode() == ISD::UNDEF)
14232 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14233 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14234 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14235 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14236 return DAG.getMergeValues(RetOps, dl);
14239 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14240 SDValue Src, SDValue Mask, SDValue Base,
14241 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14243 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14244 assert(C && "Invalid scale type");
14245 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14246 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14247 SDValue Segment = DAG.getRegister(0, MVT::i32);
14248 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14249 Index.getSimpleValueType().getVectorNumElements());
14251 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14253 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14255 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14256 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14257 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14258 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14259 return SDValue(Res, 1);
14262 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14263 SDValue Mask, SDValue Base, SDValue Index,
14264 SDValue ScaleOp, SDValue Chain) {
14266 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14267 assert(C && "Invalid scale type");
14268 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14269 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14270 SDValue Segment = DAG.getRegister(0, MVT::i32);
14272 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14274 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14276 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14278 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14279 //SDVTList VTs = DAG.getVTList(MVT::Other);
14280 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14281 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14282 return SDValue(Res, 0);
14285 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14286 // read performance monitor counters (x86_rdpmc).
14287 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14288 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14289 SmallVectorImpl<SDValue> &Results) {
14290 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14291 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14294 // The ECX register is used to select the index of the performance counter
14296 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14298 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14300 // Reads the content of a 64-bit performance counter and returns it in the
14301 // registers EDX:EAX.
14302 if (Subtarget->is64Bit()) {
14303 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14304 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14307 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14308 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14311 Chain = HI.getValue(1);
14313 if (Subtarget->is64Bit()) {
14314 // The EAX register is loaded with the low-order 32 bits. The EDX register
14315 // is loaded with the supported high-order bits of the counter.
14316 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14317 DAG.getConstant(32, MVT::i8));
14318 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14319 Results.push_back(Chain);
14323 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14324 SDValue Ops[] = { LO, HI };
14325 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14326 Results.push_back(Pair);
14327 Results.push_back(Chain);
14330 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14331 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14332 // also used to custom lower READCYCLECOUNTER nodes.
14333 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14334 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14335 SmallVectorImpl<SDValue> &Results) {
14336 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14337 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14340 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14341 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14342 // and the EAX register is loaded with the low-order 32 bits.
14343 if (Subtarget->is64Bit()) {
14344 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14345 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14348 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14349 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14352 SDValue Chain = HI.getValue(1);
14354 if (Opcode == X86ISD::RDTSCP_DAG) {
14355 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14357 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14358 // the ECX register. Add 'ecx' explicitly to the chain.
14359 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14361 // Explicitly store the content of ECX at the location passed in input
14362 // to the 'rdtscp' intrinsic.
14363 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14364 MachinePointerInfo(), false, false, 0);
14367 if (Subtarget->is64Bit()) {
14368 // The EDX register is loaded with the high-order 32 bits of the MSR, and
14369 // the EAX register is loaded with the low-order 32 bits.
14370 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14371 DAG.getConstant(32, MVT::i8));
14372 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14373 Results.push_back(Chain);
14377 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14378 SDValue Ops[] = { LO, HI };
14379 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14380 Results.push_back(Pair);
14381 Results.push_back(Chain);
14384 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14385 SelectionDAG &DAG) {
14386 SmallVector<SDValue, 2> Results;
14388 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14390 return DAG.getMergeValues(Results, DL);
14393 enum IntrinsicType {
14394 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14397 struct IntrinsicData {
14398 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14399 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14400 IntrinsicType Type;
14405 std::map < unsigned, IntrinsicData> IntrMap;
14406 static void InitIntinsicsMap() {
14407 static bool Initialized = false;
14410 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14411 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14412 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14413 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14414 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14415 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14416 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14417 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14418 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14419 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14420 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
14421 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14422 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
14423 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14424 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
14425 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14426 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
14427 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14429 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14430 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14431 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
14432 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14433 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
14434 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14435 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
14436 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14437 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
14438 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14439 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
14440 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14441 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
14442 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14443 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
14444 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14446 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
14447 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14448 X86::VGATHERPF1QPSm)));
14449 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
14450 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14451 X86::VGATHERPF1QPDm)));
14452 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
14453 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14454 X86::VGATHERPF1DPDm)));
14455 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
14456 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14457 X86::VGATHERPF1DPSm)));
14458 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
14459 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14460 X86::VSCATTERPF1QPSm)));
14461 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
14462 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14463 X86::VSCATTERPF1QPDm)));
14464 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
14465 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14466 X86::VSCATTERPF1DPDm)));
14467 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
14468 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14469 X86::VSCATTERPF1DPSm)));
14470 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14471 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14472 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14473 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14474 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14475 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14476 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14477 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14478 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14479 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14480 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14481 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14482 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14483 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
14484 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14485 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
14486 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14487 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
14488 IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14489 IntrinsicData(RDPMC, X86ISD::RDPMC_DAG, 0)));
14490 Initialized = true;
14493 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14494 SelectionDAG &DAG) {
14495 InitIntinsicsMap();
14496 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14497 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14498 if (itr == IntrMap.end())
14502 IntrinsicData Intr = itr->second;
14503 switch(Intr.Type) {
14506 // Emit the node with the right value type.
14507 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14508 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14510 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14511 // Otherwise return the value from Rand, which is always 0, casted to i32.
14512 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14513 DAG.getConstant(1, Op->getValueType(1)),
14514 DAG.getConstant(X86::COND_B, MVT::i32),
14515 SDValue(Result.getNode(), 1) };
14516 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14517 DAG.getVTList(Op->getValueType(1), MVT::Glue),
14520 // Return { result, isValid, chain }.
14521 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14522 SDValue(Result.getNode(), 2));
14525 //gather(v1, mask, index, base, scale);
14526 SDValue Chain = Op.getOperand(0);
14527 SDValue Src = Op.getOperand(2);
14528 SDValue Base = Op.getOperand(3);
14529 SDValue Index = Op.getOperand(4);
14530 SDValue Mask = Op.getOperand(5);
14531 SDValue Scale = Op.getOperand(6);
14532 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14536 //scatter(base, mask, index, v1, scale);
14537 SDValue Chain = Op.getOperand(0);
14538 SDValue Base = Op.getOperand(2);
14539 SDValue Mask = Op.getOperand(3);
14540 SDValue Index = Op.getOperand(4);
14541 SDValue Src = Op.getOperand(5);
14542 SDValue Scale = Op.getOperand(6);
14543 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14546 SDValue Hint = Op.getOperand(6);
14548 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14549 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14550 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14551 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14552 SDValue Chain = Op.getOperand(0);
14553 SDValue Mask = Op.getOperand(2);
14554 SDValue Index = Op.getOperand(3);
14555 SDValue Base = Op.getOperand(4);
14556 SDValue Scale = Op.getOperand(5);
14557 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14559 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14561 SmallVector<SDValue, 2> Results;
14562 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14563 return DAG.getMergeValues(Results, dl);
14565 // Read Performance Monitoring Counters.
14567 SmallVector<SDValue, 2> Results;
14568 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14569 return DAG.getMergeValues(Results, dl);
14571 // XTEST intrinsics.
14573 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14574 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14575 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14576 DAG.getConstant(X86::COND_NE, MVT::i8),
14578 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14579 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14580 Ret, SDValue(InTrans.getNode(), 1));
14583 llvm_unreachable("Unknown Intrinsic Type");
14586 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14587 SelectionDAG &DAG) const {
14588 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14589 MFI->setReturnAddressIsTaken(true);
14591 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14594 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14596 EVT PtrVT = getPointerTy();
14599 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14600 const X86RegisterInfo *RegInfo =
14601 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14602 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14603 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14604 DAG.getNode(ISD::ADD, dl, PtrVT,
14605 FrameAddr, Offset),
14606 MachinePointerInfo(), false, false, false, 0);
14609 // Just load the return address.
14610 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14611 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14612 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14615 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14616 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14617 MFI->setFrameAddressIsTaken(true);
14619 EVT VT = Op.getValueType();
14620 SDLoc dl(Op); // FIXME probably not meaningful
14621 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14622 const X86RegisterInfo *RegInfo =
14623 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14624 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14625 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14626 (FrameReg == X86::EBP && VT == MVT::i32)) &&
14627 "Invalid Frame Register!");
14628 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14630 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14631 MachinePointerInfo(),
14632 false, false, false, 0);
14636 // FIXME? Maybe this could be a TableGen attribute on some registers and
14637 // this table could be generated automatically from RegInfo.
14638 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14640 unsigned Reg = StringSwitch<unsigned>(RegName)
14641 .Case("esp", X86::ESP)
14642 .Case("rsp", X86::RSP)
14646 report_fatal_error("Invalid register name global variable");
14649 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14650 SelectionDAG &DAG) const {
14651 const X86RegisterInfo *RegInfo =
14652 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14653 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14656 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14657 SDValue Chain = Op.getOperand(0);
14658 SDValue Offset = Op.getOperand(1);
14659 SDValue Handler = Op.getOperand(2);
14662 EVT PtrVT = getPointerTy();
14663 const X86RegisterInfo *RegInfo =
14664 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14665 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14666 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14667 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14668 "Invalid Frame Register!");
14669 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14670 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14672 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14673 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14674 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14675 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14677 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14679 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14680 DAG.getRegister(StoreAddrReg, PtrVT));
14683 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14684 SelectionDAG &DAG) const {
14686 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14687 DAG.getVTList(MVT::i32, MVT::Other),
14688 Op.getOperand(0), Op.getOperand(1));
14691 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14692 SelectionDAG &DAG) const {
14694 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14695 Op.getOperand(0), Op.getOperand(1));
14698 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14699 return Op.getOperand(0);
14702 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14703 SelectionDAG &DAG) const {
14704 SDValue Root = Op.getOperand(0);
14705 SDValue Trmp = Op.getOperand(1); // trampoline
14706 SDValue FPtr = Op.getOperand(2); // nested function
14707 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14710 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14711 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14713 if (Subtarget->is64Bit()) {
14714 SDValue OutChains[6];
14716 // Large code-model.
14717 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
14718 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14720 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14721 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14723 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14725 // Load the pointer to the nested function into R11.
14726 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14727 SDValue Addr = Trmp;
14728 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14729 Addr, MachinePointerInfo(TrmpAddr),
14732 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14733 DAG.getConstant(2, MVT::i64));
14734 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14735 MachinePointerInfo(TrmpAddr, 2),
14738 // Load the 'nest' parameter value into R10.
14739 // R10 is specified in X86CallingConv.td
14740 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14741 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14742 DAG.getConstant(10, MVT::i64));
14743 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14744 Addr, MachinePointerInfo(TrmpAddr, 10),
14747 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14748 DAG.getConstant(12, MVT::i64));
14749 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14750 MachinePointerInfo(TrmpAddr, 12),
14753 // Jump to the nested function.
14754 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14755 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14756 DAG.getConstant(20, MVT::i64));
14757 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14758 Addr, MachinePointerInfo(TrmpAddr, 20),
14761 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14762 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14763 DAG.getConstant(22, MVT::i64));
14764 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14765 MachinePointerInfo(TrmpAddr, 22),
14768 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14770 const Function *Func =
14771 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14772 CallingConv::ID CC = Func->getCallingConv();
14777 llvm_unreachable("Unsupported calling convention");
14778 case CallingConv::C:
14779 case CallingConv::X86_StdCall: {
14780 // Pass 'nest' parameter in ECX.
14781 // Must be kept in sync with X86CallingConv.td
14782 NestReg = X86::ECX;
14784 // Check that ECX wasn't needed by an 'inreg' parameter.
14785 FunctionType *FTy = Func->getFunctionType();
14786 const AttributeSet &Attrs = Func->getAttributes();
14788 if (!Attrs.isEmpty() && !Func->isVarArg()) {
14789 unsigned InRegCount = 0;
14792 for (FunctionType::param_iterator I = FTy->param_begin(),
14793 E = FTy->param_end(); I != E; ++I, ++Idx)
14794 if (Attrs.hasAttribute(Idx, Attribute::InReg))
14795 // FIXME: should only count parameters that are lowered to integers.
14796 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14798 if (InRegCount > 2) {
14799 report_fatal_error("Nest register in use - reduce number of inreg"
14805 case CallingConv::X86_FastCall:
14806 case CallingConv::X86_ThisCall:
14807 case CallingConv::Fast:
14808 // Pass 'nest' parameter in EAX.
14809 // Must be kept in sync with X86CallingConv.td
14810 NestReg = X86::EAX;
14814 SDValue OutChains[4];
14815 SDValue Addr, Disp;
14817 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14818 DAG.getConstant(10, MVT::i32));
14819 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14821 // This is storing the opcode for MOV32ri.
14822 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14823 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14824 OutChains[0] = DAG.getStore(Root, dl,
14825 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14826 Trmp, MachinePointerInfo(TrmpAddr),
14829 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14830 DAG.getConstant(1, MVT::i32));
14831 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14832 MachinePointerInfo(TrmpAddr, 1),
14835 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14836 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14837 DAG.getConstant(5, MVT::i32));
14838 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14839 MachinePointerInfo(TrmpAddr, 5),
14842 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14843 DAG.getConstant(6, MVT::i32));
14844 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14845 MachinePointerInfo(TrmpAddr, 6),
14848 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14852 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14853 SelectionDAG &DAG) const {
14855 The rounding mode is in bits 11:10 of FPSR, and has the following
14857 00 Round to nearest
14862 FLT_ROUNDS, on the other hand, expects the following:
14869 To perform the conversion, we do:
14870 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14873 MachineFunction &MF = DAG.getMachineFunction();
14874 const TargetMachine &TM = MF.getTarget();
14875 const TargetFrameLowering &TFI = *TM.getFrameLowering();
14876 unsigned StackAlignment = TFI.getStackAlignment();
14877 MVT VT = Op.getSimpleValueType();
14880 // Save FP Control Word to stack slot
14881 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14882 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14884 MachineMemOperand *MMO =
14885 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14886 MachineMemOperand::MOStore, 2, 2);
14888 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14889 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14890 DAG.getVTList(MVT::Other),
14891 Ops, MVT::i16, MMO);
14893 // Load FP Control Word from stack slot
14894 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14895 MachinePointerInfo(), false, false, false, 0);
14897 // Transform as necessary
14899 DAG.getNode(ISD::SRL, DL, MVT::i16,
14900 DAG.getNode(ISD::AND, DL, MVT::i16,
14901 CWD, DAG.getConstant(0x800, MVT::i16)),
14902 DAG.getConstant(11, MVT::i8));
14904 DAG.getNode(ISD::SRL, DL, MVT::i16,
14905 DAG.getNode(ISD::AND, DL, MVT::i16,
14906 CWD, DAG.getConstant(0x400, MVT::i16)),
14907 DAG.getConstant(9, MVT::i8));
14910 DAG.getNode(ISD::AND, DL, MVT::i16,
14911 DAG.getNode(ISD::ADD, DL, MVT::i16,
14912 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14913 DAG.getConstant(1, MVT::i16)),
14914 DAG.getConstant(3, MVT::i16));
14916 return DAG.getNode((VT.getSizeInBits() < 16 ?
14917 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14920 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14921 MVT VT = Op.getSimpleValueType();
14923 unsigned NumBits = VT.getSizeInBits();
14926 Op = Op.getOperand(0);
14927 if (VT == MVT::i8) {
14928 // Zero extend to i32 since there is not an i8 bsr.
14930 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14933 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14934 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14935 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14937 // If src is zero (i.e. bsr sets ZF), returns NumBits.
14940 DAG.getConstant(NumBits+NumBits-1, OpVT),
14941 DAG.getConstant(X86::COND_E, MVT::i8),
14944 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14946 // Finally xor with NumBits-1.
14947 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14950 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14954 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14955 MVT VT = Op.getSimpleValueType();
14957 unsigned NumBits = VT.getSizeInBits();
14960 Op = Op.getOperand(0);
14961 if (VT == MVT::i8) {
14962 // Zero extend to i32 since there is not an i8 bsr.
14964 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14967 // Issue a bsr (scan bits in reverse).
14968 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14969 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14971 // And xor with NumBits-1.
14972 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14975 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14979 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14980 MVT VT = Op.getSimpleValueType();
14981 unsigned NumBits = VT.getSizeInBits();
14983 Op = Op.getOperand(0);
14985 // Issue a bsf (scan bits forward) which also sets EFLAGS.
14986 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14987 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14989 // If src is zero (i.e. bsf sets ZF), returns NumBits.
14992 DAG.getConstant(NumBits, VT),
14993 DAG.getConstant(X86::COND_E, MVT::i8),
14996 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
14999 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15000 // ones, and then concatenate the result back.
15001 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15002 MVT VT = Op.getSimpleValueType();
15004 assert(VT.is256BitVector() && VT.isInteger() &&
15005 "Unsupported value type for operation");
15007 unsigned NumElems = VT.getVectorNumElements();
15010 // Extract the LHS vectors
15011 SDValue LHS = Op.getOperand(0);
15012 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15013 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15015 // Extract the RHS vectors
15016 SDValue RHS = Op.getOperand(1);
15017 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15018 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15020 MVT EltVT = VT.getVectorElementType();
15021 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15023 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15024 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15025 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15028 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15029 assert(Op.getSimpleValueType().is256BitVector() &&
15030 Op.getSimpleValueType().isInteger() &&
15031 "Only handle AVX 256-bit vector integer operation");
15032 return Lower256IntArith(Op, DAG);
15035 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15036 assert(Op.getSimpleValueType().is256BitVector() &&
15037 Op.getSimpleValueType().isInteger() &&
15038 "Only handle AVX 256-bit vector integer operation");
15039 return Lower256IntArith(Op, DAG);
15042 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15043 SelectionDAG &DAG) {
15045 MVT VT = Op.getSimpleValueType();
15047 // Decompose 256-bit ops into smaller 128-bit ops.
15048 if (VT.is256BitVector() && !Subtarget->hasInt256())
15049 return Lower256IntArith(Op, DAG);
15051 SDValue A = Op.getOperand(0);
15052 SDValue B = Op.getOperand(1);
15054 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15055 if (VT == MVT::v4i32) {
15056 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15057 "Should not custom lower when pmuldq is available!");
15059 // Extract the odd parts.
15060 static const int UnpackMask[] = { 1, -1, 3, -1 };
15061 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15062 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15064 // Multiply the even parts.
15065 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15066 // Now multiply odd parts.
15067 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15069 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15070 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15072 // Merge the two vectors back together with a shuffle. This expands into 2
15074 static const int ShufMask[] = { 0, 4, 2, 6 };
15075 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15078 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15079 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15081 // Ahi = psrlqi(a, 32);
15082 // Bhi = psrlqi(b, 32);
15084 // AloBlo = pmuludq(a, b);
15085 // AloBhi = pmuludq(a, Bhi);
15086 // AhiBlo = pmuludq(Ahi, b);
15088 // AloBhi = psllqi(AloBhi, 32);
15089 // AhiBlo = psllqi(AhiBlo, 32);
15090 // return AloBlo + AloBhi + AhiBlo;
15092 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15093 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15095 // Bit cast to 32-bit vectors for MULUDQ
15096 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15097 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15098 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15099 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15100 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15101 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15103 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15104 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15105 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15107 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15108 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15110 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15111 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15114 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15115 assert(Subtarget->isTargetWin64() && "Unexpected target");
15116 EVT VT = Op.getValueType();
15117 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15118 "Unexpected return type for lowering");
15122 switch (Op->getOpcode()) {
15123 default: llvm_unreachable("Unexpected request for libcall!");
15124 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15125 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15126 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15127 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15128 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15129 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15133 SDValue InChain = DAG.getEntryNode();
15135 TargetLowering::ArgListTy Args;
15136 TargetLowering::ArgListEntry Entry;
15137 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15138 EVT ArgVT = Op->getOperand(i).getValueType();
15139 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15140 "Unexpected argument type for lowering");
15141 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15142 Entry.Node = StackPtr;
15143 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15145 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15146 Entry.Ty = PointerType::get(ArgTy,0);
15147 Entry.isSExt = false;
15148 Entry.isZExt = false;
15149 Args.push_back(Entry);
15152 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15155 TargetLowering::CallLoweringInfo CLI(DAG);
15156 CLI.setDebugLoc(dl).setChain(InChain)
15157 .setCallee(getLibcallCallingConv(LC),
15158 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15159 Callee, std::move(Args), 0)
15160 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15162 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15163 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15166 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15167 SelectionDAG &DAG) {
15168 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15169 EVT VT = Op0.getValueType();
15172 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15173 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15175 // PMULxD operations multiply each even value (starting at 0) of LHS with
15176 // the related value of RHS and produce a widen result.
15177 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15178 // => <2 x i64> <ae|cg>
15180 // In other word, to have all the results, we need to perform two PMULxD:
15181 // 1. one with the even values.
15182 // 2. one with the odd values.
15183 // To achieve #2, with need to place the odd values at an even position.
15185 // Place the odd value at an even position (basically, shift all values 1
15186 // step to the left):
15187 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15188 // <a|b|c|d> => <b|undef|d|undef>
15189 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15190 // <e|f|g|h> => <f|undef|h|undef>
15191 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15193 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15195 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15196 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15198 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15199 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15200 // => <2 x i64> <ae|cg>
15201 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15202 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15203 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15204 // => <2 x i64> <bf|dh>
15205 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15206 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15208 // Shuffle it back into the right order.
15209 // The internal representation is big endian.
15210 // In other words, a i64 bitcasted to 2 x i32 has its high part at index 0
15211 // and its low part at index 1.
15212 // Moreover, we have: Mul1 = <ae|cg> ; Mul2 = <bf|dh>
15213 // Vector index 0 1 ; 2 3
15214 // We want <ae|bf|cg|dh>
15215 // Vector index 0 2 1 3
15216 // Since each element is seen as 2 x i32, we get:
15217 // high_mask[i] = 2 x vector_index[i]
15218 // low_mask[i] = 2 x vector_index[i] + 1
15219 // where vector_index = {0, Size/2, 1, Size/2 + 1, ...,
15220 // Size/2 - 1, Size/2 + Size/2 - 1}
15221 // where Size is the number of element of the final vector.
15222 SDValue Highs, Lows;
15223 if (VT == MVT::v8i32) {
15224 const int HighMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15225 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15226 const int LowMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15227 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15229 const int HighMask[] = {0, 4, 2, 6};
15230 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15231 const int LowMask[] = {1, 5, 3, 7};
15232 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15235 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15236 // unsigned multiply.
15237 if (IsSigned && !Subtarget->hasSSE41()) {
15239 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15240 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15241 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15242 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15243 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15245 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15246 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15249 // The low part of a MUL_LOHI is supposed to be the first value and the
15250 // high part the second value.
15251 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Lows, Highs);
15254 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15255 const X86Subtarget *Subtarget) {
15256 MVT VT = Op.getSimpleValueType();
15258 SDValue R = Op.getOperand(0);
15259 SDValue Amt = Op.getOperand(1);
15261 // Optimize shl/srl/sra with constant shift amount.
15262 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15263 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15264 uint64_t ShiftAmt = ShiftConst->getZExtValue();
15266 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15267 (Subtarget->hasInt256() &&
15268 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15269 (Subtarget->hasAVX512() &&
15270 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15271 if (Op.getOpcode() == ISD::SHL)
15272 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15274 if (Op.getOpcode() == ISD::SRL)
15275 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15277 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15278 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15282 if (VT == MVT::v16i8) {
15283 if (Op.getOpcode() == ISD::SHL) {
15284 // Make a large shift.
15285 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15286 MVT::v8i16, R, ShiftAmt,
15288 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15289 // Zero out the rightmost bits.
15290 SmallVector<SDValue, 16> V(16,
15291 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15293 return DAG.getNode(ISD::AND, dl, VT, SHL,
15294 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15296 if (Op.getOpcode() == ISD::SRL) {
15297 // Make a large shift.
15298 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15299 MVT::v8i16, R, ShiftAmt,
15301 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15302 // Zero out the leftmost bits.
15303 SmallVector<SDValue, 16> V(16,
15304 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15306 return DAG.getNode(ISD::AND, dl, VT, SRL,
15307 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15309 if (Op.getOpcode() == ISD::SRA) {
15310 if (ShiftAmt == 7) {
15311 // R s>> 7 === R s< 0
15312 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15313 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15316 // R s>> a === ((R u>> a) ^ m) - m
15317 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15318 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15320 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15321 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15322 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15325 llvm_unreachable("Unknown shift opcode.");
15328 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15329 if (Op.getOpcode() == ISD::SHL) {
15330 // Make a large shift.
15331 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15332 MVT::v16i16, R, ShiftAmt,
15334 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15335 // Zero out the rightmost bits.
15336 SmallVector<SDValue, 32> V(32,
15337 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15339 return DAG.getNode(ISD::AND, dl, VT, SHL,
15340 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15342 if (Op.getOpcode() == ISD::SRL) {
15343 // Make a large shift.
15344 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15345 MVT::v16i16, R, ShiftAmt,
15347 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15348 // Zero out the leftmost bits.
15349 SmallVector<SDValue, 32> V(32,
15350 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15352 return DAG.getNode(ISD::AND, dl, VT, SRL,
15353 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15355 if (Op.getOpcode() == ISD::SRA) {
15356 if (ShiftAmt == 7) {
15357 // R s>> 7 === R s< 0
15358 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15359 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15362 // R s>> a === ((R u>> a) ^ m) - m
15363 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15364 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15366 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15367 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15368 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15371 llvm_unreachable("Unknown shift opcode.");
15376 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15377 if (!Subtarget->is64Bit() &&
15378 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15379 Amt.getOpcode() == ISD::BITCAST &&
15380 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15381 Amt = Amt.getOperand(0);
15382 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15383 VT.getVectorNumElements();
15384 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15385 uint64_t ShiftAmt = 0;
15386 for (unsigned i = 0; i != Ratio; ++i) {
15387 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15391 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15393 // Check remaining shift amounts.
15394 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15395 uint64_t ShAmt = 0;
15396 for (unsigned j = 0; j != Ratio; ++j) {
15397 ConstantSDNode *C =
15398 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15402 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15404 if (ShAmt != ShiftAmt)
15407 switch (Op.getOpcode()) {
15409 llvm_unreachable("Unknown shift opcode!");
15411 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15414 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15417 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15425 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15426 const X86Subtarget* Subtarget) {
15427 MVT VT = Op.getSimpleValueType();
15429 SDValue R = Op.getOperand(0);
15430 SDValue Amt = Op.getOperand(1);
15432 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15433 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15434 (Subtarget->hasInt256() &&
15435 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15436 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15437 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15439 EVT EltVT = VT.getVectorElementType();
15441 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15442 unsigned NumElts = VT.getVectorNumElements();
15444 for (i = 0; i != NumElts; ++i) {
15445 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15449 for (j = i; j != NumElts; ++j) {
15450 SDValue Arg = Amt.getOperand(j);
15451 if (Arg.getOpcode() == ISD::UNDEF) continue;
15452 if (Arg != Amt.getOperand(i))
15455 if (i != NumElts && j == NumElts)
15456 BaseShAmt = Amt.getOperand(i);
15458 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15459 Amt = Amt.getOperand(0);
15460 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15461 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15462 SDValue InVec = Amt.getOperand(0);
15463 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15464 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15466 for (; i != NumElts; ++i) {
15467 SDValue Arg = InVec.getOperand(i);
15468 if (Arg.getOpcode() == ISD::UNDEF) continue;
15472 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15473 if (ConstantSDNode *C =
15474 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15475 unsigned SplatIdx =
15476 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15477 if (C->getZExtValue() == SplatIdx)
15478 BaseShAmt = InVec.getOperand(1);
15481 if (!BaseShAmt.getNode())
15482 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15483 DAG.getIntPtrConstant(0));
15487 if (BaseShAmt.getNode()) {
15488 if (EltVT.bitsGT(MVT::i32))
15489 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15490 else if (EltVT.bitsLT(MVT::i32))
15491 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15493 switch (Op.getOpcode()) {
15495 llvm_unreachable("Unknown shift opcode!");
15497 switch (VT.SimpleTy) {
15498 default: return SDValue();
15507 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15510 switch (VT.SimpleTy) {
15511 default: return SDValue();
15518 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15521 switch (VT.SimpleTy) {
15522 default: return SDValue();
15531 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15537 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15538 if (!Subtarget->is64Bit() &&
15539 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15540 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15541 Amt.getOpcode() == ISD::BITCAST &&
15542 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15543 Amt = Amt.getOperand(0);
15544 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15545 VT.getVectorNumElements();
15546 std::vector<SDValue> Vals(Ratio);
15547 for (unsigned i = 0; i != Ratio; ++i)
15548 Vals[i] = Amt.getOperand(i);
15549 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15550 for (unsigned j = 0; j != Ratio; ++j)
15551 if (Vals[j] != Amt.getOperand(i + j))
15554 switch (Op.getOpcode()) {
15556 llvm_unreachable("Unknown shift opcode!");
15558 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15560 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15562 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15569 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15570 SelectionDAG &DAG) {
15571 MVT VT = Op.getSimpleValueType();
15573 SDValue R = Op.getOperand(0);
15574 SDValue Amt = Op.getOperand(1);
15577 assert(VT.isVector() && "Custom lowering only for vector shifts!");
15578 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15580 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15584 V = LowerScalarVariableShift(Op, DAG, Subtarget);
15588 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15590 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15591 if (Subtarget->hasInt256()) {
15592 if (Op.getOpcode() == ISD::SRL &&
15593 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15594 VT == MVT::v4i64 || VT == MVT::v8i32))
15596 if (Op.getOpcode() == ISD::SHL &&
15597 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15598 VT == MVT::v4i64 || VT == MVT::v8i32))
15600 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15604 // If possible, lower this packed shift into a vector multiply instead of
15605 // expanding it into a sequence of scalar shifts.
15606 // Do this only if the vector shift count is a constant build_vector.
15607 if (Op.getOpcode() == ISD::SHL &&
15608 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15609 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15610 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15611 SmallVector<SDValue, 8> Elts;
15612 EVT SVT = VT.getScalarType();
15613 unsigned SVTBits = SVT.getSizeInBits();
15614 const APInt &One = APInt(SVTBits, 1);
15615 unsigned NumElems = VT.getVectorNumElements();
15617 for (unsigned i=0; i !=NumElems; ++i) {
15618 SDValue Op = Amt->getOperand(i);
15619 if (Op->getOpcode() == ISD::UNDEF) {
15620 Elts.push_back(Op);
15624 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15625 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15626 uint64_t ShAmt = C.getZExtValue();
15627 if (ShAmt >= SVTBits) {
15628 Elts.push_back(DAG.getUNDEF(SVT));
15631 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15633 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15634 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15637 // Lower SHL with variable shift amount.
15638 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15639 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15641 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15642 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15643 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15644 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15647 // If possible, lower this shift as a sequence of two shifts by
15648 // constant plus a MOVSS/MOVSD instead of scalarizing it.
15650 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15652 // Could be rewritten as:
15653 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15655 // The advantage is that the two shifts from the example would be
15656 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15657 // the vector shift into four scalar shifts plus four pairs of vector
15659 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15660 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15661 unsigned TargetOpcode = X86ISD::MOVSS;
15662 bool CanBeSimplified;
15663 // The splat value for the first packed shift (the 'X' from the example).
15664 SDValue Amt1 = Amt->getOperand(0);
15665 // The splat value for the second packed shift (the 'Y' from the example).
15666 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15667 Amt->getOperand(2);
15669 // See if it is possible to replace this node with a sequence of
15670 // two shifts followed by a MOVSS/MOVSD
15671 if (VT == MVT::v4i32) {
15672 // Check if it is legal to use a MOVSS.
15673 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15674 Amt2 == Amt->getOperand(3);
15675 if (!CanBeSimplified) {
15676 // Otherwise, check if we can still simplify this node using a MOVSD.
15677 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15678 Amt->getOperand(2) == Amt->getOperand(3);
15679 TargetOpcode = X86ISD::MOVSD;
15680 Amt2 = Amt->getOperand(2);
15683 // Do similar checks for the case where the machine value type
15685 CanBeSimplified = Amt1 == Amt->getOperand(1);
15686 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15687 CanBeSimplified = Amt2 == Amt->getOperand(i);
15689 if (!CanBeSimplified) {
15690 TargetOpcode = X86ISD::MOVSD;
15691 CanBeSimplified = true;
15692 Amt2 = Amt->getOperand(4);
15693 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15694 CanBeSimplified = Amt1 == Amt->getOperand(i);
15695 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15696 CanBeSimplified = Amt2 == Amt->getOperand(j);
15700 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15701 isa<ConstantSDNode>(Amt2)) {
15702 // Replace this node with two shifts followed by a MOVSS/MOVSD.
15703 EVT CastVT = MVT::v4i32;
15705 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15706 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15708 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15709 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15710 if (TargetOpcode == X86ISD::MOVSD)
15711 CastVT = MVT::v2i64;
15712 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15713 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15714 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15716 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15720 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15721 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15724 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15725 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15727 // Turn 'a' into a mask suitable for VSELECT
15728 SDValue VSelM = DAG.getConstant(0x80, VT);
15729 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15730 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15732 SDValue CM1 = DAG.getConstant(0x0f, VT);
15733 SDValue CM2 = DAG.getConstant(0x3f, VT);
15735 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15736 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15737 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15738 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15739 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15742 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15743 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15744 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15746 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15747 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15748 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15749 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15750 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15753 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15754 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15755 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15757 // return VSELECT(r, r+r, a);
15758 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15759 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15763 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15764 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15765 // solution better.
15766 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15767 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15769 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15770 R = DAG.getNode(ExtOpc, dl, NewVT, R);
15771 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15772 return DAG.getNode(ISD::TRUNCATE, dl, VT,
15773 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15776 // Decompose 256-bit shifts into smaller 128-bit shifts.
15777 if (VT.is256BitVector()) {
15778 unsigned NumElems = VT.getVectorNumElements();
15779 MVT EltVT = VT.getVectorElementType();
15780 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15782 // Extract the two vectors
15783 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15784 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15786 // Recreate the shift amount vectors
15787 SDValue Amt1, Amt2;
15788 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15789 // Constant shift amount
15790 SmallVector<SDValue, 4> Amt1Csts;
15791 SmallVector<SDValue, 4> Amt2Csts;
15792 for (unsigned i = 0; i != NumElems/2; ++i)
15793 Amt1Csts.push_back(Amt->getOperand(i));
15794 for (unsigned i = NumElems/2; i != NumElems; ++i)
15795 Amt2Csts.push_back(Amt->getOperand(i));
15797 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15798 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15800 // Variable shift amount
15801 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15802 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15805 // Issue new vector shifts for the smaller types
15806 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15807 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15809 // Concatenate the result back
15810 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15816 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15817 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15818 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15819 // looks for this combo and may remove the "setcc" instruction if the "setcc"
15820 // has only one use.
15821 SDNode *N = Op.getNode();
15822 SDValue LHS = N->getOperand(0);
15823 SDValue RHS = N->getOperand(1);
15824 unsigned BaseOp = 0;
15827 switch (Op.getOpcode()) {
15828 default: llvm_unreachable("Unknown ovf instruction!");
15830 // A subtract of one will be selected as a INC. Note that INC doesn't
15831 // set CF, so we can't do this for UADDO.
15832 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15834 BaseOp = X86ISD::INC;
15835 Cond = X86::COND_O;
15838 BaseOp = X86ISD::ADD;
15839 Cond = X86::COND_O;
15842 BaseOp = X86ISD::ADD;
15843 Cond = X86::COND_B;
15846 // A subtract of one will be selected as a DEC. Note that DEC doesn't
15847 // set CF, so we can't do this for USUBO.
15848 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15850 BaseOp = X86ISD::DEC;
15851 Cond = X86::COND_O;
15854 BaseOp = X86ISD::SUB;
15855 Cond = X86::COND_O;
15858 BaseOp = X86ISD::SUB;
15859 Cond = X86::COND_B;
15862 BaseOp = X86ISD::SMUL;
15863 Cond = X86::COND_O;
15865 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15866 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15868 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15871 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15872 DAG.getConstant(X86::COND_O, MVT::i32),
15873 SDValue(Sum.getNode(), 2));
15875 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15879 // Also sets EFLAGS.
15880 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15881 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15884 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15885 DAG.getConstant(Cond, MVT::i32),
15886 SDValue(Sum.getNode(), 1));
15888 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15891 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15892 SelectionDAG &DAG) const {
15894 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15895 MVT VT = Op.getSimpleValueType();
15897 if (!Subtarget->hasSSE2() || !VT.isVector())
15900 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15901 ExtraVT.getScalarType().getSizeInBits();
15903 switch (VT.SimpleTy) {
15904 default: return SDValue();
15907 if (!Subtarget->hasFp256())
15909 if (!Subtarget->hasInt256()) {
15910 // needs to be split
15911 unsigned NumElems = VT.getVectorNumElements();
15913 // Extract the LHS vectors
15914 SDValue LHS = Op.getOperand(0);
15915 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15916 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15918 MVT EltVT = VT.getVectorElementType();
15919 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15921 EVT ExtraEltVT = ExtraVT.getVectorElementType();
15922 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15923 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15925 SDValue Extra = DAG.getValueType(ExtraVT);
15927 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15928 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15930 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15935 SDValue Op0 = Op.getOperand(0);
15936 SDValue Op00 = Op0.getOperand(0);
15938 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15939 if (Op0.getOpcode() == ISD::BITCAST &&
15940 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15941 // (sext (vzext x)) -> (vsext x)
15942 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15943 if (Tmp1.getNode()) {
15944 EVT ExtraEltVT = ExtraVT.getVectorElementType();
15945 // This folding is only valid when the in-reg type is a vector of i8,
15947 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15948 ExtraEltVT == MVT::i32) {
15949 SDValue Tmp1Op0 = Tmp1.getOperand(0);
15950 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15951 "This optimization is invalid without a VZEXT.");
15952 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15958 // If the above didn't work, then just use Shift-Left + Shift-Right.
15959 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15961 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15967 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15968 SelectionDAG &DAG) {
15970 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15971 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15972 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15973 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15975 // The only fence that needs an instruction is a sequentially-consistent
15976 // cross-thread fence.
15977 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15978 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15979 // no-sse2). There isn't any reason to disable it if the target processor
15981 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15982 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15984 SDValue Chain = Op.getOperand(0);
15985 SDValue Zero = DAG.getConstant(0, MVT::i32);
15987 DAG.getRegister(X86::ESP, MVT::i32), // Base
15988 DAG.getTargetConstant(1, MVT::i8), // Scale
15989 DAG.getRegister(0, MVT::i32), // Index
15990 DAG.getTargetConstant(0, MVT::i32), // Disp
15991 DAG.getRegister(0, MVT::i32), // Segment.
15995 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15996 return SDValue(Res, 0);
15999 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16000 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16003 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16004 SelectionDAG &DAG) {
16005 MVT T = Op.getSimpleValueType();
16009 switch(T.SimpleTy) {
16010 default: llvm_unreachable("Invalid value type!");
16011 case MVT::i8: Reg = X86::AL; size = 1; break;
16012 case MVT::i16: Reg = X86::AX; size = 2; break;
16013 case MVT::i32: Reg = X86::EAX; size = 4; break;
16015 assert(Subtarget->is64Bit() && "Node not type legal!");
16016 Reg = X86::RAX; size = 8;
16019 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16020 Op.getOperand(2), SDValue());
16021 SDValue Ops[] = { cpIn.getValue(0),
16024 DAG.getTargetConstant(size, MVT::i8),
16025 cpIn.getValue(1) };
16026 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16027 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16028 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16032 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16033 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16034 MVT::i32, cpOut.getValue(2));
16035 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16036 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16038 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16039 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16040 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16044 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16045 SelectionDAG &DAG) {
16046 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16047 MVT DstVT = Op.getSimpleValueType();
16049 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16050 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16051 if (DstVT != MVT::f64)
16052 // This conversion needs to be expanded.
16055 SDValue InVec = Op->getOperand(0);
16057 unsigned NumElts = SrcVT.getVectorNumElements();
16058 EVT SVT = SrcVT.getVectorElementType();
16060 // Widen the vector in input in the case of MVT::v2i32.
16061 // Example: from MVT::v2i32 to MVT::v4i32.
16062 SmallVector<SDValue, 16> Elts;
16063 for (unsigned i = 0, e = NumElts; i != e; ++i)
16064 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16065 DAG.getIntPtrConstant(i)));
16067 // Explicitly mark the extra elements as Undef.
16068 SDValue Undef = DAG.getUNDEF(SVT);
16069 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16070 Elts.push_back(Undef);
16072 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16073 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16074 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16075 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16076 DAG.getIntPtrConstant(0));
16079 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16080 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16081 assert((DstVT == MVT::i64 ||
16082 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16083 "Unexpected custom BITCAST");
16084 // i64 <=> MMX conversions are Legal.
16085 if (SrcVT==MVT::i64 && DstVT.isVector())
16087 if (DstVT==MVT::i64 && SrcVT.isVector())
16089 // MMX <=> MMX conversions are Legal.
16090 if (SrcVT.isVector() && DstVT.isVector())
16092 // All other conversions need to be expanded.
16096 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16097 SDNode *Node = Op.getNode();
16099 EVT T = Node->getValueType(0);
16100 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16101 DAG.getConstant(0, T), Node->getOperand(2));
16102 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16103 cast<AtomicSDNode>(Node)->getMemoryVT(),
16104 Node->getOperand(0),
16105 Node->getOperand(1), negOp,
16106 cast<AtomicSDNode>(Node)->getMemOperand(),
16107 cast<AtomicSDNode>(Node)->getOrdering(),
16108 cast<AtomicSDNode>(Node)->getSynchScope());
16111 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16112 SDNode *Node = Op.getNode();
16114 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16116 // Convert seq_cst store -> xchg
16117 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16118 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16119 // (The only way to get a 16-byte store is cmpxchg16b)
16120 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16121 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16122 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16123 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16124 cast<AtomicSDNode>(Node)->getMemoryVT(),
16125 Node->getOperand(0),
16126 Node->getOperand(1), Node->getOperand(2),
16127 cast<AtomicSDNode>(Node)->getMemOperand(),
16128 cast<AtomicSDNode>(Node)->getOrdering(),
16129 cast<AtomicSDNode>(Node)->getSynchScope());
16130 return Swap.getValue(1);
16132 // Other atomic stores have a simple pattern.
16136 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16137 EVT VT = Op.getNode()->getSimpleValueType(0);
16139 // Let legalize expand this if it isn't a legal type yet.
16140 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16143 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16146 bool ExtraOp = false;
16147 switch (Op.getOpcode()) {
16148 default: llvm_unreachable("Invalid code");
16149 case ISD::ADDC: Opc = X86ISD::ADD; break;
16150 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16151 case ISD::SUBC: Opc = X86ISD::SUB; break;
16152 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16156 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16158 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16159 Op.getOperand(1), Op.getOperand(2));
16162 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16163 SelectionDAG &DAG) {
16164 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16166 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16167 // which returns the values as { float, float } (in XMM0) or
16168 // { double, double } (which is returned in XMM0, XMM1).
16170 SDValue Arg = Op.getOperand(0);
16171 EVT ArgVT = Arg.getValueType();
16172 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16174 TargetLowering::ArgListTy Args;
16175 TargetLowering::ArgListEntry Entry;
16179 Entry.isSExt = false;
16180 Entry.isZExt = false;
16181 Args.push_back(Entry);
16183 bool isF64 = ArgVT == MVT::f64;
16184 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16185 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16186 // the results are returned via SRet in memory.
16187 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16188 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16189 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16191 Type *RetTy = isF64
16192 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16193 : (Type*)VectorType::get(ArgTy, 4);
16195 TargetLowering::CallLoweringInfo CLI(DAG);
16196 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16197 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16199 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16202 // Returned in xmm0 and xmm1.
16203 return CallResult.first;
16205 // Returned in bits 0:31 and 32:64 xmm0.
16206 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16207 CallResult.first, DAG.getIntPtrConstant(0));
16208 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16209 CallResult.first, DAG.getIntPtrConstant(1));
16210 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16211 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16214 /// LowerOperation - Provide custom lowering hooks for some operations.
16216 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16217 switch (Op.getOpcode()) {
16218 default: llvm_unreachable("Should not custom lower this!");
16219 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
16220 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16221 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16222 return LowerCMP_SWAP(Op, Subtarget, DAG);
16223 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16224 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16225 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16226 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16227 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
16228 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16229 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16230 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16231 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16232 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16233 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16234 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16235 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16236 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16237 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16238 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16239 case ISD::SHL_PARTS:
16240 case ISD::SRA_PARTS:
16241 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16242 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16243 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16244 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16245 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16246 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16247 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16248 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16249 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16250 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16251 case ISD::FABS: return LowerFABS(Op, DAG);
16252 case ISD::FNEG: return LowerFNEG(Op, DAG);
16253 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16254 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16255 case ISD::SETCC: return LowerSETCC(Op, DAG);
16256 case ISD::SELECT: return LowerSELECT(Op, DAG);
16257 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16258 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16259 case ISD::VASTART: return LowerVASTART(Op, DAG);
16260 case ISD::VAARG: return LowerVAARG(Op, DAG);
16261 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16262 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16263 case ISD::INTRINSIC_VOID:
16264 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16265 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16266 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16267 case ISD::FRAME_TO_ARGS_OFFSET:
16268 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16269 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16270 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16271 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16272 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16273 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16274 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16275 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16276 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16277 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16278 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16279 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16280 case ISD::UMUL_LOHI:
16281 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16284 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16290 case ISD::UMULO: return LowerXALUO(Op, DAG);
16291 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16292 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16296 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16297 case ISD::ADD: return LowerADD(Op, DAG);
16298 case ISD::SUB: return LowerSUB(Op, DAG);
16299 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16303 static void ReplaceATOMIC_LOAD(SDNode *Node,
16304 SmallVectorImpl<SDValue> &Results,
16305 SelectionDAG &DAG) {
16307 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16309 // Convert wide load -> cmpxchg8b/cmpxchg16b
16310 // FIXME: On 32-bit, load -> fild or movq would be more efficient
16311 // (The only way to get a 16-byte load is cmpxchg16b)
16312 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16313 SDValue Zero = DAG.getConstant(0, VT);
16314 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16316 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16317 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16318 cast<AtomicSDNode>(Node)->getMemOperand(),
16319 cast<AtomicSDNode>(Node)->getOrdering(),
16320 cast<AtomicSDNode>(Node)->getOrdering(),
16321 cast<AtomicSDNode>(Node)->getSynchScope());
16322 Results.push_back(Swap.getValue(0));
16323 Results.push_back(Swap.getValue(2));
16326 /// ReplaceNodeResults - Replace a node with an illegal result type
16327 /// with a new node built out of custom code.
16328 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16329 SmallVectorImpl<SDValue>&Results,
16330 SelectionDAG &DAG) const {
16332 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16333 switch (N->getOpcode()) {
16335 llvm_unreachable("Do not know how to custom type legalize this operation!");
16336 case ISD::SIGN_EXTEND_INREG:
16341 // We don't want to expand or promote these.
16348 case ISD::UDIVREM: {
16349 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16350 Results.push_back(V);
16353 case ISD::FP_TO_SINT:
16354 case ISD::FP_TO_UINT: {
16355 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16357 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16360 std::pair<SDValue,SDValue> Vals =
16361 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16362 SDValue FIST = Vals.first, StackSlot = Vals.second;
16363 if (FIST.getNode()) {
16364 EVT VT = N->getValueType(0);
16365 // Return a load from the stack slot.
16366 if (StackSlot.getNode())
16367 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16368 MachinePointerInfo(),
16369 false, false, false, 0));
16371 Results.push_back(FIST);
16375 case ISD::UINT_TO_FP: {
16376 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16377 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16378 N->getValueType(0) != MVT::v2f32)
16380 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16382 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16384 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16385 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16386 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16387 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16388 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16389 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16392 case ISD::FP_ROUND: {
16393 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16395 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16396 Results.push_back(V);
16399 case ISD::INTRINSIC_W_CHAIN: {
16400 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16402 default : llvm_unreachable("Do not know how to custom type "
16403 "legalize this intrinsic operation!");
16404 case Intrinsic::x86_rdtsc:
16405 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16407 case Intrinsic::x86_rdtscp:
16408 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16410 case Intrinsic::x86_rdpmc:
16411 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16414 case ISD::READCYCLECOUNTER: {
16415 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16418 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16419 EVT T = N->getValueType(0);
16420 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16421 bool Regs64bit = T == MVT::i128;
16422 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16423 SDValue cpInL, cpInH;
16424 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16425 DAG.getConstant(0, HalfT));
16426 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16427 DAG.getConstant(1, HalfT));
16428 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16429 Regs64bit ? X86::RAX : X86::EAX,
16431 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16432 Regs64bit ? X86::RDX : X86::EDX,
16433 cpInH, cpInL.getValue(1));
16434 SDValue swapInL, swapInH;
16435 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16436 DAG.getConstant(0, HalfT));
16437 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16438 DAG.getConstant(1, HalfT));
16439 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16440 Regs64bit ? X86::RBX : X86::EBX,
16441 swapInL, cpInH.getValue(1));
16442 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16443 Regs64bit ? X86::RCX : X86::ECX,
16444 swapInH, swapInL.getValue(1));
16445 SDValue Ops[] = { swapInH.getValue(0),
16447 swapInH.getValue(1) };
16448 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16449 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16450 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16451 X86ISD::LCMPXCHG8_DAG;
16452 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16453 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16454 Regs64bit ? X86::RAX : X86::EAX,
16455 HalfT, Result.getValue(1));
16456 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16457 Regs64bit ? X86::RDX : X86::EDX,
16458 HalfT, cpOutL.getValue(2));
16459 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16461 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16462 MVT::i32, cpOutH.getValue(2));
16464 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16465 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16466 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16468 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16469 Results.push_back(Success);
16470 Results.push_back(EFLAGS.getValue(1));
16473 case ISD::ATOMIC_SWAP:
16474 case ISD::ATOMIC_LOAD_ADD:
16475 case ISD::ATOMIC_LOAD_SUB:
16476 case ISD::ATOMIC_LOAD_AND:
16477 case ISD::ATOMIC_LOAD_OR:
16478 case ISD::ATOMIC_LOAD_XOR:
16479 case ISD::ATOMIC_LOAD_NAND:
16480 case ISD::ATOMIC_LOAD_MIN:
16481 case ISD::ATOMIC_LOAD_MAX:
16482 case ISD::ATOMIC_LOAD_UMIN:
16483 case ISD::ATOMIC_LOAD_UMAX:
16484 // Delegate to generic TypeLegalization. Situations we can really handle
16485 // should have already been dealt with by X86AtomicExpand.cpp.
16487 case ISD::ATOMIC_LOAD: {
16488 ReplaceATOMIC_LOAD(N, Results, DAG);
16491 case ISD::BITCAST: {
16492 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16493 EVT DstVT = N->getValueType(0);
16494 EVT SrcVT = N->getOperand(0)->getValueType(0);
16496 if (SrcVT != MVT::f64 ||
16497 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16500 unsigned NumElts = DstVT.getVectorNumElements();
16501 EVT SVT = DstVT.getVectorElementType();
16502 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16503 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16504 MVT::v2f64, N->getOperand(0));
16505 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16507 if (ExperimentalVectorWideningLegalization) {
16508 // If we are legalizing vectors by widening, we already have the desired
16509 // legal vector type, just return it.
16510 Results.push_back(ToVecInt);
16514 SmallVector<SDValue, 8> Elts;
16515 for (unsigned i = 0, e = NumElts; i != e; ++i)
16516 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16517 ToVecInt, DAG.getIntPtrConstant(i)));
16519 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16524 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16526 default: return nullptr;
16527 case X86ISD::BSF: return "X86ISD::BSF";
16528 case X86ISD::BSR: return "X86ISD::BSR";
16529 case X86ISD::SHLD: return "X86ISD::SHLD";
16530 case X86ISD::SHRD: return "X86ISD::SHRD";
16531 case X86ISD::FAND: return "X86ISD::FAND";
16532 case X86ISD::FANDN: return "X86ISD::FANDN";
16533 case X86ISD::FOR: return "X86ISD::FOR";
16534 case X86ISD::FXOR: return "X86ISD::FXOR";
16535 case X86ISD::FSRL: return "X86ISD::FSRL";
16536 case X86ISD::FILD: return "X86ISD::FILD";
16537 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
16538 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16539 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16540 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16541 case X86ISD::FLD: return "X86ISD::FLD";
16542 case X86ISD::FST: return "X86ISD::FST";
16543 case X86ISD::CALL: return "X86ISD::CALL";
16544 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
16545 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
16546 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
16547 case X86ISD::BT: return "X86ISD::BT";
16548 case X86ISD::CMP: return "X86ISD::CMP";
16549 case X86ISD::COMI: return "X86ISD::COMI";
16550 case X86ISD::UCOMI: return "X86ISD::UCOMI";
16551 case X86ISD::CMPM: return "X86ISD::CMPM";
16552 case X86ISD::CMPMU: return "X86ISD::CMPMU";
16553 case X86ISD::SETCC: return "X86ISD::SETCC";
16554 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
16555 case X86ISD::FSETCC: return "X86ISD::FSETCC";
16556 case X86ISD::CMOV: return "X86ISD::CMOV";
16557 case X86ISD::BRCOND: return "X86ISD::BRCOND";
16558 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
16559 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
16560 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
16561 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
16562 case X86ISD::Wrapper: return "X86ISD::Wrapper";
16563 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
16564 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
16565 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
16566 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
16567 case X86ISD::PINSRB: return "X86ISD::PINSRB";
16568 case X86ISD::PINSRW: return "X86ISD::PINSRW";
16569 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
16570 case X86ISD::ANDNP: return "X86ISD::ANDNP";
16571 case X86ISD::PSIGN: return "X86ISD::PSIGN";
16572 case X86ISD::BLENDV: return "X86ISD::BLENDV";
16573 case X86ISD::BLENDI: return "X86ISD::BLENDI";
16574 case X86ISD::SUBUS: return "X86ISD::SUBUS";
16575 case X86ISD::HADD: return "X86ISD::HADD";
16576 case X86ISD::HSUB: return "X86ISD::HSUB";
16577 case X86ISD::FHADD: return "X86ISD::FHADD";
16578 case X86ISD::FHSUB: return "X86ISD::FHSUB";
16579 case X86ISD::UMAX: return "X86ISD::UMAX";
16580 case X86ISD::UMIN: return "X86ISD::UMIN";
16581 case X86ISD::SMAX: return "X86ISD::SMAX";
16582 case X86ISD::SMIN: return "X86ISD::SMIN";
16583 case X86ISD::FMAX: return "X86ISD::FMAX";
16584 case X86ISD::FMIN: return "X86ISD::FMIN";
16585 case X86ISD::FMAXC: return "X86ISD::FMAXC";
16586 case X86ISD::FMINC: return "X86ISD::FMINC";
16587 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
16588 case X86ISD::FRCP: return "X86ISD::FRCP";
16589 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
16590 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
16591 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
16592 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
16593 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
16594 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
16595 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
16596 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
16597 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
16598 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
16599 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
16600 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
16601 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
16602 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
16603 case X86ISD::VZEXT: return "X86ISD::VZEXT";
16604 case X86ISD::VSEXT: return "X86ISD::VSEXT";
16605 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
16606 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
16607 case X86ISD::VINSERT: return "X86ISD::VINSERT";
16608 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
16609 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
16610 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
16611 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
16612 case X86ISD::VSHL: return "X86ISD::VSHL";
16613 case X86ISD::VSRL: return "X86ISD::VSRL";
16614 case X86ISD::VSRA: return "X86ISD::VSRA";
16615 case X86ISD::VSHLI: return "X86ISD::VSHLI";
16616 case X86ISD::VSRLI: return "X86ISD::VSRLI";
16617 case X86ISD::VSRAI: return "X86ISD::VSRAI";
16618 case X86ISD::CMPP: return "X86ISD::CMPP";
16619 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
16620 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
16621 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
16622 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
16623 case X86ISD::ADD: return "X86ISD::ADD";
16624 case X86ISD::SUB: return "X86ISD::SUB";
16625 case X86ISD::ADC: return "X86ISD::ADC";
16626 case X86ISD::SBB: return "X86ISD::SBB";
16627 case X86ISD::SMUL: return "X86ISD::SMUL";
16628 case X86ISD::UMUL: return "X86ISD::UMUL";
16629 case X86ISD::INC: return "X86ISD::INC";
16630 case X86ISD::DEC: return "X86ISD::DEC";
16631 case X86ISD::OR: return "X86ISD::OR";
16632 case X86ISD::XOR: return "X86ISD::XOR";
16633 case X86ISD::AND: return "X86ISD::AND";
16634 case X86ISD::BEXTR: return "X86ISD::BEXTR";
16635 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
16636 case X86ISD::PTEST: return "X86ISD::PTEST";
16637 case X86ISD::TESTP: return "X86ISD::TESTP";
16638 case X86ISD::TESTM: return "X86ISD::TESTM";
16639 case X86ISD::TESTNM: return "X86ISD::TESTNM";
16640 case X86ISD::KORTEST: return "X86ISD::KORTEST";
16641 case X86ISD::PACKSS: return "X86ISD::PACKSS";
16642 case X86ISD::PACKUS: return "X86ISD::PACKUS";
16643 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
16644 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
16645 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
16646 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
16647 case X86ISD::SHUFP: return "X86ISD::SHUFP";
16648 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
16649 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
16650 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
16651 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
16652 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
16653 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
16654 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
16655 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
16656 case X86ISD::MOVSD: return "X86ISD::MOVSD";
16657 case X86ISD::MOVSS: return "X86ISD::MOVSS";
16658 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
16659 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
16660 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
16661 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
16662 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
16663 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
16664 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
16665 case X86ISD::VPERMV: return "X86ISD::VPERMV";
16666 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
16667 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
16668 case X86ISD::VPERMI: return "X86ISD::VPERMI";
16669 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
16670 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
16671 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16672 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
16673 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
16674 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
16675 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
16676 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
16677 case X86ISD::SAHF: return "X86ISD::SAHF";
16678 case X86ISD::RDRAND: return "X86ISD::RDRAND";
16679 case X86ISD::RDSEED: return "X86ISD::RDSEED";
16680 case X86ISD::FMADD: return "X86ISD::FMADD";
16681 case X86ISD::FMSUB: return "X86ISD::FMSUB";
16682 case X86ISD::FNMADD: return "X86ISD::FNMADD";
16683 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
16684 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
16685 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
16686 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
16687 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
16688 case X86ISD::XTEST: return "X86ISD::XTEST";
16692 // isLegalAddressingMode - Return true if the addressing mode represented
16693 // by AM is legal for this target, for a load/store of the specified type.
16694 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16696 // X86 supports extremely general addressing modes.
16697 CodeModel::Model M = getTargetMachine().getCodeModel();
16698 Reloc::Model R = getTargetMachine().getRelocationModel();
16700 // X86 allows a sign-extended 32-bit immediate field as a displacement.
16701 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16706 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16708 // If a reference to this global requires an extra load, we can't fold it.
16709 if (isGlobalStubReference(GVFlags))
16712 // If BaseGV requires a register for the PIC base, we cannot also have a
16713 // BaseReg specified.
16714 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16717 // If lower 4G is not available, then we must use rip-relative addressing.
16718 if ((M != CodeModel::Small || R != Reloc::Static) &&
16719 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16723 switch (AM.Scale) {
16729 // These scales always work.
16734 // These scales are formed with basereg+scalereg. Only accept if there is
16739 default: // Other stuff never works.
16746 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16747 unsigned Bits = Ty->getScalarSizeInBits();
16749 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16750 // particularly cheaper than those without.
16754 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16755 // variable shifts just as cheap as scalar ones.
16756 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16759 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16760 // fully general vector.
16764 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16765 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16767 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16768 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16769 return NumBits1 > NumBits2;
16772 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16773 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16776 if (!isTypeLegal(EVT::getEVT(Ty1)))
16779 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16781 // Assuming the caller doesn't have a zeroext or signext return parameter,
16782 // truncation all the way down to i1 is valid.
16786 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16787 return isInt<32>(Imm);
16790 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16791 // Can also use sub to handle negated immediates.
16792 return isInt<32>(Imm);
16795 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16796 if (!VT1.isInteger() || !VT2.isInteger())
16798 unsigned NumBits1 = VT1.getSizeInBits();
16799 unsigned NumBits2 = VT2.getSizeInBits();
16800 return NumBits1 > NumBits2;
16803 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16804 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16805 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16808 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16809 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16810 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16813 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16814 EVT VT1 = Val.getValueType();
16815 if (isZExtFree(VT1, VT2))
16818 if (Val.getOpcode() != ISD::LOAD)
16821 if (!VT1.isSimple() || !VT1.isInteger() ||
16822 !VT2.isSimple() || !VT2.isInteger())
16825 switch (VT1.getSimpleVT().SimpleTy) {
16830 // X86 has 8, 16, and 32-bit zero-extending loads.
16838 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16839 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16842 VT = VT.getScalarType();
16844 if (!VT.isSimple())
16847 switch (VT.getSimpleVT().SimpleTy) {
16858 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16859 // i16 instructions are longer (0x66 prefix) and potentially slower.
16860 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16863 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16864 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16865 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16866 /// are assumed to be legal.
16868 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16870 if (!VT.isSimple())
16873 MVT SVT = VT.getSimpleVT();
16875 // Very little shuffling can be done for 64-bit vectors right now.
16876 if (VT.getSizeInBits() == 64)
16879 // If this is a single-input shuffle with no 128 bit lane crossings we can
16880 // lower it into pshufb.
16881 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16882 (SVT.is256BitVector() && Subtarget->hasInt256())) {
16883 bool isLegal = true;
16884 for (unsigned I = 0, E = M.size(); I != E; ++I) {
16885 if (M[I] >= (int)SVT.getVectorNumElements() ||
16886 ShuffleCrosses128bitLane(SVT, I, M[I])) {
16895 // FIXME: blends, shifts.
16896 return (SVT.getVectorNumElements() == 2 ||
16897 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16898 isMOVLMask(M, SVT) ||
16899 isMOVHLPSMask(M, SVT) ||
16900 isSHUFPMask(M, SVT) ||
16901 isPSHUFDMask(M, SVT) ||
16902 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16903 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16904 isPALIGNRMask(M, SVT, Subtarget) ||
16905 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16906 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16907 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16908 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16909 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16913 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16915 if (!VT.isSimple())
16918 MVT SVT = VT.getSimpleVT();
16919 unsigned NumElts = SVT.getVectorNumElements();
16920 // FIXME: This collection of masks seems suspect.
16923 if (NumElts == 4 && SVT.is128BitVector()) {
16924 return (isMOVLMask(Mask, SVT) ||
16925 isCommutedMOVLMask(Mask, SVT, true) ||
16926 isSHUFPMask(Mask, SVT) ||
16927 isSHUFPMask(Mask, SVT, /* Commuted */ true));
16932 //===----------------------------------------------------------------------===//
16933 // X86 Scheduler Hooks
16934 //===----------------------------------------------------------------------===//
16936 /// Utility function to emit xbegin specifying the start of an RTM region.
16937 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16938 const TargetInstrInfo *TII) {
16939 DebugLoc DL = MI->getDebugLoc();
16941 const BasicBlock *BB = MBB->getBasicBlock();
16942 MachineFunction::iterator I = MBB;
16945 // For the v = xbegin(), we generate
16956 MachineBasicBlock *thisMBB = MBB;
16957 MachineFunction *MF = MBB->getParent();
16958 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16959 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16960 MF->insert(I, mainMBB);
16961 MF->insert(I, sinkMBB);
16963 // Transfer the remainder of BB and its successor edges to sinkMBB.
16964 sinkMBB->splice(sinkMBB->begin(), MBB,
16965 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16966 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16970 // # fallthrough to mainMBB
16971 // # abortion to sinkMBB
16972 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16973 thisMBB->addSuccessor(mainMBB);
16974 thisMBB->addSuccessor(sinkMBB);
16978 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16979 mainMBB->addSuccessor(sinkMBB);
16982 // EAX is live into the sinkMBB
16983 sinkMBB->addLiveIn(X86::EAX);
16984 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16985 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16988 MI->eraseFromParent();
16992 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16993 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16994 // in the .td file.
16995 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16996 const TargetInstrInfo *TII) {
16998 switch (MI->getOpcode()) {
16999 default: llvm_unreachable("illegal opcode!");
17000 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17001 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17002 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17003 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17004 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17005 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17006 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17007 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17010 DebugLoc dl = MI->getDebugLoc();
17011 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17013 unsigned NumArgs = MI->getNumOperands();
17014 for (unsigned i = 1; i < NumArgs; ++i) {
17015 MachineOperand &Op = MI->getOperand(i);
17016 if (!(Op.isReg() && Op.isImplicit()))
17017 MIB.addOperand(Op);
17019 if (MI->hasOneMemOperand())
17020 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17022 BuildMI(*BB, MI, dl,
17023 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17024 .addReg(X86::XMM0);
17026 MI->eraseFromParent();
17030 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17031 // defs in an instruction pattern
17032 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17033 const TargetInstrInfo *TII) {
17035 switch (MI->getOpcode()) {
17036 default: llvm_unreachable("illegal opcode!");
17037 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17038 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17039 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17040 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17041 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17042 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17043 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17044 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17047 DebugLoc dl = MI->getDebugLoc();
17048 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17050 unsigned NumArgs = MI->getNumOperands(); // remove the results
17051 for (unsigned i = 1; i < NumArgs; ++i) {
17052 MachineOperand &Op = MI->getOperand(i);
17053 if (!(Op.isReg() && Op.isImplicit()))
17054 MIB.addOperand(Op);
17056 if (MI->hasOneMemOperand())
17057 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17059 BuildMI(*BB, MI, dl,
17060 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17063 MI->eraseFromParent();
17067 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17068 const TargetInstrInfo *TII,
17069 const X86Subtarget* Subtarget) {
17070 DebugLoc dl = MI->getDebugLoc();
17072 // Address into RAX/EAX, other two args into ECX, EDX.
17073 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17074 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17075 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17076 for (int i = 0; i < X86::AddrNumOperands; ++i)
17077 MIB.addOperand(MI->getOperand(i));
17079 unsigned ValOps = X86::AddrNumOperands;
17080 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17081 .addReg(MI->getOperand(ValOps).getReg());
17082 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17083 .addReg(MI->getOperand(ValOps+1).getReg());
17085 // The instruction doesn't actually take any operands though.
17086 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17088 MI->eraseFromParent(); // The pseudo is gone now.
17092 MachineBasicBlock *
17093 X86TargetLowering::EmitVAARG64WithCustomInserter(
17095 MachineBasicBlock *MBB) const {
17096 // Emit va_arg instruction on X86-64.
17098 // Operands to this pseudo-instruction:
17099 // 0 ) Output : destination address (reg)
17100 // 1-5) Input : va_list address (addr, i64mem)
17101 // 6 ) ArgSize : Size (in bytes) of vararg type
17102 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17103 // 8 ) Align : Alignment of type
17104 // 9 ) EFLAGS (implicit-def)
17106 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17107 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17109 unsigned DestReg = MI->getOperand(0).getReg();
17110 MachineOperand &Base = MI->getOperand(1);
17111 MachineOperand &Scale = MI->getOperand(2);
17112 MachineOperand &Index = MI->getOperand(3);
17113 MachineOperand &Disp = MI->getOperand(4);
17114 MachineOperand &Segment = MI->getOperand(5);
17115 unsigned ArgSize = MI->getOperand(6).getImm();
17116 unsigned ArgMode = MI->getOperand(7).getImm();
17117 unsigned Align = MI->getOperand(8).getImm();
17119 // Memory Reference
17120 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17121 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17122 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17124 // Machine Information
17125 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17126 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17127 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17128 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17129 DebugLoc DL = MI->getDebugLoc();
17131 // struct va_list {
17134 // i64 overflow_area (address)
17135 // i64 reg_save_area (address)
17137 // sizeof(va_list) = 24
17138 // alignment(va_list) = 8
17140 unsigned TotalNumIntRegs = 6;
17141 unsigned TotalNumXMMRegs = 8;
17142 bool UseGPOffset = (ArgMode == 1);
17143 bool UseFPOffset = (ArgMode == 2);
17144 unsigned MaxOffset = TotalNumIntRegs * 8 +
17145 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17147 /* Align ArgSize to a multiple of 8 */
17148 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17149 bool NeedsAlign = (Align > 8);
17151 MachineBasicBlock *thisMBB = MBB;
17152 MachineBasicBlock *overflowMBB;
17153 MachineBasicBlock *offsetMBB;
17154 MachineBasicBlock *endMBB;
17156 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17157 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17158 unsigned OffsetReg = 0;
17160 if (!UseGPOffset && !UseFPOffset) {
17161 // If we only pull from the overflow region, we don't create a branch.
17162 // We don't need to alter control flow.
17163 OffsetDestReg = 0; // unused
17164 OverflowDestReg = DestReg;
17166 offsetMBB = nullptr;
17167 overflowMBB = thisMBB;
17170 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17171 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17172 // If not, pull from overflow_area. (branch to overflowMBB)
17177 // offsetMBB overflowMBB
17182 // Registers for the PHI in endMBB
17183 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17184 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17186 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17187 MachineFunction *MF = MBB->getParent();
17188 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17189 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17190 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17192 MachineFunction::iterator MBBIter = MBB;
17195 // Insert the new basic blocks
17196 MF->insert(MBBIter, offsetMBB);
17197 MF->insert(MBBIter, overflowMBB);
17198 MF->insert(MBBIter, endMBB);
17200 // Transfer the remainder of MBB and its successor edges to endMBB.
17201 endMBB->splice(endMBB->begin(), thisMBB,
17202 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17203 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17205 // Make offsetMBB and overflowMBB successors of thisMBB
17206 thisMBB->addSuccessor(offsetMBB);
17207 thisMBB->addSuccessor(overflowMBB);
17209 // endMBB is a successor of both offsetMBB and overflowMBB
17210 offsetMBB->addSuccessor(endMBB);
17211 overflowMBB->addSuccessor(endMBB);
17213 // Load the offset value into a register
17214 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17215 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17219 .addDisp(Disp, UseFPOffset ? 4 : 0)
17220 .addOperand(Segment)
17221 .setMemRefs(MMOBegin, MMOEnd);
17223 // Check if there is enough room left to pull this argument.
17224 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17226 .addImm(MaxOffset + 8 - ArgSizeA8);
17228 // Branch to "overflowMBB" if offset >= max
17229 // Fall through to "offsetMBB" otherwise
17230 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17231 .addMBB(overflowMBB);
17234 // In offsetMBB, emit code to use the reg_save_area.
17236 assert(OffsetReg != 0);
17238 // Read the reg_save_area address.
17239 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17240 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17245 .addOperand(Segment)
17246 .setMemRefs(MMOBegin, MMOEnd);
17248 // Zero-extend the offset
17249 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17250 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17253 .addImm(X86::sub_32bit);
17255 // Add the offset to the reg_save_area to get the final address.
17256 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17257 .addReg(OffsetReg64)
17258 .addReg(RegSaveReg);
17260 // Compute the offset for the next argument
17261 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17262 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17264 .addImm(UseFPOffset ? 16 : 8);
17266 // Store it back into the va_list.
17267 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17271 .addDisp(Disp, UseFPOffset ? 4 : 0)
17272 .addOperand(Segment)
17273 .addReg(NextOffsetReg)
17274 .setMemRefs(MMOBegin, MMOEnd);
17277 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17282 // Emit code to use overflow area
17285 // Load the overflow_area address into a register.
17286 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17287 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17292 .addOperand(Segment)
17293 .setMemRefs(MMOBegin, MMOEnd);
17295 // If we need to align it, do so. Otherwise, just copy the address
17296 // to OverflowDestReg.
17298 // Align the overflow address
17299 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17300 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17302 // aligned_addr = (addr + (align-1)) & ~(align-1)
17303 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17304 .addReg(OverflowAddrReg)
17307 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17309 .addImm(~(uint64_t)(Align-1));
17311 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17312 .addReg(OverflowAddrReg);
17315 // Compute the next overflow address after this argument.
17316 // (the overflow address should be kept 8-byte aligned)
17317 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17318 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17319 .addReg(OverflowDestReg)
17320 .addImm(ArgSizeA8);
17322 // Store the new overflow address.
17323 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17328 .addOperand(Segment)
17329 .addReg(NextAddrReg)
17330 .setMemRefs(MMOBegin, MMOEnd);
17332 // If we branched, emit the PHI to the front of endMBB.
17334 BuildMI(*endMBB, endMBB->begin(), DL,
17335 TII->get(X86::PHI), DestReg)
17336 .addReg(OffsetDestReg).addMBB(offsetMBB)
17337 .addReg(OverflowDestReg).addMBB(overflowMBB);
17340 // Erase the pseudo instruction
17341 MI->eraseFromParent();
17346 MachineBasicBlock *
17347 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17349 MachineBasicBlock *MBB) const {
17350 // Emit code to save XMM registers to the stack. The ABI says that the
17351 // number of registers to save is given in %al, so it's theoretically
17352 // possible to do an indirect jump trick to avoid saving all of them,
17353 // however this code takes a simpler approach and just executes all
17354 // of the stores if %al is non-zero. It's less code, and it's probably
17355 // easier on the hardware branch predictor, and stores aren't all that
17356 // expensive anyway.
17358 // Create the new basic blocks. One block contains all the XMM stores,
17359 // and one block is the final destination regardless of whether any
17360 // stores were performed.
17361 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17362 MachineFunction *F = MBB->getParent();
17363 MachineFunction::iterator MBBIter = MBB;
17365 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17366 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17367 F->insert(MBBIter, XMMSaveMBB);
17368 F->insert(MBBIter, EndMBB);
17370 // Transfer the remainder of MBB and its successor edges to EndMBB.
17371 EndMBB->splice(EndMBB->begin(), MBB,
17372 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17373 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17375 // The original block will now fall through to the XMM save block.
17376 MBB->addSuccessor(XMMSaveMBB);
17377 // The XMMSaveMBB will fall through to the end block.
17378 XMMSaveMBB->addSuccessor(EndMBB);
17380 // Now add the instructions.
17381 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17382 DebugLoc DL = MI->getDebugLoc();
17384 unsigned CountReg = MI->getOperand(0).getReg();
17385 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17386 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17388 if (!Subtarget->isTargetWin64()) {
17389 // If %al is 0, branch around the XMM save block.
17390 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17391 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17392 MBB->addSuccessor(EndMBB);
17395 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17396 // that was just emitted, but clearly shouldn't be "saved".
17397 assert((MI->getNumOperands() <= 3 ||
17398 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17399 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17400 && "Expected last argument to be EFLAGS");
17401 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17402 // In the XMM save block, save all the XMM argument registers.
17403 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17404 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17405 MachineMemOperand *MMO =
17406 F->getMachineMemOperand(
17407 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17408 MachineMemOperand::MOStore,
17409 /*Size=*/16, /*Align=*/16);
17410 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17411 .addFrameIndex(RegSaveFrameIndex)
17412 .addImm(/*Scale=*/1)
17413 .addReg(/*IndexReg=*/0)
17414 .addImm(/*Disp=*/Offset)
17415 .addReg(/*Segment=*/0)
17416 .addReg(MI->getOperand(i).getReg())
17417 .addMemOperand(MMO);
17420 MI->eraseFromParent(); // The pseudo instruction is gone now.
17425 // The EFLAGS operand of SelectItr might be missing a kill marker
17426 // because there were multiple uses of EFLAGS, and ISel didn't know
17427 // which to mark. Figure out whether SelectItr should have had a
17428 // kill marker, and set it if it should. Returns the correct kill
17430 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17431 MachineBasicBlock* BB,
17432 const TargetRegisterInfo* TRI) {
17433 // Scan forward through BB for a use/def of EFLAGS.
17434 MachineBasicBlock::iterator miI(std::next(SelectItr));
17435 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17436 const MachineInstr& mi = *miI;
17437 if (mi.readsRegister(X86::EFLAGS))
17439 if (mi.definesRegister(X86::EFLAGS))
17440 break; // Should have kill-flag - update below.
17443 // If we hit the end of the block, check whether EFLAGS is live into a
17445 if (miI == BB->end()) {
17446 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17447 sEnd = BB->succ_end();
17448 sItr != sEnd; ++sItr) {
17449 MachineBasicBlock* succ = *sItr;
17450 if (succ->isLiveIn(X86::EFLAGS))
17455 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17456 // out. SelectMI should have a kill flag on EFLAGS.
17457 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17461 MachineBasicBlock *
17462 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17463 MachineBasicBlock *BB) const {
17464 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17465 DebugLoc DL = MI->getDebugLoc();
17467 // To "insert" a SELECT_CC instruction, we actually have to insert the
17468 // diamond control-flow pattern. The incoming instruction knows the
17469 // destination vreg to set, the condition code register to branch on, the
17470 // true/false values to select between, and a branch opcode to use.
17471 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17472 MachineFunction::iterator It = BB;
17478 // cmpTY ccX, r1, r2
17480 // fallthrough --> copy0MBB
17481 MachineBasicBlock *thisMBB = BB;
17482 MachineFunction *F = BB->getParent();
17483 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17484 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17485 F->insert(It, copy0MBB);
17486 F->insert(It, sinkMBB);
17488 // If the EFLAGS register isn't dead in the terminator, then claim that it's
17489 // live into the sink and copy blocks.
17490 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17491 if (!MI->killsRegister(X86::EFLAGS) &&
17492 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17493 copy0MBB->addLiveIn(X86::EFLAGS);
17494 sinkMBB->addLiveIn(X86::EFLAGS);
17497 // Transfer the remainder of BB and its successor edges to sinkMBB.
17498 sinkMBB->splice(sinkMBB->begin(), BB,
17499 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17500 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17502 // Add the true and fallthrough blocks as its successors.
17503 BB->addSuccessor(copy0MBB);
17504 BB->addSuccessor(sinkMBB);
17506 // Create the conditional branch instruction.
17508 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17509 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17512 // %FalseValue = ...
17513 // # fallthrough to sinkMBB
17514 copy0MBB->addSuccessor(sinkMBB);
17517 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17519 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17520 TII->get(X86::PHI), MI->getOperand(0).getReg())
17521 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17522 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17524 MI->eraseFromParent(); // The pseudo instruction is gone now.
17528 MachineBasicBlock *
17529 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17530 bool Is64Bit) const {
17531 MachineFunction *MF = BB->getParent();
17532 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17533 DebugLoc DL = MI->getDebugLoc();
17534 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17536 assert(MF->shouldSplitStack());
17538 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17539 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17542 // ... [Till the alloca]
17543 // If stacklet is not large enough, jump to mallocMBB
17546 // Allocate by subtracting from RSP
17547 // Jump to continueMBB
17550 // Allocate by call to runtime
17554 // [rest of original BB]
17557 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17558 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17559 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17561 MachineRegisterInfo &MRI = MF->getRegInfo();
17562 const TargetRegisterClass *AddrRegClass =
17563 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17565 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17566 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17567 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17568 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17569 sizeVReg = MI->getOperand(1).getReg(),
17570 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17572 MachineFunction::iterator MBBIter = BB;
17575 MF->insert(MBBIter, bumpMBB);
17576 MF->insert(MBBIter, mallocMBB);
17577 MF->insert(MBBIter, continueMBB);
17579 continueMBB->splice(continueMBB->begin(), BB,
17580 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17581 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17583 // Add code to the main basic block to check if the stack limit has been hit,
17584 // and if so, jump to mallocMBB otherwise to bumpMBB.
17585 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17586 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17587 .addReg(tmpSPVReg).addReg(sizeVReg);
17588 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17589 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17590 .addReg(SPLimitVReg);
17591 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17593 // bumpMBB simply decreases the stack pointer, since we know the current
17594 // stacklet has enough space.
17595 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17596 .addReg(SPLimitVReg);
17597 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17598 .addReg(SPLimitVReg);
17599 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17601 // Calls into a routine in libgcc to allocate more space from the heap.
17602 const uint32_t *RegMask =
17603 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17605 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17607 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17608 .addExternalSymbol("__morestack_allocate_stack_space")
17609 .addRegMask(RegMask)
17610 .addReg(X86::RDI, RegState::Implicit)
17611 .addReg(X86::RAX, RegState::ImplicitDefine);
17613 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17615 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17616 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17617 .addExternalSymbol("__morestack_allocate_stack_space")
17618 .addRegMask(RegMask)
17619 .addReg(X86::EAX, RegState::ImplicitDefine);
17623 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17626 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17627 .addReg(Is64Bit ? X86::RAX : X86::EAX);
17628 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17630 // Set up the CFG correctly.
17631 BB->addSuccessor(bumpMBB);
17632 BB->addSuccessor(mallocMBB);
17633 mallocMBB->addSuccessor(continueMBB);
17634 bumpMBB->addSuccessor(continueMBB);
17636 // Take care of the PHI nodes.
17637 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17638 MI->getOperand(0).getReg())
17639 .addReg(mallocPtrVReg).addMBB(mallocMBB)
17640 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17642 // Delete the original pseudo instruction.
17643 MI->eraseFromParent();
17646 return continueMBB;
17649 MachineBasicBlock *
17650 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17651 MachineBasicBlock *BB) const {
17652 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17653 DebugLoc DL = MI->getDebugLoc();
17655 assert(!Subtarget->isTargetMacho());
17657 // The lowering is pretty easy: we're just emitting the call to _alloca. The
17658 // non-trivial part is impdef of ESP.
17660 if (Subtarget->isTargetWin64()) {
17661 if (Subtarget->isTargetCygMing()) {
17662 // ___chkstk(Mingw64):
17663 // Clobbers R10, R11, RAX and EFLAGS.
17665 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17666 .addExternalSymbol("___chkstk")
17667 .addReg(X86::RAX, RegState::Implicit)
17668 .addReg(X86::RSP, RegState::Implicit)
17669 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17670 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17671 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17673 // __chkstk(MSVCRT): does not update stack pointer.
17674 // Clobbers R10, R11 and EFLAGS.
17675 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17676 .addExternalSymbol("__chkstk")
17677 .addReg(X86::RAX, RegState::Implicit)
17678 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17679 // RAX has the offset to be subtracted from RSP.
17680 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17685 const char *StackProbeSymbol =
17686 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17688 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17689 .addExternalSymbol(StackProbeSymbol)
17690 .addReg(X86::EAX, RegState::Implicit)
17691 .addReg(X86::ESP, RegState::Implicit)
17692 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17693 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17694 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17697 MI->eraseFromParent(); // The pseudo instruction is gone now.
17701 MachineBasicBlock *
17702 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17703 MachineBasicBlock *BB) const {
17704 // This is pretty easy. We're taking the value that we received from
17705 // our load from the relocation, sticking it in either RDI (x86-64)
17706 // or EAX and doing an indirect call. The return value will then
17707 // be in the normal return register.
17708 MachineFunction *F = BB->getParent();
17709 const X86InstrInfo *TII
17710 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17711 DebugLoc DL = MI->getDebugLoc();
17713 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17714 assert(MI->getOperand(3).isGlobal() && "This should be a global");
17716 // Get a register mask for the lowered call.
17717 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17718 // proper register mask.
17719 const uint32_t *RegMask =
17720 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17721 if (Subtarget->is64Bit()) {
17722 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17723 TII->get(X86::MOV64rm), X86::RDI)
17725 .addImm(0).addReg(0)
17726 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17727 MI->getOperand(3).getTargetFlags())
17729 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17730 addDirectMem(MIB, X86::RDI);
17731 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17732 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17733 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17734 TII->get(X86::MOV32rm), X86::EAX)
17736 .addImm(0).addReg(0)
17737 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17738 MI->getOperand(3).getTargetFlags())
17740 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17741 addDirectMem(MIB, X86::EAX);
17742 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17744 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17745 TII->get(X86::MOV32rm), X86::EAX)
17746 .addReg(TII->getGlobalBaseReg(F))
17747 .addImm(0).addReg(0)
17748 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17749 MI->getOperand(3).getTargetFlags())
17751 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17752 addDirectMem(MIB, X86::EAX);
17753 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17756 MI->eraseFromParent(); // The pseudo instruction is gone now.
17760 MachineBasicBlock *
17761 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17762 MachineBasicBlock *MBB) const {
17763 DebugLoc DL = MI->getDebugLoc();
17764 MachineFunction *MF = MBB->getParent();
17765 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17766 MachineRegisterInfo &MRI = MF->getRegInfo();
17768 const BasicBlock *BB = MBB->getBasicBlock();
17769 MachineFunction::iterator I = MBB;
17772 // Memory Reference
17773 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17774 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17777 unsigned MemOpndSlot = 0;
17779 unsigned CurOp = 0;
17781 DstReg = MI->getOperand(CurOp++).getReg();
17782 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17783 assert(RC->hasType(MVT::i32) && "Invalid destination!");
17784 unsigned mainDstReg = MRI.createVirtualRegister(RC);
17785 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17787 MemOpndSlot = CurOp;
17789 MVT PVT = getPointerTy();
17790 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17791 "Invalid Pointer Size!");
17793 // For v = setjmp(buf), we generate
17796 // buf[LabelOffset] = restoreMBB
17797 // SjLjSetup restoreMBB
17803 // v = phi(main, restore)
17808 MachineBasicBlock *thisMBB = MBB;
17809 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17810 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17811 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17812 MF->insert(I, mainMBB);
17813 MF->insert(I, sinkMBB);
17814 MF->push_back(restoreMBB);
17816 MachineInstrBuilder MIB;
17818 // Transfer the remainder of BB and its successor edges to sinkMBB.
17819 sinkMBB->splice(sinkMBB->begin(), MBB,
17820 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17821 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17824 unsigned PtrStoreOpc = 0;
17825 unsigned LabelReg = 0;
17826 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17827 Reloc::Model RM = MF->getTarget().getRelocationModel();
17828 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17829 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17831 // Prepare IP either in reg or imm.
17832 if (!UseImmLabel) {
17833 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17834 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17835 LabelReg = MRI.createVirtualRegister(PtrRC);
17836 if (Subtarget->is64Bit()) {
17837 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17841 .addMBB(restoreMBB)
17844 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17845 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17846 .addReg(XII->getGlobalBaseReg(MF))
17849 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17853 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17855 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17856 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17857 if (i == X86::AddrDisp)
17858 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17860 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17863 MIB.addReg(LabelReg);
17865 MIB.addMBB(restoreMBB);
17866 MIB.setMemRefs(MMOBegin, MMOEnd);
17868 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17869 .addMBB(restoreMBB);
17871 const X86RegisterInfo *RegInfo =
17872 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17873 MIB.addRegMask(RegInfo->getNoPreservedMask());
17874 thisMBB->addSuccessor(mainMBB);
17875 thisMBB->addSuccessor(restoreMBB);
17879 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17880 mainMBB->addSuccessor(sinkMBB);
17883 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17884 TII->get(X86::PHI), DstReg)
17885 .addReg(mainDstReg).addMBB(mainMBB)
17886 .addReg(restoreDstReg).addMBB(restoreMBB);
17889 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17890 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17891 restoreMBB->addSuccessor(sinkMBB);
17893 MI->eraseFromParent();
17897 MachineBasicBlock *
17898 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17899 MachineBasicBlock *MBB) const {
17900 DebugLoc DL = MI->getDebugLoc();
17901 MachineFunction *MF = MBB->getParent();
17902 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17903 MachineRegisterInfo &MRI = MF->getRegInfo();
17905 // Memory Reference
17906 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17907 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17909 MVT PVT = getPointerTy();
17910 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17911 "Invalid Pointer Size!");
17913 const TargetRegisterClass *RC =
17914 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17915 unsigned Tmp = MRI.createVirtualRegister(RC);
17916 // Since FP is only updated here but NOT referenced, it's treated as GPR.
17917 const X86RegisterInfo *RegInfo =
17918 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17919 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17920 unsigned SP = RegInfo->getStackRegister();
17922 MachineInstrBuilder MIB;
17924 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17925 const int64_t SPOffset = 2 * PVT.getStoreSize();
17927 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17928 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17931 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17932 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17933 MIB.addOperand(MI->getOperand(i));
17934 MIB.setMemRefs(MMOBegin, MMOEnd);
17936 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17937 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17938 if (i == X86::AddrDisp)
17939 MIB.addDisp(MI->getOperand(i), LabelOffset);
17941 MIB.addOperand(MI->getOperand(i));
17943 MIB.setMemRefs(MMOBegin, MMOEnd);
17945 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17946 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17947 if (i == X86::AddrDisp)
17948 MIB.addDisp(MI->getOperand(i), SPOffset);
17950 MIB.addOperand(MI->getOperand(i));
17952 MIB.setMemRefs(MMOBegin, MMOEnd);
17954 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17956 MI->eraseFromParent();
17960 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17961 // accumulator loops. Writing back to the accumulator allows the coalescer
17962 // to remove extra copies in the loop.
17963 MachineBasicBlock *
17964 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17965 MachineBasicBlock *MBB) const {
17966 MachineOperand &AddendOp = MI->getOperand(3);
17968 // Bail out early if the addend isn't a register - we can't switch these.
17969 if (!AddendOp.isReg())
17972 MachineFunction &MF = *MBB->getParent();
17973 MachineRegisterInfo &MRI = MF.getRegInfo();
17975 // Check whether the addend is defined by a PHI:
17976 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17977 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17978 if (!AddendDef.isPHI())
17981 // Look for the following pattern:
17983 // %addend = phi [%entry, 0], [%loop, %result]
17985 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17989 // %addend = phi [%entry, 0], [%loop, %result]
17991 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17993 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17994 assert(AddendDef.getOperand(i).isReg());
17995 MachineOperand PHISrcOp = AddendDef.getOperand(i);
17996 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17997 if (&PHISrcInst == MI) {
17998 // Found a matching instruction.
17999 unsigned NewFMAOpc = 0;
18000 switch (MI->getOpcode()) {
18001 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18002 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18003 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18004 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18005 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18006 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18007 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18008 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18009 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18010 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18011 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18012 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18013 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18014 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18015 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18016 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18017 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18018 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18019 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18020 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18021 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18022 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18023 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18024 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18025 default: llvm_unreachable("Unrecognized FMA variant.");
18028 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18029 MachineInstrBuilder MIB =
18030 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18031 .addOperand(MI->getOperand(0))
18032 .addOperand(MI->getOperand(3))
18033 .addOperand(MI->getOperand(2))
18034 .addOperand(MI->getOperand(1));
18035 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18036 MI->eraseFromParent();
18043 MachineBasicBlock *
18044 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18045 MachineBasicBlock *BB) const {
18046 switch (MI->getOpcode()) {
18047 default: llvm_unreachable("Unexpected instr type to insert");
18048 case X86::TAILJMPd64:
18049 case X86::TAILJMPr64:
18050 case X86::TAILJMPm64:
18051 llvm_unreachable("TAILJMP64 would not be touched here.");
18052 case X86::TCRETURNdi64:
18053 case X86::TCRETURNri64:
18054 case X86::TCRETURNmi64:
18056 case X86::WIN_ALLOCA:
18057 return EmitLoweredWinAlloca(MI, BB);
18058 case X86::SEG_ALLOCA_32:
18059 return EmitLoweredSegAlloca(MI, BB, false);
18060 case X86::SEG_ALLOCA_64:
18061 return EmitLoweredSegAlloca(MI, BB, true);
18062 case X86::TLSCall_32:
18063 case X86::TLSCall_64:
18064 return EmitLoweredTLSCall(MI, BB);
18065 case X86::CMOV_GR8:
18066 case X86::CMOV_FR32:
18067 case X86::CMOV_FR64:
18068 case X86::CMOV_V4F32:
18069 case X86::CMOV_V2F64:
18070 case X86::CMOV_V2I64:
18071 case X86::CMOV_V8F32:
18072 case X86::CMOV_V4F64:
18073 case X86::CMOV_V4I64:
18074 case X86::CMOV_V16F32:
18075 case X86::CMOV_V8F64:
18076 case X86::CMOV_V8I64:
18077 case X86::CMOV_GR16:
18078 case X86::CMOV_GR32:
18079 case X86::CMOV_RFP32:
18080 case X86::CMOV_RFP64:
18081 case X86::CMOV_RFP80:
18082 return EmitLoweredSelect(MI, BB);
18084 case X86::FP32_TO_INT16_IN_MEM:
18085 case X86::FP32_TO_INT32_IN_MEM:
18086 case X86::FP32_TO_INT64_IN_MEM:
18087 case X86::FP64_TO_INT16_IN_MEM:
18088 case X86::FP64_TO_INT32_IN_MEM:
18089 case X86::FP64_TO_INT64_IN_MEM:
18090 case X86::FP80_TO_INT16_IN_MEM:
18091 case X86::FP80_TO_INT32_IN_MEM:
18092 case X86::FP80_TO_INT64_IN_MEM: {
18093 MachineFunction *F = BB->getParent();
18094 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18095 DebugLoc DL = MI->getDebugLoc();
18097 // Change the floating point control register to use "round towards zero"
18098 // mode when truncating to an integer value.
18099 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18100 addFrameReference(BuildMI(*BB, MI, DL,
18101 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18103 // Load the old value of the high byte of the control word...
18105 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18106 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18109 // Set the high part to be round to zero...
18110 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18113 // Reload the modified control word now...
18114 addFrameReference(BuildMI(*BB, MI, DL,
18115 TII->get(X86::FLDCW16m)), CWFrameIdx);
18117 // Restore the memory image of control word to original value
18118 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18121 // Get the X86 opcode to use.
18123 switch (MI->getOpcode()) {
18124 default: llvm_unreachable("illegal opcode!");
18125 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18126 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18127 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18128 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18129 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18130 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18131 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18132 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18133 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18137 MachineOperand &Op = MI->getOperand(0);
18139 AM.BaseType = X86AddressMode::RegBase;
18140 AM.Base.Reg = Op.getReg();
18142 AM.BaseType = X86AddressMode::FrameIndexBase;
18143 AM.Base.FrameIndex = Op.getIndex();
18145 Op = MI->getOperand(1);
18147 AM.Scale = Op.getImm();
18148 Op = MI->getOperand(2);
18150 AM.IndexReg = Op.getImm();
18151 Op = MI->getOperand(3);
18152 if (Op.isGlobal()) {
18153 AM.GV = Op.getGlobal();
18155 AM.Disp = Op.getImm();
18157 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18158 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18160 // Reload the original control word now.
18161 addFrameReference(BuildMI(*BB, MI, DL,
18162 TII->get(X86::FLDCW16m)), CWFrameIdx);
18164 MI->eraseFromParent(); // The pseudo instruction is gone now.
18167 // String/text processing lowering.
18168 case X86::PCMPISTRM128REG:
18169 case X86::VPCMPISTRM128REG:
18170 case X86::PCMPISTRM128MEM:
18171 case X86::VPCMPISTRM128MEM:
18172 case X86::PCMPESTRM128REG:
18173 case X86::VPCMPESTRM128REG:
18174 case X86::PCMPESTRM128MEM:
18175 case X86::VPCMPESTRM128MEM:
18176 assert(Subtarget->hasSSE42() &&
18177 "Target must have SSE4.2 or AVX features enabled");
18178 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18180 // String/text processing lowering.
18181 case X86::PCMPISTRIREG:
18182 case X86::VPCMPISTRIREG:
18183 case X86::PCMPISTRIMEM:
18184 case X86::VPCMPISTRIMEM:
18185 case X86::PCMPESTRIREG:
18186 case X86::VPCMPESTRIREG:
18187 case X86::PCMPESTRIMEM:
18188 case X86::VPCMPESTRIMEM:
18189 assert(Subtarget->hasSSE42() &&
18190 "Target must have SSE4.2 or AVX features enabled");
18191 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18193 // Thread synchronization.
18195 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18199 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18201 case X86::VASTART_SAVE_XMM_REGS:
18202 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18204 case X86::VAARG_64:
18205 return EmitVAARG64WithCustomInserter(MI, BB);
18207 case X86::EH_SjLj_SetJmp32:
18208 case X86::EH_SjLj_SetJmp64:
18209 return emitEHSjLjSetJmp(MI, BB);
18211 case X86::EH_SjLj_LongJmp32:
18212 case X86::EH_SjLj_LongJmp64:
18213 return emitEHSjLjLongJmp(MI, BB);
18215 case TargetOpcode::STACKMAP:
18216 case TargetOpcode::PATCHPOINT:
18217 return emitPatchPoint(MI, BB);
18219 case X86::VFMADDPDr213r:
18220 case X86::VFMADDPSr213r:
18221 case X86::VFMADDSDr213r:
18222 case X86::VFMADDSSr213r:
18223 case X86::VFMSUBPDr213r:
18224 case X86::VFMSUBPSr213r:
18225 case X86::VFMSUBSDr213r:
18226 case X86::VFMSUBSSr213r:
18227 case X86::VFNMADDPDr213r:
18228 case X86::VFNMADDPSr213r:
18229 case X86::VFNMADDSDr213r:
18230 case X86::VFNMADDSSr213r:
18231 case X86::VFNMSUBPDr213r:
18232 case X86::VFNMSUBPSr213r:
18233 case X86::VFNMSUBSDr213r:
18234 case X86::VFNMSUBSSr213r:
18235 case X86::VFMADDPDr213rY:
18236 case X86::VFMADDPSr213rY:
18237 case X86::VFMSUBPDr213rY:
18238 case X86::VFMSUBPSr213rY:
18239 case X86::VFNMADDPDr213rY:
18240 case X86::VFNMADDPSr213rY:
18241 case X86::VFNMSUBPDr213rY:
18242 case X86::VFNMSUBPSr213rY:
18243 return emitFMA3Instr(MI, BB);
18247 //===----------------------------------------------------------------------===//
18248 // X86 Optimization Hooks
18249 //===----------------------------------------------------------------------===//
18251 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18254 const SelectionDAG &DAG,
18255 unsigned Depth) const {
18256 unsigned BitWidth = KnownZero.getBitWidth();
18257 unsigned Opc = Op.getOpcode();
18258 assert((Opc >= ISD::BUILTIN_OP_END ||
18259 Opc == ISD::INTRINSIC_WO_CHAIN ||
18260 Opc == ISD::INTRINSIC_W_CHAIN ||
18261 Opc == ISD::INTRINSIC_VOID) &&
18262 "Should use MaskedValueIsZero if you don't know whether Op"
18263 " is a target node!");
18265 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
18279 // These nodes' second result is a boolean.
18280 if (Op.getResNo() == 0)
18283 case X86ISD::SETCC:
18284 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18286 case ISD::INTRINSIC_WO_CHAIN: {
18287 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18288 unsigned NumLoBits = 0;
18291 case Intrinsic::x86_sse_movmsk_ps:
18292 case Intrinsic::x86_avx_movmsk_ps_256:
18293 case Intrinsic::x86_sse2_movmsk_pd:
18294 case Intrinsic::x86_avx_movmsk_pd_256:
18295 case Intrinsic::x86_mmx_pmovmskb:
18296 case Intrinsic::x86_sse2_pmovmskb_128:
18297 case Intrinsic::x86_avx2_pmovmskb: {
18298 // High bits of movmskp{s|d}, pmovmskb are known zero.
18300 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18301 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
18302 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
18303 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
18304 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
18305 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
18306 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
18307 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
18309 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18318 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18320 const SelectionDAG &,
18321 unsigned Depth) const {
18322 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18323 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18324 return Op.getValueType().getScalarType().getSizeInBits();
18330 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18331 /// node is a GlobalAddress + offset.
18332 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18333 const GlobalValue* &GA,
18334 int64_t &Offset) const {
18335 if (N->getOpcode() == X86ISD::Wrapper) {
18336 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18337 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18338 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18342 return TargetLowering::isGAPlusOffset(N, GA, Offset);
18345 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18346 /// same as extracting the high 128-bit part of 256-bit vector and then
18347 /// inserting the result into the low part of a new 256-bit vector
18348 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18349 EVT VT = SVOp->getValueType(0);
18350 unsigned NumElems = VT.getVectorNumElements();
18352 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18353 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18354 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18355 SVOp->getMaskElt(j) >= 0)
18361 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18362 /// same as extracting the low 128-bit part of 256-bit vector and then
18363 /// inserting the result into the high part of a new 256-bit vector
18364 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18365 EVT VT = SVOp->getValueType(0);
18366 unsigned NumElems = VT.getVectorNumElements();
18368 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18369 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18370 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18371 SVOp->getMaskElt(j) >= 0)
18377 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18378 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18379 TargetLowering::DAGCombinerInfo &DCI,
18380 const X86Subtarget* Subtarget) {
18382 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18383 SDValue V1 = SVOp->getOperand(0);
18384 SDValue V2 = SVOp->getOperand(1);
18385 EVT VT = SVOp->getValueType(0);
18386 unsigned NumElems = VT.getVectorNumElements();
18388 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18389 V2.getOpcode() == ISD::CONCAT_VECTORS) {
18393 // V UNDEF BUILD_VECTOR UNDEF
18395 // CONCAT_VECTOR CONCAT_VECTOR
18398 // RESULT: V + zero extended
18400 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18401 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18402 V1.getOperand(1).getOpcode() != ISD::UNDEF)
18405 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18408 // To match the shuffle mask, the first half of the mask should
18409 // be exactly the first vector, and all the rest a splat with the
18410 // first element of the second one.
18411 for (unsigned i = 0; i != NumElems/2; ++i)
18412 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18413 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18416 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18417 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18418 if (Ld->hasNUsesOfValue(1, 0)) {
18419 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18420 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18422 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18424 Ld->getPointerInfo(),
18425 Ld->getAlignment(),
18426 false/*isVolatile*/, true/*ReadMem*/,
18427 false/*WriteMem*/);
18429 // Make sure the newly-created LOAD is in the same position as Ld in
18430 // terms of dependency. We create a TokenFactor for Ld and ResNode,
18431 // and update uses of Ld's output chain to use the TokenFactor.
18432 if (Ld->hasAnyUseOfValue(1)) {
18433 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18434 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18435 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18436 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18437 SDValue(ResNode.getNode(), 1));
18440 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18444 // Emit a zeroed vector and insert the desired subvector on its
18446 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18447 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18448 return DCI.CombineTo(N, InsV);
18451 //===--------------------------------------------------------------------===//
18452 // Combine some shuffles into subvector extracts and inserts:
18455 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18456 if (isShuffleHigh128VectorInsertLow(SVOp)) {
18457 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18458 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18459 return DCI.CombineTo(N, InsV);
18462 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18463 if (isShuffleLow128VectorInsertHigh(SVOp)) {
18464 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18465 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18466 return DCI.CombineTo(N, InsV);
18472 /// \brief Get the PSHUF-style mask from PSHUF node.
18474 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18475 /// PSHUF-style masks that can be reused with such instructions.
18476 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18477 SmallVector<int, 4> Mask;
18479 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18483 switch (N.getOpcode()) {
18484 case X86ISD::PSHUFD:
18486 case X86ISD::PSHUFLW:
18489 case X86ISD::PSHUFHW:
18490 Mask.erase(Mask.begin(), Mask.begin() + 4);
18491 for (int &M : Mask)
18495 llvm_unreachable("No valid shuffle instruction found!");
18499 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18501 /// We walk up the chain and look for a combinable shuffle, skipping over
18502 /// shuffles that we could hoist this shuffle's transformation past without
18503 /// altering anything.
18504 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18506 TargetLowering::DAGCombinerInfo &DCI) {
18507 assert(N.getOpcode() == X86ISD::PSHUFD &&
18508 "Called with something other than an x86 128-bit half shuffle!");
18511 // Walk up a single-use chain looking for a combinable shuffle.
18512 SDValue V = N.getOperand(0);
18513 for (; V.hasOneUse(); V = V.getOperand(0)) {
18514 switch (V.getOpcode()) {
18516 return false; // Nothing combined!
18519 // Skip bitcasts as we always know the type for the target specific
18523 case X86ISD::PSHUFD:
18524 // Found another dword shuffle.
18527 case X86ISD::PSHUFLW:
18528 // Check that the low words (being shuffled) are the identity in the
18529 // dword shuffle, and the high words are self-contained.
18530 if (Mask[0] != 0 || Mask[1] != 1 ||
18531 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
18536 case X86ISD::PSHUFHW:
18537 // Check that the high words (being shuffled) are the identity in the
18538 // dword shuffle, and the low words are self-contained.
18539 if (Mask[2] != 2 || Mask[3] != 3 ||
18540 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
18545 case X86ISD::UNPCKL:
18546 case X86ISD::UNPCKH:
18547 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
18548 // shuffle into a preceding word shuffle.
18549 if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
18552 // Search for a half-shuffle which we can combine with.
18553 unsigned CombineOp =
18554 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18555 if (V.getOperand(0) != V.getOperand(1) ||
18556 !V->isOnlyUserOf(V.getOperand(0).getNode()))
18558 V = V.getOperand(0);
18560 switch (V.getOpcode()) {
18562 return false; // Nothing to combine.
18564 case X86ISD::PSHUFLW:
18565 case X86ISD::PSHUFHW:
18566 if (V.getOpcode() == CombineOp)
18571 V = V.getOperand(0);
18575 } while (V.hasOneUse());
18578 // Break out of the loop if we break out of the switch.
18582 if (!V.hasOneUse())
18583 // We fell out of the loop without finding a viable combining instruction.
18586 // Record the old value to use in RAUW-ing.
18589 // Merge this node's mask and our incoming mask.
18590 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18591 for (int &M : Mask)
18593 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
18594 getV4X86ShuffleImm8ForMask(Mask, DAG));
18596 // It is possible that one of the combinable shuffles was completely absorbed
18597 // by the other, just replace it and revisit all users in that case.
18598 if (Old.getNode() == V.getNode()) {
18599 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
18603 // Replace N with its operand as we're going to combine that shuffle away.
18604 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18606 // Replace the combinable shuffle with the combined one, updating all users
18607 // so that we re-evaluate the chain here.
18608 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18612 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
18614 /// We walk up the chain, skipping shuffles of the other half and looking
18615 /// through shuffles which switch halves trying to find a shuffle of the same
18616 /// pair of dwords.
18617 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
18619 TargetLowering::DAGCombinerInfo &DCI) {
18621 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
18622 "Called with something other than an x86 128-bit half shuffle!");
18624 unsigned CombineOpcode = N.getOpcode();
18626 // Walk up a single-use chain looking for a combinable shuffle.
18627 SDValue V = N.getOperand(0);
18628 for (; V.hasOneUse(); V = V.getOperand(0)) {
18629 switch (V.getOpcode()) {
18631 return false; // Nothing combined!
18634 // Skip bitcasts as we always know the type for the target specific
18638 case X86ISD::PSHUFLW:
18639 case X86ISD::PSHUFHW:
18640 if (V.getOpcode() == CombineOpcode)
18643 // Other-half shuffles are no-ops.
18646 case X86ISD::PSHUFD: {
18647 // We can only handle pshufd if the half we are combining either stays in
18648 // its half, or switches to the other half. Bail if one of these isn't
18650 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18651 int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
18652 if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
18653 (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
18656 // Map the mask through the pshufd and keep walking up the chain.
18657 for (int i = 0; i < 4; ++i)
18658 Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
18660 // Switch halves if the pshufd does.
18662 VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18666 // Break out of the loop if we break out of the switch.
18670 if (!V.hasOneUse())
18671 // We fell out of the loop without finding a viable combining instruction.
18674 // Record the old value to use in RAUW-ing.
18677 // Merge this node's mask and our incoming mask (adjusted to account for all
18678 // the pshufd instructions encountered).
18679 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18680 for (int &M : Mask)
18682 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
18683 getV4X86ShuffleImm8ForMask(Mask, DAG));
18685 // Replace N with its operand as we're going to combine that shuffle away.
18686 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18688 // Replace the combinable shuffle with the combined one, updating all users
18689 // so that we re-evaluate the chain here.
18690 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18694 /// \brief Try to combine x86 target specific shuffles.
18695 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
18696 TargetLowering::DAGCombinerInfo &DCI,
18697 const X86Subtarget *Subtarget) {
18699 MVT VT = N.getSimpleValueType();
18700 SmallVector<int, 4> Mask;
18702 switch (N.getOpcode()) {
18703 case X86ISD::PSHUFD:
18704 case X86ISD::PSHUFLW:
18705 case X86ISD::PSHUFHW:
18706 Mask = getPSHUFShuffleMask(N);
18707 assert(Mask.size() == 4);
18713 // Nuke no-op shuffles that show up after combining.
18714 if (isNoopShuffleMask(Mask))
18715 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
18717 // Look for simplifications involving one or two shuffle instructions.
18718 SDValue V = N.getOperand(0);
18719 switch (N.getOpcode()) {
18722 case X86ISD::PSHUFLW:
18723 case X86ISD::PSHUFHW:
18724 assert(VT == MVT::v8i16);
18727 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
18728 return SDValue(); // We combined away this shuffle, so we're done.
18730 // See if this reduces to a PSHUFD which is no more expensive and can
18731 // combine with more operations.
18732 if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
18733 areAdjacentMasksSequential(Mask)) {
18734 int DMask[] = {-1, -1, -1, -1};
18735 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
18736 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
18737 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
18738 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
18739 DCI.AddToWorklist(V.getNode());
18740 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
18741 getV4X86ShuffleImm8ForMask(DMask, DAG));
18742 DCI.AddToWorklist(V.getNode());
18743 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
18746 // Look for shuffle patterns which can be implemented as a single unpack.
18747 // FIXME: This doesn't handle the location of the PSHUFD generically, and
18748 // only works when we have a PSHUFD followed by two half-shuffles.
18749 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
18750 (V.getOpcode() == X86ISD::PSHUFLW ||
18751 V.getOpcode() == X86ISD::PSHUFHW) &&
18752 V.getOpcode() != N.getOpcode() &&
18754 SDValue D = V.getOperand(0);
18755 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
18756 D = D.getOperand(0);
18757 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
18758 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18759 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
18760 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
18761 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
18763 for (int i = 0; i < 4; ++i) {
18764 WordMask[i + NOffset] = Mask[i] + NOffset;
18765 WordMask[i + VOffset] = VMask[i] + VOffset;
18767 // Map the word mask through the DWord mask.
18769 for (int i = 0; i < 8; ++i)
18770 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
18771 const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
18772 const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
18773 if (std::equal(std::begin(MappedMask), std::end(MappedMask),
18774 std::begin(UnpackLoMask)) ||
18775 std::equal(std::begin(MappedMask), std::end(MappedMask),
18776 std::begin(UnpackHiMask))) {
18777 // We can replace all three shuffles with an unpack.
18778 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
18779 DCI.AddToWorklist(V.getNode());
18780 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
18782 DL, MVT::v8i16, V, V);
18789 case X86ISD::PSHUFD:
18790 if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
18791 return SDValue(); // We combined away this shuffle.
18799 /// PerformShuffleCombine - Performs several different shuffle combines.
18800 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
18801 TargetLowering::DAGCombinerInfo &DCI,
18802 const X86Subtarget *Subtarget) {
18804 SDValue N0 = N->getOperand(0);
18805 SDValue N1 = N->getOperand(1);
18806 EVT VT = N->getValueType(0);
18808 // Canonicalize shuffles that perform 'addsub' on packed float vectors
18809 // according to the rule:
18810 // (shuffle (FADD A, B), (FSUB A, B), Mask) ->
18811 // (shuffle (FSUB A, -B), (FADD A, -B), Mask)
18813 // Where 'Mask' is:
18814 // <0,5,2,7> -- for v4f32 and v4f64 shuffles;
18815 // <0,3> -- for v2f64 shuffles;
18816 // <0,9,2,11,4,13,6,15> -- for v8f32 shuffles.
18818 // This helps pattern-matching more SSE3/AVX ADDSUB instructions
18819 // during ISel stage.
18820 if (N->getOpcode() == ISD::VECTOR_SHUFFLE &&
18821 ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18822 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18823 N0->getOpcode() == ISD::FADD && N1->getOpcode() == ISD::FSUB &&
18824 // Operands to the FADD and FSUB must be the same.
18825 ((N0->getOperand(0) == N1->getOperand(0) &&
18826 N0->getOperand(1) == N1->getOperand(1)) ||
18827 // FADD is commutable. See if by commuting the operands of the FADD
18828 // we would still be able to match the operands of the FSUB dag node.
18829 (N0->getOperand(1) == N1->getOperand(0) &&
18830 N0->getOperand(0) == N1->getOperand(1))) &&
18831 N0->getOperand(0)->getOpcode() != ISD::UNDEF &&
18832 N0->getOperand(1)->getOpcode() != ISD::UNDEF) {
18834 ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
18835 unsigned NumElts = VT.getVectorNumElements();
18836 ArrayRef<int> Mask = SV->getMask();
18837 bool CanFold = true;
18839 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i)
18840 CanFold = Mask[i] == (int)((i & 1) ? i + NumElts : i);
18843 SDValue Op0 = N1->getOperand(0);
18844 SDValue Op1 = DAG.getNode(ISD::FNEG, dl, VT, N1->getOperand(1));
18845 SDValue Sub = DAG.getNode(ISD::FSUB, dl, VT, Op0, Op1);
18846 SDValue Add = DAG.getNode(ISD::FADD, dl, VT, Op0, Op1);
18847 return DAG.getVectorShuffle(VT, dl, Sub, Add, Mask);
18851 // Don't create instructions with illegal types after legalize types has run.
18852 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18853 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
18856 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
18857 if (Subtarget->hasFp256() && VT.is256BitVector() &&
18858 N->getOpcode() == ISD::VECTOR_SHUFFLE)
18859 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
18861 // During Type Legalization, when promoting illegal vector types,
18862 // the backend might introduce new shuffle dag nodes and bitcasts.
18864 // This code performs the following transformation:
18865 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
18866 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
18868 // We do this only if both the bitcast and the BINOP dag nodes have
18869 // one use. Also, perform this transformation only if the new binary
18870 // operation is legal. This is to avoid introducing dag nodes that
18871 // potentially need to be further expanded (or custom lowered) into a
18872 // less optimal sequence of dag nodes.
18873 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
18874 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
18875 N0.getOpcode() == ISD::BITCAST) {
18876 SDValue BC0 = N0.getOperand(0);
18877 EVT SVT = BC0.getValueType();
18878 unsigned Opcode = BC0.getOpcode();
18879 unsigned NumElts = VT.getVectorNumElements();
18881 if (BC0.hasOneUse() && SVT.isVector() &&
18882 SVT.getVectorNumElements() * 2 == NumElts &&
18883 TLI.isOperationLegal(Opcode, VT)) {
18884 bool CanFold = false;
18896 unsigned SVTNumElts = SVT.getVectorNumElements();
18897 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18898 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
18899 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
18900 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
18901 CanFold = SVOp->getMaskElt(i) < 0;
18904 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
18905 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
18906 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
18907 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
18912 // Only handle 128 wide vector from here on.
18913 if (!VT.is128BitVector())
18916 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
18917 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
18918 // consecutive, non-overlapping, and in the right order.
18919 SmallVector<SDValue, 16> Elts;
18920 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
18921 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
18923 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
18927 if (isTargetShuffle(N->getOpcode())) {
18929 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
18930 if (Shuffle.getNode())
18937 /// PerformTruncateCombine - Converts truncate operation to
18938 /// a sequence of vector shuffle operations.
18939 /// It is possible when we truncate 256-bit vector to 128-bit vector
18940 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
18941 TargetLowering::DAGCombinerInfo &DCI,
18942 const X86Subtarget *Subtarget) {
18946 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
18947 /// specific shuffle of a load can be folded into a single element load.
18948 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
18949 /// shuffles have been customed lowered so we need to handle those here.
18950 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
18951 TargetLowering::DAGCombinerInfo &DCI) {
18952 if (DCI.isBeforeLegalizeOps())
18955 SDValue InVec = N->getOperand(0);
18956 SDValue EltNo = N->getOperand(1);
18958 if (!isa<ConstantSDNode>(EltNo))
18961 EVT VT = InVec.getValueType();
18963 bool HasShuffleIntoBitcast = false;
18964 if (InVec.getOpcode() == ISD::BITCAST) {
18965 // Don't duplicate a load with other uses.
18966 if (!InVec.hasOneUse())
18968 EVT BCVT = InVec.getOperand(0).getValueType();
18969 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
18971 InVec = InVec.getOperand(0);
18972 HasShuffleIntoBitcast = true;
18975 if (!isTargetShuffle(InVec.getOpcode()))
18978 // Don't duplicate a load with other uses.
18979 if (!InVec.hasOneUse())
18982 SmallVector<int, 16> ShuffleMask;
18984 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18988 // Select the input vector, guarding against out of range extract vector.
18989 unsigned NumElems = VT.getVectorNumElements();
18990 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18991 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18992 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18993 : InVec.getOperand(1);
18995 // If inputs to shuffle are the same for both ops, then allow 2 uses
18996 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18998 if (LdNode.getOpcode() == ISD::BITCAST) {
18999 // Don't duplicate a load with other uses.
19000 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19003 AllowedUses = 1; // only allow 1 load use if we have a bitcast
19004 LdNode = LdNode.getOperand(0);
19007 if (!ISD::isNormalLoad(LdNode.getNode()))
19010 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19012 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19015 if (HasShuffleIntoBitcast) {
19016 // If there's a bitcast before the shuffle, check if the load type and
19017 // alignment is valid.
19018 unsigned Align = LN0->getAlignment();
19019 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19020 unsigned NewAlign = TLI.getDataLayout()->
19021 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19023 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19027 // All checks match so transform back to vector_shuffle so that DAG combiner
19028 // can finish the job
19031 // Create shuffle node taking into account the case that its a unary shuffle
19032 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19033 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19034 InVec.getOperand(0), Shuffle,
19036 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19037 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19041 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19042 /// generation and convert it from being a bunch of shuffles and extracts
19043 /// to a simple store and scalar loads to extract the elements.
19044 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19045 TargetLowering::DAGCombinerInfo &DCI) {
19046 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19047 if (NewOp.getNode())
19050 SDValue InputVector = N->getOperand(0);
19052 // Detect whether we are trying to convert from mmx to i32 and the bitcast
19053 // from mmx to v2i32 has a single usage.
19054 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19055 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19056 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19057 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19058 N->getValueType(0),
19059 InputVector.getNode()->getOperand(0));
19061 // Only operate on vectors of 4 elements, where the alternative shuffling
19062 // gets to be more expensive.
19063 if (InputVector.getValueType() != MVT::v4i32)
19066 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19067 // single use which is a sign-extend or zero-extend, and all elements are
19069 SmallVector<SDNode *, 4> Uses;
19070 unsigned ExtractedElements = 0;
19071 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19072 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19073 if (UI.getUse().getResNo() != InputVector.getResNo())
19076 SDNode *Extract = *UI;
19077 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19080 if (Extract->getValueType(0) != MVT::i32)
19082 if (!Extract->hasOneUse())
19084 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19085 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19087 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19090 // Record which element was extracted.
19091 ExtractedElements |=
19092 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19094 Uses.push_back(Extract);
19097 // If not all the elements were used, this may not be worthwhile.
19098 if (ExtractedElements != 15)
19101 // Ok, we've now decided to do the transformation.
19102 SDLoc dl(InputVector);
19104 // Store the value to a temporary stack slot.
19105 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19106 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19107 MachinePointerInfo(), false, false, 0);
19109 // Replace each use (extract) with a load of the appropriate element.
19110 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19111 UE = Uses.end(); UI != UE; ++UI) {
19112 SDNode *Extract = *UI;
19114 // cOMpute the element's address.
19115 SDValue Idx = Extract->getOperand(1);
19117 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19118 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19119 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19120 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19122 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19123 StackPtr, OffsetVal);
19125 // Load the scalar.
19126 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19127 ScalarAddr, MachinePointerInfo(),
19128 false, false, false, 0);
19130 // Replace the exact with the load.
19131 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19134 // The replacement was made in place; don't return anything.
19138 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19139 static std::pair<unsigned, bool>
19140 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19141 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19142 if (!VT.isVector())
19143 return std::make_pair(0, false);
19145 bool NeedSplit = false;
19146 switch (VT.getSimpleVT().SimpleTy) {
19147 default: return std::make_pair(0, false);
19151 if (!Subtarget->hasAVX2())
19153 if (!Subtarget->hasAVX())
19154 return std::make_pair(0, false);
19159 if (!Subtarget->hasSSE2())
19160 return std::make_pair(0, false);
19163 // SSE2 has only a small subset of the operations.
19164 bool hasUnsigned = Subtarget->hasSSE41() ||
19165 (Subtarget->hasSSE2() && VT == MVT::v16i8);
19166 bool hasSigned = Subtarget->hasSSE41() ||
19167 (Subtarget->hasSSE2() && VT == MVT::v8i16);
19169 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19172 // Check for x CC y ? x : y.
19173 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19174 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19179 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19182 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19185 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19188 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19190 // Check for x CC y ? y : x -- a min/max with reversed arms.
19191 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19192 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19197 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19200 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19203 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19206 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19210 return std::make_pair(Opc, NeedSplit);
19214 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19215 const X86Subtarget *Subtarget) {
19217 SDValue Cond = N->getOperand(0);
19218 SDValue LHS = N->getOperand(1);
19219 SDValue RHS = N->getOperand(2);
19221 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19222 SDValue CondSrc = Cond->getOperand(0);
19223 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19224 Cond = CondSrc->getOperand(0);
19227 MVT VT = N->getSimpleValueType(0);
19228 MVT EltVT = VT.getVectorElementType();
19229 unsigned NumElems = VT.getVectorNumElements();
19230 // There is no blend with immediate in AVX-512.
19231 if (VT.is512BitVector())
19234 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19236 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19239 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19242 unsigned MaskValue = 0;
19243 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19246 SmallVector<int, 8> ShuffleMask(NumElems, -1);
19247 for (unsigned i = 0; i < NumElems; ++i) {
19248 // Be sure we emit undef where we can.
19249 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19250 ShuffleMask[i] = -1;
19252 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19255 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19258 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19260 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19261 TargetLowering::DAGCombinerInfo &DCI,
19262 const X86Subtarget *Subtarget) {
19264 SDValue Cond = N->getOperand(0);
19265 // Get the LHS/RHS of the select.
19266 SDValue LHS = N->getOperand(1);
19267 SDValue RHS = N->getOperand(2);
19268 EVT VT = LHS.getValueType();
19269 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19271 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19272 // instructions match the semantics of the common C idiom x<y?x:y but not
19273 // x<=y?x:y, because of how they handle negative zero (which can be
19274 // ignored in unsafe-math mode).
19275 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19276 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19277 (Subtarget->hasSSE2() ||
19278 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19279 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19281 unsigned Opcode = 0;
19282 // Check for x CC y ? x : y.
19283 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19284 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19288 // Converting this to a min would handle NaNs incorrectly, and swapping
19289 // the operands would cause it to handle comparisons between positive
19290 // and negative zero incorrectly.
19291 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19292 if (!DAG.getTarget().Options.UnsafeFPMath &&
19293 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19295 std::swap(LHS, RHS);
19297 Opcode = X86ISD::FMIN;
19300 // Converting this to a min would handle comparisons between positive
19301 // and negative zero incorrectly.
19302 if (!DAG.getTarget().Options.UnsafeFPMath &&
19303 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19305 Opcode = X86ISD::FMIN;
19308 // Converting this to a min would handle both negative zeros and NaNs
19309 // incorrectly, but we can swap the operands to fix both.
19310 std::swap(LHS, RHS);
19314 Opcode = X86ISD::FMIN;
19318 // Converting this to a max would handle comparisons between positive
19319 // and negative zero incorrectly.
19320 if (!DAG.getTarget().Options.UnsafeFPMath &&
19321 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19323 Opcode = X86ISD::FMAX;
19326 // Converting this to a max would handle NaNs incorrectly, and swapping
19327 // the operands would cause it to handle comparisons between positive
19328 // and negative zero incorrectly.
19329 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19330 if (!DAG.getTarget().Options.UnsafeFPMath &&
19331 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19333 std::swap(LHS, RHS);
19335 Opcode = X86ISD::FMAX;
19338 // Converting this to a max would handle both negative zeros and NaNs
19339 // incorrectly, but we can swap the operands to fix both.
19340 std::swap(LHS, RHS);
19344 Opcode = X86ISD::FMAX;
19347 // Check for x CC y ? y : x -- a min/max with reversed arms.
19348 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19349 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19353 // Converting this to a min would handle comparisons between positive
19354 // and negative zero incorrectly, and swapping the operands would
19355 // cause it to handle NaNs incorrectly.
19356 if (!DAG.getTarget().Options.UnsafeFPMath &&
19357 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19358 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19360 std::swap(LHS, RHS);
19362 Opcode = X86ISD::FMIN;
19365 // Converting this to a min would handle NaNs incorrectly.
19366 if (!DAG.getTarget().Options.UnsafeFPMath &&
19367 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19369 Opcode = X86ISD::FMIN;
19372 // Converting this to a min would handle both negative zeros and NaNs
19373 // incorrectly, but we can swap the operands to fix both.
19374 std::swap(LHS, RHS);
19378 Opcode = X86ISD::FMIN;
19382 // Converting this to a max would handle NaNs incorrectly.
19383 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19385 Opcode = X86ISD::FMAX;
19388 // Converting this to a max would handle comparisons between positive
19389 // and negative zero incorrectly, and swapping the operands would
19390 // cause it to handle NaNs incorrectly.
19391 if (!DAG.getTarget().Options.UnsafeFPMath &&
19392 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19393 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19395 std::swap(LHS, RHS);
19397 Opcode = X86ISD::FMAX;
19400 // Converting this to a max would handle both negative zeros and NaNs
19401 // incorrectly, but we can swap the operands to fix both.
19402 std::swap(LHS, RHS);
19406 Opcode = X86ISD::FMAX;
19412 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19415 EVT CondVT = Cond.getValueType();
19416 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19417 CondVT.getVectorElementType() == MVT::i1) {
19418 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19419 // lowering on AVX-512. In this case we convert it to
19420 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19421 // The same situation for all 128 and 256-bit vectors of i8 and i16
19422 EVT OpVT = LHS.getValueType();
19423 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19424 (OpVT.getVectorElementType() == MVT::i8 ||
19425 OpVT.getVectorElementType() == MVT::i16)) {
19426 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19427 DCI.AddToWorklist(Cond.getNode());
19428 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19431 // If this is a select between two integer constants, try to do some
19433 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19434 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19435 // Don't do this for crazy integer types.
19436 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19437 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19438 // so that TrueC (the true value) is larger than FalseC.
19439 bool NeedsCondInvert = false;
19441 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19442 // Efficiently invertible.
19443 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
19444 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
19445 isa<ConstantSDNode>(Cond.getOperand(1))))) {
19446 NeedsCondInvert = true;
19447 std::swap(TrueC, FalseC);
19450 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
19451 if (FalseC->getAPIntValue() == 0 &&
19452 TrueC->getAPIntValue().isPowerOf2()) {
19453 if (NeedsCondInvert) // Invert the condition if needed.
19454 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19455 DAG.getConstant(1, Cond.getValueType()));
19457 // Zero extend the condition if needed.
19458 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19460 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19461 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19462 DAG.getConstant(ShAmt, MVT::i8));
19465 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19466 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19467 if (NeedsCondInvert) // Invert the condition if needed.
19468 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19469 DAG.getConstant(1, Cond.getValueType()));
19471 // Zero extend the condition if needed.
19472 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19473 FalseC->getValueType(0), Cond);
19474 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19475 SDValue(FalseC, 0));
19478 // Optimize cases that will turn into an LEA instruction. This requires
19479 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19480 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19481 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19482 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19484 bool isFastMultiplier = false;
19486 switch ((unsigned char)Diff) {
19488 case 1: // result = add base, cond
19489 case 2: // result = lea base( , cond*2)
19490 case 3: // result = lea base(cond, cond*2)
19491 case 4: // result = lea base( , cond*4)
19492 case 5: // result = lea base(cond, cond*4)
19493 case 8: // result = lea base( , cond*8)
19494 case 9: // result = lea base(cond, cond*8)
19495 isFastMultiplier = true;
19500 if (isFastMultiplier) {
19501 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19502 if (NeedsCondInvert) // Invert the condition if needed.
19503 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19504 DAG.getConstant(1, Cond.getValueType()));
19506 // Zero extend the condition if needed.
19507 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19509 // Scale the condition by the difference.
19511 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19512 DAG.getConstant(Diff, Cond.getValueType()));
19514 // Add the base if non-zero.
19515 if (FalseC->getAPIntValue() != 0)
19516 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19517 SDValue(FalseC, 0));
19524 // Canonicalize max and min:
19525 // (x > y) ? x : y -> (x >= y) ? x : y
19526 // (x < y) ? x : y -> (x <= y) ? x : y
19527 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19528 // the need for an extra compare
19529 // against zero. e.g.
19530 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19532 // testl %edi, %edi
19534 // cmovgl %edi, %eax
19538 // cmovsl %eax, %edi
19539 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19540 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19541 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19542 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19547 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19548 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19549 Cond.getOperand(0), Cond.getOperand(1), NewCC);
19550 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19555 // Early exit check
19556 if (!TLI.isTypeLegal(VT))
19559 // Match VSELECTs into subs with unsigned saturation.
19560 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19561 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
19562 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
19563 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
19564 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19566 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
19567 // left side invert the predicate to simplify logic below.
19569 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
19571 CC = ISD::getSetCCInverse(CC, true);
19572 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
19576 if (Other.getNode() && Other->getNumOperands() == 2 &&
19577 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
19578 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
19579 SDValue CondRHS = Cond->getOperand(1);
19581 // Look for a general sub with unsigned saturation first.
19582 // x >= y ? x-y : 0 --> subus x, y
19583 // x > y ? x-y : 0 --> subus x, y
19584 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
19585 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
19586 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19588 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
19589 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
19590 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
19591 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
19592 // If the RHS is a constant we have to reverse the const
19593 // canonicalization.
19594 // x > C-1 ? x+-C : 0 --> subus x, C
19595 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
19596 CondRHSConst->getAPIntValue() ==
19597 (-OpRHSConst->getAPIntValue() - 1))
19598 return DAG.getNode(
19599 X86ISD::SUBUS, DL, VT, OpLHS,
19600 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
19602 // Another special case: If C was a sign bit, the sub has been
19603 // canonicalized into a xor.
19604 // FIXME: Would it be better to use computeKnownBits to determine
19605 // whether it's safe to decanonicalize the xor?
19606 // x s< 0 ? x^C : 0 --> subus x, C
19607 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
19608 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
19609 OpRHSConst->getAPIntValue().isSignBit())
19610 // Note that we have to rebuild the RHS constant here to ensure we
19611 // don't rely on particular values of undef lanes.
19612 return DAG.getNode(
19613 X86ISD::SUBUS, DL, VT, OpLHS,
19614 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
19619 // Try to match a min/max vector operation.
19620 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
19621 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
19622 unsigned Opc = ret.first;
19623 bool NeedSplit = ret.second;
19625 if (Opc && NeedSplit) {
19626 unsigned NumElems = VT.getVectorNumElements();
19627 // Extract the LHS vectors
19628 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
19629 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
19631 // Extract the RHS vectors
19632 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
19633 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
19635 // Create min/max for each subvector
19636 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
19637 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
19639 // Merge the result
19640 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
19642 return DAG.getNode(Opc, DL, VT, LHS, RHS);
19645 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
19646 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19647 // Check if SETCC has already been promoted
19648 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
19649 // Check that condition value type matches vselect operand type
19652 assert(Cond.getValueType().isVector() &&
19653 "vector select expects a vector selector!");
19655 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
19656 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
19658 if (!TValIsAllOnes && !FValIsAllZeros) {
19659 // Try invert the condition if true value is not all 1s and false value
19661 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
19662 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
19664 if (TValIsAllZeros || FValIsAllOnes) {
19665 SDValue CC = Cond.getOperand(2);
19666 ISD::CondCode NewCC =
19667 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
19668 Cond.getOperand(0).getValueType().isInteger());
19669 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
19670 std::swap(LHS, RHS);
19671 TValIsAllOnes = FValIsAllOnes;
19672 FValIsAllZeros = TValIsAllZeros;
19676 if (TValIsAllOnes || FValIsAllZeros) {
19679 if (TValIsAllOnes && FValIsAllZeros)
19681 else if (TValIsAllOnes)
19682 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
19683 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
19684 else if (FValIsAllZeros)
19685 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
19686 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
19688 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
19692 // Try to fold this VSELECT into a MOVSS/MOVSD
19693 if (N->getOpcode() == ISD::VSELECT &&
19694 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
19695 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
19696 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
19697 bool CanFold = false;
19698 unsigned NumElems = Cond.getNumOperands();
19702 if (isZero(Cond.getOperand(0))) {
19705 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
19706 // fold (vselect <0,-1> -> (movsd A, B)
19707 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19708 CanFold = isAllOnes(Cond.getOperand(i));
19709 } else if (isAllOnes(Cond.getOperand(0))) {
19713 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
19714 // fold (vselect <-1,0> -> (movsd B, A)
19715 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19716 CanFold = isZero(Cond.getOperand(i));
19720 if (VT == MVT::v4i32 || VT == MVT::v4f32)
19721 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
19722 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
19725 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
19726 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
19727 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
19728 // (v2i64 (bitcast B)))))
19730 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
19731 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
19732 // (v2f64 (bitcast B)))))
19734 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
19735 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
19736 // (v2i64 (bitcast A)))))
19738 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
19739 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
19740 // (v2f64 (bitcast A)))))
19742 CanFold = (isZero(Cond.getOperand(0)) &&
19743 isZero(Cond.getOperand(1)) &&
19744 isAllOnes(Cond.getOperand(2)) &&
19745 isAllOnes(Cond.getOperand(3)));
19747 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
19748 isAllOnes(Cond.getOperand(1)) &&
19749 isZero(Cond.getOperand(2)) &&
19750 isZero(Cond.getOperand(3))) {
19752 std::swap(LHS, RHS);
19756 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
19757 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
19758 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
19759 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
19761 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
19767 // If we know that this node is legal then we know that it is going to be
19768 // matched by one of the SSE/AVX BLEND instructions. These instructions only
19769 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
19770 // to simplify previous instructions.
19771 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
19772 !DCI.isBeforeLegalize() &&
19773 // We explicitly check against v8i16 and v16i16 because, although
19774 // they're marked as Custom, they might only be legal when Cond is a
19775 // build_vector of constants. This will be taken care in a later
19777 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
19778 VT != MVT::v8i16)) {
19779 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
19781 // Don't optimize vector selects that map to mask-registers.
19785 // Check all uses of that condition operand to check whether it will be
19786 // consumed by non-BLEND instructions, which may depend on all bits are set
19788 for (SDNode::use_iterator I = Cond->use_begin(),
19789 E = Cond->use_end(); I != E; ++I)
19790 if (I->getOpcode() != ISD::VSELECT)
19791 // TODO: Add other opcodes eventually lowered into BLEND.
19794 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
19795 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
19797 APInt KnownZero, KnownOne;
19798 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
19799 DCI.isBeforeLegalizeOps());
19800 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
19801 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
19802 DCI.CommitTargetLoweringOpt(TLO);
19805 // We should generate an X86ISD::BLENDI from a vselect if its argument
19806 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
19807 // constants. This specific pattern gets generated when we split a
19808 // selector for a 512 bit vector in a machine without AVX512 (but with
19809 // 256-bit vectors), during legalization:
19811 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
19813 // Iff we find this pattern and the build_vectors are built from
19814 // constants, we translate the vselect into a shuffle_vector that we
19815 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
19816 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
19817 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
19818 if (Shuffle.getNode())
19825 // Check whether a boolean test is testing a boolean value generated by
19826 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
19829 // Simplify the following patterns:
19830 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
19831 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
19832 // to (Op EFLAGS Cond)
19834 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
19835 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
19836 // to (Op EFLAGS !Cond)
19838 // where Op could be BRCOND or CMOV.
19840 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
19841 // Quit if not CMP and SUB with its value result used.
19842 if (Cmp.getOpcode() != X86ISD::CMP &&
19843 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
19846 // Quit if not used as a boolean value.
19847 if (CC != X86::COND_E && CC != X86::COND_NE)
19850 // Check CMP operands. One of them should be 0 or 1 and the other should be
19851 // an SetCC or extended from it.
19852 SDValue Op1 = Cmp.getOperand(0);
19853 SDValue Op2 = Cmp.getOperand(1);
19856 const ConstantSDNode* C = nullptr;
19857 bool needOppositeCond = (CC == X86::COND_E);
19858 bool checkAgainstTrue = false; // Is it a comparison against 1?
19860 if ((C = dyn_cast<ConstantSDNode>(Op1)))
19862 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
19864 else // Quit if all operands are not constants.
19867 if (C->getZExtValue() == 1) {
19868 needOppositeCond = !needOppositeCond;
19869 checkAgainstTrue = true;
19870 } else if (C->getZExtValue() != 0)
19871 // Quit if the constant is neither 0 or 1.
19874 bool truncatedToBoolWithAnd = false;
19875 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
19876 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
19877 SetCC.getOpcode() == ISD::TRUNCATE ||
19878 SetCC.getOpcode() == ISD::AND) {
19879 if (SetCC.getOpcode() == ISD::AND) {
19881 ConstantSDNode *CS;
19882 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
19883 CS->getZExtValue() == 1)
19885 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
19886 CS->getZExtValue() == 1)
19890 SetCC = SetCC.getOperand(OpIdx);
19891 truncatedToBoolWithAnd = true;
19893 SetCC = SetCC.getOperand(0);
19896 switch (SetCC.getOpcode()) {
19897 case X86ISD::SETCC_CARRY:
19898 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
19899 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
19900 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
19901 // truncated to i1 using 'and'.
19902 if (checkAgainstTrue && !truncatedToBoolWithAnd)
19904 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
19905 "Invalid use of SETCC_CARRY!");
19907 case X86ISD::SETCC:
19908 // Set the condition code or opposite one if necessary.
19909 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
19910 if (needOppositeCond)
19911 CC = X86::GetOppositeBranchCondition(CC);
19912 return SetCC.getOperand(1);
19913 case X86ISD::CMOV: {
19914 // Check whether false/true value has canonical one, i.e. 0 or 1.
19915 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
19916 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
19917 // Quit if true value is not a constant.
19920 // Quit if false value is not a constant.
19922 SDValue Op = SetCC.getOperand(0);
19923 // Skip 'zext' or 'trunc' node.
19924 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
19925 Op.getOpcode() == ISD::TRUNCATE)
19926 Op = Op.getOperand(0);
19927 // A special case for rdrand/rdseed, where 0 is set if false cond is
19929 if ((Op.getOpcode() != X86ISD::RDRAND &&
19930 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
19933 // Quit if false value is not the constant 0 or 1.
19934 bool FValIsFalse = true;
19935 if (FVal && FVal->getZExtValue() != 0) {
19936 if (FVal->getZExtValue() != 1)
19938 // If FVal is 1, opposite cond is needed.
19939 needOppositeCond = !needOppositeCond;
19940 FValIsFalse = false;
19942 // Quit if TVal is not the constant opposite of FVal.
19943 if (FValIsFalse && TVal->getZExtValue() != 1)
19945 if (!FValIsFalse && TVal->getZExtValue() != 0)
19947 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
19948 if (needOppositeCond)
19949 CC = X86::GetOppositeBranchCondition(CC);
19950 return SetCC.getOperand(3);
19957 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
19958 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
19959 TargetLowering::DAGCombinerInfo &DCI,
19960 const X86Subtarget *Subtarget) {
19963 // If the flag operand isn't dead, don't touch this CMOV.
19964 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
19967 SDValue FalseOp = N->getOperand(0);
19968 SDValue TrueOp = N->getOperand(1);
19969 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
19970 SDValue Cond = N->getOperand(3);
19972 if (CC == X86::COND_E || CC == X86::COND_NE) {
19973 switch (Cond.getOpcode()) {
19977 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
19978 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
19979 return (CC == X86::COND_E) ? FalseOp : TrueOp;
19985 Flags = checkBoolTestSetCCCombine(Cond, CC);
19986 if (Flags.getNode() &&
19987 // Extra check as FCMOV only supports a subset of X86 cond.
19988 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
19989 SDValue Ops[] = { FalseOp, TrueOp,
19990 DAG.getConstant(CC, MVT::i8), Flags };
19991 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19994 // If this is a select between two integer constants, try to do some
19995 // optimizations. Note that the operands are ordered the opposite of SELECT
19997 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19998 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19999 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20000 // larger than FalseC (the false value).
20001 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20002 CC = X86::GetOppositeBranchCondition(CC);
20003 std::swap(TrueC, FalseC);
20004 std::swap(TrueOp, FalseOp);
20007 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
20008 // This is efficient for any integer data type (including i8/i16) and
20010 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20011 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20012 DAG.getConstant(CC, MVT::i8), Cond);
20014 // Zero extend the condition if needed.
20015 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20017 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20018 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20019 DAG.getConstant(ShAmt, MVT::i8));
20020 if (N->getNumValues() == 2) // Dead flag value?
20021 return DCI.CombineTo(N, Cond, SDValue());
20025 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
20026 // for any integer data type, including i8/i16.
20027 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20028 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20029 DAG.getConstant(CC, MVT::i8), Cond);
20031 // Zero extend the condition if needed.
20032 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20033 FalseC->getValueType(0), Cond);
20034 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20035 SDValue(FalseC, 0));
20037 if (N->getNumValues() == 2) // Dead flag value?
20038 return DCI.CombineTo(N, Cond, SDValue());
20042 // Optimize cases that will turn into an LEA instruction. This requires
20043 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20044 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20045 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20046 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20048 bool isFastMultiplier = false;
20050 switch ((unsigned char)Diff) {
20052 case 1: // result = add base, cond
20053 case 2: // result = lea base( , cond*2)
20054 case 3: // result = lea base(cond, cond*2)
20055 case 4: // result = lea base( , cond*4)
20056 case 5: // result = lea base(cond, cond*4)
20057 case 8: // result = lea base( , cond*8)
20058 case 9: // result = lea base(cond, cond*8)
20059 isFastMultiplier = true;
20064 if (isFastMultiplier) {
20065 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20066 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20067 DAG.getConstant(CC, MVT::i8), Cond);
20068 // Zero extend the condition if needed.
20069 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20071 // Scale the condition by the difference.
20073 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20074 DAG.getConstant(Diff, Cond.getValueType()));
20076 // Add the base if non-zero.
20077 if (FalseC->getAPIntValue() != 0)
20078 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20079 SDValue(FalseC, 0));
20080 if (N->getNumValues() == 2) // Dead flag value?
20081 return DCI.CombineTo(N, Cond, SDValue());
20088 // Handle these cases:
20089 // (select (x != c), e, c) -> select (x != c), e, x),
20090 // (select (x == c), c, e) -> select (x == c), x, e)
20091 // where the c is an integer constant, and the "select" is the combination
20092 // of CMOV and CMP.
20094 // The rationale for this change is that the conditional-move from a constant
20095 // needs two instructions, however, conditional-move from a register needs
20096 // only one instruction.
20098 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20099 // some instruction-combining opportunities. This opt needs to be
20100 // postponed as late as possible.
20102 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20103 // the DCI.xxxx conditions are provided to postpone the optimization as
20104 // late as possible.
20106 ConstantSDNode *CmpAgainst = nullptr;
20107 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20108 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20109 !isa<ConstantSDNode>(Cond.getOperand(0))) {
20111 if (CC == X86::COND_NE &&
20112 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20113 CC = X86::GetOppositeBranchCondition(CC);
20114 std::swap(TrueOp, FalseOp);
20117 if (CC == X86::COND_E &&
20118 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20119 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20120 DAG.getConstant(CC, MVT::i8), Cond };
20121 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20129 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20130 const X86Subtarget *Subtarget) {
20131 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20133 default: return SDValue();
20134 // SSE/AVX/AVX2 blend intrinsics.
20135 case Intrinsic::x86_avx2_pblendvb:
20136 case Intrinsic::x86_avx2_pblendw:
20137 case Intrinsic::x86_avx2_pblendd_128:
20138 case Intrinsic::x86_avx2_pblendd_256:
20139 // Don't try to simplify this intrinsic if we don't have AVX2.
20140 if (!Subtarget->hasAVX2())
20143 case Intrinsic::x86_avx_blend_pd_256:
20144 case Intrinsic::x86_avx_blend_ps_256:
20145 case Intrinsic::x86_avx_blendv_pd_256:
20146 case Intrinsic::x86_avx_blendv_ps_256:
20147 // Don't try to simplify this intrinsic if we don't have AVX.
20148 if (!Subtarget->hasAVX())
20151 case Intrinsic::x86_sse41_pblendw:
20152 case Intrinsic::x86_sse41_blendpd:
20153 case Intrinsic::x86_sse41_blendps:
20154 case Intrinsic::x86_sse41_blendvps:
20155 case Intrinsic::x86_sse41_blendvpd:
20156 case Intrinsic::x86_sse41_pblendvb: {
20157 SDValue Op0 = N->getOperand(1);
20158 SDValue Op1 = N->getOperand(2);
20159 SDValue Mask = N->getOperand(3);
20161 // Don't try to simplify this intrinsic if we don't have SSE4.1.
20162 if (!Subtarget->hasSSE41())
20165 // fold (blend A, A, Mask) -> A
20168 // fold (blend A, B, allZeros) -> A
20169 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20171 // fold (blend A, B, allOnes) -> B
20172 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20175 // Simplify the case where the mask is a constant i32 value.
20176 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20177 if (C->isNullValue())
20179 if (C->isAllOnesValue())
20186 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20187 case Intrinsic::x86_sse2_psrai_w:
20188 case Intrinsic::x86_sse2_psrai_d:
20189 case Intrinsic::x86_avx2_psrai_w:
20190 case Intrinsic::x86_avx2_psrai_d:
20191 case Intrinsic::x86_sse2_psra_w:
20192 case Intrinsic::x86_sse2_psra_d:
20193 case Intrinsic::x86_avx2_psra_w:
20194 case Intrinsic::x86_avx2_psra_d: {
20195 SDValue Op0 = N->getOperand(1);
20196 SDValue Op1 = N->getOperand(2);
20197 EVT VT = Op0.getValueType();
20198 assert(VT.isVector() && "Expected a vector type!");
20200 if (isa<BuildVectorSDNode>(Op1))
20201 Op1 = Op1.getOperand(0);
20203 if (!isa<ConstantSDNode>(Op1))
20206 EVT SVT = VT.getVectorElementType();
20207 unsigned SVTBits = SVT.getSizeInBits();
20209 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20210 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20211 uint64_t ShAmt = C.getZExtValue();
20213 // Don't try to convert this shift into a ISD::SRA if the shift
20214 // count is bigger than or equal to the element size.
20215 if (ShAmt >= SVTBits)
20218 // Trivial case: if the shift count is zero, then fold this
20219 // into the first operand.
20223 // Replace this packed shift intrinsic with a target independent
20225 SDValue Splat = DAG.getConstant(C, VT);
20226 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20231 /// PerformMulCombine - Optimize a single multiply with constant into two
20232 /// in order to implement it with two cheaper instructions, e.g.
20233 /// LEA + SHL, LEA + LEA.
20234 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20235 TargetLowering::DAGCombinerInfo &DCI) {
20236 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20239 EVT VT = N->getValueType(0);
20240 if (VT != MVT::i64)
20243 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20246 uint64_t MulAmt = C->getZExtValue();
20247 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20250 uint64_t MulAmt1 = 0;
20251 uint64_t MulAmt2 = 0;
20252 if ((MulAmt % 9) == 0) {
20254 MulAmt2 = MulAmt / 9;
20255 } else if ((MulAmt % 5) == 0) {
20257 MulAmt2 = MulAmt / 5;
20258 } else if ((MulAmt % 3) == 0) {
20260 MulAmt2 = MulAmt / 3;
20263 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20266 if (isPowerOf2_64(MulAmt2) &&
20267 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20268 // If second multiplifer is pow2, issue it first. We want the multiply by
20269 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20271 std::swap(MulAmt1, MulAmt2);
20274 if (isPowerOf2_64(MulAmt1))
20275 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20276 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20278 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20279 DAG.getConstant(MulAmt1, VT));
20281 if (isPowerOf2_64(MulAmt2))
20282 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20283 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20285 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20286 DAG.getConstant(MulAmt2, VT));
20288 // Do not add new nodes to DAG combiner worklist.
20289 DCI.CombineTo(N, NewMul, false);
20294 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20295 SDValue N0 = N->getOperand(0);
20296 SDValue N1 = N->getOperand(1);
20297 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20298 EVT VT = N0.getValueType();
20300 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20301 // since the result of setcc_c is all zero's or all ones.
20302 if (VT.isInteger() && !VT.isVector() &&
20303 N1C && N0.getOpcode() == ISD::AND &&
20304 N0.getOperand(1).getOpcode() == ISD::Constant) {
20305 SDValue N00 = N0.getOperand(0);
20306 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20307 ((N00.getOpcode() == ISD::ANY_EXTEND ||
20308 N00.getOpcode() == ISD::ZERO_EXTEND) &&
20309 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20310 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20311 APInt ShAmt = N1C->getAPIntValue();
20312 Mask = Mask.shl(ShAmt);
20314 return DAG.getNode(ISD::AND, SDLoc(N), VT,
20315 N00, DAG.getConstant(Mask, VT));
20319 // Hardware support for vector shifts is sparse which makes us scalarize the
20320 // vector operations in many cases. Also, on sandybridge ADD is faster than
20322 // (shl V, 1) -> add V,V
20323 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
20324 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
20325 assert(N0.getValueType().isVector() && "Invalid vector shift type");
20326 // We shift all of the values by one. In many cases we do not have
20327 // hardware support for this operation. This is better expressed as an ADD
20329 if (N1SplatC->getZExtValue() == 1)
20330 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20336 /// \brief Returns a vector of 0s if the node in input is a vector logical
20337 /// shift by a constant amount which is known to be bigger than or equal
20338 /// to the vector element size in bits.
20339 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20340 const X86Subtarget *Subtarget) {
20341 EVT VT = N->getValueType(0);
20343 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20344 (!Subtarget->hasInt256() ||
20345 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20348 SDValue Amt = N->getOperand(1);
20350 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
20351 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
20352 APInt ShiftAmt = AmtSplat->getAPIntValue();
20353 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20355 // SSE2/AVX2 logical shifts always return a vector of 0s
20356 // if the shift amount is bigger than or equal to
20357 // the element size. The constant shift amount will be
20358 // encoded as a 8-bit immediate.
20359 if (ShiftAmt.trunc(8).uge(MaxAmount))
20360 return getZeroVector(VT, Subtarget, DAG, DL);
20366 /// PerformShiftCombine - Combine shifts.
20367 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20368 TargetLowering::DAGCombinerInfo &DCI,
20369 const X86Subtarget *Subtarget) {
20370 if (N->getOpcode() == ISD::SHL) {
20371 SDValue V = PerformSHLCombine(N, DAG);
20372 if (V.getNode()) return V;
20375 if (N->getOpcode() != ISD::SRA) {
20376 // Try to fold this logical shift into a zero vector.
20377 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20378 if (V.getNode()) return V;
20384 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
20385 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20386 // and friends. Likewise for OR -> CMPNEQSS.
20387 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20388 TargetLowering::DAGCombinerInfo &DCI,
20389 const X86Subtarget *Subtarget) {
20392 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20393 // we're requiring SSE2 for both.
20394 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20395 SDValue N0 = N->getOperand(0);
20396 SDValue N1 = N->getOperand(1);
20397 SDValue CMP0 = N0->getOperand(1);
20398 SDValue CMP1 = N1->getOperand(1);
20401 // The SETCCs should both refer to the same CMP.
20402 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20405 SDValue CMP00 = CMP0->getOperand(0);
20406 SDValue CMP01 = CMP0->getOperand(1);
20407 EVT VT = CMP00.getValueType();
20409 if (VT == MVT::f32 || VT == MVT::f64) {
20410 bool ExpectingFlags = false;
20411 // Check for any users that want flags:
20412 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20413 !ExpectingFlags && UI != UE; ++UI)
20414 switch (UI->getOpcode()) {
20419 ExpectingFlags = true;
20421 case ISD::CopyToReg:
20422 case ISD::SIGN_EXTEND:
20423 case ISD::ZERO_EXTEND:
20424 case ISD::ANY_EXTEND:
20428 if (!ExpectingFlags) {
20429 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20430 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20432 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20433 X86::CondCode tmp = cc0;
20438 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
20439 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20440 // FIXME: need symbolic constants for these magic numbers.
20441 // See X86ATTInstPrinter.cpp:printSSECC().
20442 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20443 if (Subtarget->hasAVX512()) {
20444 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20445 CMP01, DAG.getConstant(x86cc, MVT::i8));
20446 if (N->getValueType(0) != MVT::i1)
20447 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20451 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20452 CMP00.getValueType(), CMP00, CMP01,
20453 DAG.getConstant(x86cc, MVT::i8));
20455 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20456 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20458 if (is64BitFP && !Subtarget->is64Bit()) {
20459 // On a 32-bit target, we cannot bitcast the 64-bit float to a
20460 // 64-bit integer, since that's not a legal type. Since
20461 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20462 // bits, but can do this little dance to extract the lowest 32 bits
20463 // and work with those going forward.
20464 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20466 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20468 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20469 Vector32, DAG.getIntPtrConstant(0));
20473 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20474 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20475 DAG.getConstant(1, IntVT));
20476 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20477 return OneBitOfTruth;
20485 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20486 /// so it can be folded inside ANDNP.
20487 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20488 EVT VT = N->getValueType(0);
20490 // Match direct AllOnes for 128 and 256-bit vectors
20491 if (ISD::isBuildVectorAllOnes(N))
20494 // Look through a bit convert.
20495 if (N->getOpcode() == ISD::BITCAST)
20496 N = N->getOperand(0).getNode();
20498 // Sometimes the operand may come from a insert_subvector building a 256-bit
20500 if (VT.is256BitVector() &&
20501 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20502 SDValue V1 = N->getOperand(0);
20503 SDValue V2 = N->getOperand(1);
20505 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20506 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20507 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20508 ISD::isBuildVectorAllOnes(V2.getNode()))
20515 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20516 // register. In most cases we actually compare or select YMM-sized registers
20517 // and mixing the two types creates horrible code. This method optimizes
20518 // some of the transition sequences.
20519 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20520 TargetLowering::DAGCombinerInfo &DCI,
20521 const X86Subtarget *Subtarget) {
20522 EVT VT = N->getValueType(0);
20523 if (!VT.is256BitVector())
20526 assert((N->getOpcode() == ISD::ANY_EXTEND ||
20527 N->getOpcode() == ISD::ZERO_EXTEND ||
20528 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20530 SDValue Narrow = N->getOperand(0);
20531 EVT NarrowVT = Narrow->getValueType(0);
20532 if (!NarrowVT.is128BitVector())
20535 if (Narrow->getOpcode() != ISD::XOR &&
20536 Narrow->getOpcode() != ISD::AND &&
20537 Narrow->getOpcode() != ISD::OR)
20540 SDValue N0 = Narrow->getOperand(0);
20541 SDValue N1 = Narrow->getOperand(1);
20544 // The Left side has to be a trunc.
20545 if (N0.getOpcode() != ISD::TRUNCATE)
20548 // The type of the truncated inputs.
20549 EVT WideVT = N0->getOperand(0)->getValueType(0);
20553 // The right side has to be a 'trunc' or a constant vector.
20554 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20555 ConstantSDNode *RHSConstSplat = nullptr;
20556 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
20557 RHSConstSplat = RHSBV->getConstantSplatNode();
20558 if (!RHSTrunc && !RHSConstSplat)
20561 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20563 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
20566 // Set N0 and N1 to hold the inputs to the new wide operation.
20567 N0 = N0->getOperand(0);
20568 if (RHSConstSplat) {
20569 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
20570 SDValue(RHSConstSplat, 0));
20571 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
20572 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
20573 } else if (RHSTrunc) {
20574 N1 = N1->getOperand(0);
20577 // Generate the wide operation.
20578 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
20579 unsigned Opcode = N->getOpcode();
20581 case ISD::ANY_EXTEND:
20583 case ISD::ZERO_EXTEND: {
20584 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
20585 APInt Mask = APInt::getAllOnesValue(InBits);
20586 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
20587 return DAG.getNode(ISD::AND, DL, VT,
20588 Op, DAG.getConstant(Mask, VT));
20590 case ISD::SIGN_EXTEND:
20591 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
20592 Op, DAG.getValueType(NarrowVT));
20594 llvm_unreachable("Unexpected opcode");
20598 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
20599 TargetLowering::DAGCombinerInfo &DCI,
20600 const X86Subtarget *Subtarget) {
20601 EVT VT = N->getValueType(0);
20602 if (DCI.isBeforeLegalizeOps())
20605 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20609 // Create BEXTR instructions
20610 // BEXTR is ((X >> imm) & (2**size-1))
20611 if (VT == MVT::i32 || VT == MVT::i64) {
20612 SDValue N0 = N->getOperand(0);
20613 SDValue N1 = N->getOperand(1);
20616 // Check for BEXTR.
20617 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
20618 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
20619 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
20620 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20621 if (MaskNode && ShiftNode) {
20622 uint64_t Mask = MaskNode->getZExtValue();
20623 uint64_t Shift = ShiftNode->getZExtValue();
20624 if (isMask_64(Mask)) {
20625 uint64_t MaskSize = CountPopulation_64(Mask);
20626 if (Shift + MaskSize <= VT.getSizeInBits())
20627 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
20628 DAG.getConstant(Shift | (MaskSize << 8), VT));
20636 // Want to form ANDNP nodes:
20637 // 1) In the hopes of then easily combining them with OR and AND nodes
20638 // to form PBLEND/PSIGN.
20639 // 2) To match ANDN packed intrinsics
20640 if (VT != MVT::v2i64 && VT != MVT::v4i64)
20643 SDValue N0 = N->getOperand(0);
20644 SDValue N1 = N->getOperand(1);
20647 // Check LHS for vnot
20648 if (N0.getOpcode() == ISD::XOR &&
20649 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
20650 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
20651 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
20653 // Check RHS for vnot
20654 if (N1.getOpcode() == ISD::XOR &&
20655 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
20656 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
20657 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
20662 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
20663 TargetLowering::DAGCombinerInfo &DCI,
20664 const X86Subtarget *Subtarget) {
20665 if (DCI.isBeforeLegalizeOps())
20668 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20672 SDValue N0 = N->getOperand(0);
20673 SDValue N1 = N->getOperand(1);
20674 EVT VT = N->getValueType(0);
20676 // look for psign/blend
20677 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
20678 if (!Subtarget->hasSSSE3() ||
20679 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
20682 // Canonicalize pandn to RHS
20683 if (N0.getOpcode() == X86ISD::ANDNP)
20685 // or (and (m, y), (pandn m, x))
20686 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
20687 SDValue Mask = N1.getOperand(0);
20688 SDValue X = N1.getOperand(1);
20690 if (N0.getOperand(0) == Mask)
20691 Y = N0.getOperand(1);
20692 if (N0.getOperand(1) == Mask)
20693 Y = N0.getOperand(0);
20695 // Check to see if the mask appeared in both the AND and ANDNP and
20699 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
20700 // Look through mask bitcast.
20701 if (Mask.getOpcode() == ISD::BITCAST)
20702 Mask = Mask.getOperand(0);
20703 if (X.getOpcode() == ISD::BITCAST)
20704 X = X.getOperand(0);
20705 if (Y.getOpcode() == ISD::BITCAST)
20706 Y = Y.getOperand(0);
20708 EVT MaskVT = Mask.getValueType();
20710 // Validate that the Mask operand is a vector sra node.
20711 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
20712 // there is no psrai.b
20713 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
20714 unsigned SraAmt = ~0;
20715 if (Mask.getOpcode() == ISD::SRA) {
20716 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
20717 if (auto *AmtConst = AmtBV->getConstantSplatNode())
20718 SraAmt = AmtConst->getZExtValue();
20719 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
20720 SDValue SraC = Mask.getOperand(1);
20721 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
20723 if ((SraAmt + 1) != EltBits)
20728 // Now we know we at least have a plendvb with the mask val. See if
20729 // we can form a psignb/w/d.
20730 // psign = x.type == y.type == mask.type && y = sub(0, x);
20731 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
20732 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
20733 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
20734 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
20735 "Unsupported VT for PSIGN");
20736 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
20737 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20739 // PBLENDVB only available on SSE 4.1
20740 if (!Subtarget->hasSSE41())
20743 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
20745 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
20746 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
20747 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
20748 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
20749 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20753 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
20756 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
20757 MachineFunction &MF = DAG.getMachineFunction();
20758 bool OptForSize = MF.getFunction()->getAttributes().
20759 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
20761 // SHLD/SHRD instructions have lower register pressure, but on some
20762 // platforms they have higher latency than the equivalent
20763 // series of shifts/or that would otherwise be generated.
20764 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
20765 // have higher latencies and we are not optimizing for size.
20766 if (!OptForSize && Subtarget->isSHLDSlow())
20769 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
20771 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
20773 if (!N0.hasOneUse() || !N1.hasOneUse())
20776 SDValue ShAmt0 = N0.getOperand(1);
20777 if (ShAmt0.getValueType() != MVT::i8)
20779 SDValue ShAmt1 = N1.getOperand(1);
20780 if (ShAmt1.getValueType() != MVT::i8)
20782 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
20783 ShAmt0 = ShAmt0.getOperand(0);
20784 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
20785 ShAmt1 = ShAmt1.getOperand(0);
20788 unsigned Opc = X86ISD::SHLD;
20789 SDValue Op0 = N0.getOperand(0);
20790 SDValue Op1 = N1.getOperand(0);
20791 if (ShAmt0.getOpcode() == ISD::SUB) {
20792 Opc = X86ISD::SHRD;
20793 std::swap(Op0, Op1);
20794 std::swap(ShAmt0, ShAmt1);
20797 unsigned Bits = VT.getSizeInBits();
20798 if (ShAmt1.getOpcode() == ISD::SUB) {
20799 SDValue Sum = ShAmt1.getOperand(0);
20800 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
20801 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
20802 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
20803 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
20804 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
20805 return DAG.getNode(Opc, DL, VT,
20807 DAG.getNode(ISD::TRUNCATE, DL,
20810 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
20811 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
20813 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
20814 return DAG.getNode(Opc, DL, VT,
20815 N0.getOperand(0), N1.getOperand(0),
20816 DAG.getNode(ISD::TRUNCATE, DL,
20823 // Generate NEG and CMOV for integer abs.
20824 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
20825 EVT VT = N->getValueType(0);
20827 // Since X86 does not have CMOV for 8-bit integer, we don't convert
20828 // 8-bit integer abs to NEG and CMOV.
20829 if (VT.isInteger() && VT.getSizeInBits() == 8)
20832 SDValue N0 = N->getOperand(0);
20833 SDValue N1 = N->getOperand(1);
20836 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
20837 // and change it to SUB and CMOV.
20838 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
20839 N0.getOpcode() == ISD::ADD &&
20840 N0.getOperand(1) == N1 &&
20841 N1.getOpcode() == ISD::SRA &&
20842 N1.getOperand(0) == N0.getOperand(0))
20843 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
20844 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
20845 // Generate SUB & CMOV.
20846 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
20847 DAG.getConstant(0, VT), N0.getOperand(0));
20849 SDValue Ops[] = { N0.getOperand(0), Neg,
20850 DAG.getConstant(X86::COND_GE, MVT::i8),
20851 SDValue(Neg.getNode(), 1) };
20852 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
20857 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
20858 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
20859 TargetLowering::DAGCombinerInfo &DCI,
20860 const X86Subtarget *Subtarget) {
20861 if (DCI.isBeforeLegalizeOps())
20864 if (Subtarget->hasCMov()) {
20865 SDValue RV = performIntegerAbsCombine(N, DAG);
20873 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
20874 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
20875 TargetLowering::DAGCombinerInfo &DCI,
20876 const X86Subtarget *Subtarget) {
20877 LoadSDNode *Ld = cast<LoadSDNode>(N);
20878 EVT RegVT = Ld->getValueType(0);
20879 EVT MemVT = Ld->getMemoryVT();
20881 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20882 unsigned RegSz = RegVT.getSizeInBits();
20884 // On Sandybridge unaligned 256bit loads are inefficient.
20885 ISD::LoadExtType Ext = Ld->getExtensionType();
20886 unsigned Alignment = Ld->getAlignment();
20887 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
20888 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
20889 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
20890 unsigned NumElems = RegVT.getVectorNumElements();
20894 SDValue Ptr = Ld->getBasePtr();
20895 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
20897 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20899 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20900 Ld->getPointerInfo(), Ld->isVolatile(),
20901 Ld->isNonTemporal(), Ld->isInvariant(),
20903 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20904 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20905 Ld->getPointerInfo(), Ld->isVolatile(),
20906 Ld->isNonTemporal(), Ld->isInvariant(),
20907 std::min(16U, Alignment));
20908 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20910 Load2.getValue(1));
20912 SDValue NewVec = DAG.getUNDEF(RegVT);
20913 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
20914 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
20915 return DCI.CombineTo(N, NewVec, TF, true);
20918 // If this is a vector EXT Load then attempt to optimize it using a
20919 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
20920 // expansion is still better than scalar code.
20921 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
20922 // emit a shuffle and a arithmetic shift.
20923 // TODO: It is possible to support ZExt by zeroing the undef values
20924 // during the shuffle phase or after the shuffle.
20925 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
20926 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
20927 assert(MemVT != RegVT && "Cannot extend to the same type");
20928 assert(MemVT.isVector() && "Must load a vector from memory");
20930 unsigned NumElems = RegVT.getVectorNumElements();
20931 unsigned MemSz = MemVT.getSizeInBits();
20932 assert(RegSz > MemSz && "Register size must be greater than the mem size");
20934 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
20937 // All sizes must be a power of two.
20938 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
20941 // Attempt to load the original value using scalar loads.
20942 // Find the largest scalar type that divides the total loaded size.
20943 MVT SclrLoadTy = MVT::i8;
20944 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20945 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20946 MVT Tp = (MVT::SimpleValueType)tp;
20947 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20952 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20953 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20955 SclrLoadTy = MVT::f64;
20957 // Calculate the number of scalar loads that we need to perform
20958 // in order to load our vector from memory.
20959 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20960 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
20963 unsigned loadRegZize = RegSz;
20964 if (Ext == ISD::SEXTLOAD && RegSz == 256)
20967 // Represent our vector as a sequence of elements which are the
20968 // largest scalar that we can load.
20969 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
20970 loadRegZize/SclrLoadTy.getSizeInBits());
20972 // Represent the data using the same element type that is stored in
20973 // memory. In practice, we ''widen'' MemVT.
20975 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20976 loadRegZize/MemVT.getScalarType().getSizeInBits());
20978 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20979 "Invalid vector type");
20981 // We can't shuffle using an illegal type.
20982 if (!TLI.isTypeLegal(WideVecVT))
20985 SmallVector<SDValue, 8> Chains;
20986 SDValue Ptr = Ld->getBasePtr();
20987 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20988 TLI.getPointerTy());
20989 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20991 for (unsigned i = 0; i < NumLoads; ++i) {
20992 // Perform a single load.
20993 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20994 Ptr, Ld->getPointerInfo(),
20995 Ld->isVolatile(), Ld->isNonTemporal(),
20996 Ld->isInvariant(), Ld->getAlignment());
20997 Chains.push_back(ScalarLoad.getValue(1));
20998 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20999 // another round of DAGCombining.
21001 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
21003 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
21004 ScalarLoad, DAG.getIntPtrConstant(i));
21006 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21009 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21011 // Bitcast the loaded value to a vector of the original element type, in
21012 // the size of the target vector type.
21013 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
21014 unsigned SizeRatio = RegSz/MemSz;
21016 if (Ext == ISD::SEXTLOAD) {
21017 // If we have SSE4.1 we can directly emit a VSEXT node.
21018 if (Subtarget->hasSSE41()) {
21019 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
21020 return DCI.CombineTo(N, Sext, TF, true);
21023 // Otherwise we'll shuffle the small elements in the high bits of the
21024 // larger type and perform an arithmetic shift. If the shift is not legal
21025 // it's better to scalarize.
21026 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
21029 // Redistribute the loaded elements into the different locations.
21030 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21031 for (unsigned i = 0; i != NumElems; ++i)
21032 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
21034 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21035 DAG.getUNDEF(WideVecVT),
21038 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
21040 // Build the arithmetic shift.
21041 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
21042 MemVT.getVectorElementType().getSizeInBits();
21043 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
21044 DAG.getConstant(Amt, RegVT));
21046 return DCI.CombineTo(N, Shuff, TF, true);
21049 // Redistribute the loaded elements into the different locations.
21050 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21051 for (unsigned i = 0; i != NumElems; ++i)
21052 ShuffleVec[i*SizeRatio] = i;
21054 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21055 DAG.getUNDEF(WideVecVT),
21058 // Bitcast to the requested type.
21059 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
21060 // Replace the original load with the new sequence
21061 // and return the new chain.
21062 return DCI.CombineTo(N, Shuff, TF, true);
21068 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21069 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21070 const X86Subtarget *Subtarget) {
21071 StoreSDNode *St = cast<StoreSDNode>(N);
21072 EVT VT = St->getValue().getValueType();
21073 EVT StVT = St->getMemoryVT();
21075 SDValue StoredVal = St->getOperand(1);
21076 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21078 // If we are saving a concatenation of two XMM registers, perform two stores.
21079 // On Sandy Bridge, 256-bit memory operations are executed by two
21080 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21081 // memory operation.
21082 unsigned Alignment = St->getAlignment();
21083 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21084 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21085 StVT == VT && !IsAligned) {
21086 unsigned NumElems = VT.getVectorNumElements();
21090 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21091 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21093 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21094 SDValue Ptr0 = St->getBasePtr();
21095 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21097 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21098 St->getPointerInfo(), St->isVolatile(),
21099 St->isNonTemporal(), Alignment);
21100 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21101 St->getPointerInfo(), St->isVolatile(),
21102 St->isNonTemporal(),
21103 std::min(16U, Alignment));
21104 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21107 // Optimize trunc store (of multiple scalars) to shuffle and store.
21108 // First, pack all of the elements in one place. Next, store to memory
21109 // in fewer chunks.
21110 if (St->isTruncatingStore() && VT.isVector()) {
21111 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21112 unsigned NumElems = VT.getVectorNumElements();
21113 assert(StVT != VT && "Cannot truncate to the same type");
21114 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21115 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21117 // From, To sizes and ElemCount must be pow of two
21118 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21119 // We are going to use the original vector elt for storing.
21120 // Accumulated smaller vector elements must be a multiple of the store size.
21121 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21123 unsigned SizeRatio = FromSz / ToSz;
21125 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21127 // Create a type on which we perform the shuffle
21128 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21129 StVT.getScalarType(), NumElems*SizeRatio);
21131 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21133 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21134 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21135 for (unsigned i = 0; i != NumElems; ++i)
21136 ShuffleVec[i] = i * SizeRatio;
21138 // Can't shuffle using an illegal type.
21139 if (!TLI.isTypeLegal(WideVecVT))
21142 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21143 DAG.getUNDEF(WideVecVT),
21145 // At this point all of the data is stored at the bottom of the
21146 // register. We now need to save it to mem.
21148 // Find the largest store unit
21149 MVT StoreType = MVT::i8;
21150 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21151 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21152 MVT Tp = (MVT::SimpleValueType)tp;
21153 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21157 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21158 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21159 (64 <= NumElems * ToSz))
21160 StoreType = MVT::f64;
21162 // Bitcast the original vector into a vector of store-size units
21163 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21164 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21165 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21166 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21167 SmallVector<SDValue, 8> Chains;
21168 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21169 TLI.getPointerTy());
21170 SDValue Ptr = St->getBasePtr();
21172 // Perform one or more big stores into memory.
21173 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21174 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21175 StoreType, ShuffWide,
21176 DAG.getIntPtrConstant(i));
21177 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21178 St->getPointerInfo(), St->isVolatile(),
21179 St->isNonTemporal(), St->getAlignment());
21180 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21181 Chains.push_back(Ch);
21184 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21187 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
21188 // the FP state in cases where an emms may be missing.
21189 // A preferable solution to the general problem is to figure out the right
21190 // places to insert EMMS. This qualifies as a quick hack.
21192 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21193 if (VT.getSizeInBits() != 64)
21196 const Function *F = DAG.getMachineFunction().getFunction();
21197 bool NoImplicitFloatOps = F->getAttributes().
21198 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21199 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21200 && Subtarget->hasSSE2();
21201 if ((VT.isVector() ||
21202 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21203 isa<LoadSDNode>(St->getValue()) &&
21204 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21205 St->getChain().hasOneUse() && !St->isVolatile()) {
21206 SDNode* LdVal = St->getValue().getNode();
21207 LoadSDNode *Ld = nullptr;
21208 int TokenFactorIndex = -1;
21209 SmallVector<SDValue, 8> Ops;
21210 SDNode* ChainVal = St->getChain().getNode();
21211 // Must be a store of a load. We currently handle two cases: the load
21212 // is a direct child, and it's under an intervening TokenFactor. It is
21213 // possible to dig deeper under nested TokenFactors.
21214 if (ChainVal == LdVal)
21215 Ld = cast<LoadSDNode>(St->getChain());
21216 else if (St->getValue().hasOneUse() &&
21217 ChainVal->getOpcode() == ISD::TokenFactor) {
21218 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21219 if (ChainVal->getOperand(i).getNode() == LdVal) {
21220 TokenFactorIndex = i;
21221 Ld = cast<LoadSDNode>(St->getValue());
21223 Ops.push_back(ChainVal->getOperand(i));
21227 if (!Ld || !ISD::isNormalLoad(Ld))
21230 // If this is not the MMX case, i.e. we are just turning i64 load/store
21231 // into f64 load/store, avoid the transformation if there are multiple
21232 // uses of the loaded value.
21233 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21238 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21239 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21241 if (Subtarget->is64Bit() || F64IsLegal) {
21242 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21243 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21244 Ld->getPointerInfo(), Ld->isVolatile(),
21245 Ld->isNonTemporal(), Ld->isInvariant(),
21246 Ld->getAlignment());
21247 SDValue NewChain = NewLd.getValue(1);
21248 if (TokenFactorIndex != -1) {
21249 Ops.push_back(NewChain);
21250 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21252 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21253 St->getPointerInfo(),
21254 St->isVolatile(), St->isNonTemporal(),
21255 St->getAlignment());
21258 // Otherwise, lower to two pairs of 32-bit loads / stores.
21259 SDValue LoAddr = Ld->getBasePtr();
21260 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21261 DAG.getConstant(4, MVT::i32));
21263 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21264 Ld->getPointerInfo(),
21265 Ld->isVolatile(), Ld->isNonTemporal(),
21266 Ld->isInvariant(), Ld->getAlignment());
21267 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21268 Ld->getPointerInfo().getWithOffset(4),
21269 Ld->isVolatile(), Ld->isNonTemporal(),
21271 MinAlign(Ld->getAlignment(), 4));
21273 SDValue NewChain = LoLd.getValue(1);
21274 if (TokenFactorIndex != -1) {
21275 Ops.push_back(LoLd);
21276 Ops.push_back(HiLd);
21277 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21280 LoAddr = St->getBasePtr();
21281 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21282 DAG.getConstant(4, MVT::i32));
21284 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21285 St->getPointerInfo(),
21286 St->isVolatile(), St->isNonTemporal(),
21287 St->getAlignment());
21288 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21289 St->getPointerInfo().getWithOffset(4),
21291 St->isNonTemporal(),
21292 MinAlign(St->getAlignment(), 4));
21293 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21298 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21299 /// and return the operands for the horizontal operation in LHS and RHS. A
21300 /// horizontal operation performs the binary operation on successive elements
21301 /// of its first operand, then on successive elements of its second operand,
21302 /// returning the resulting values in a vector. For example, if
21303 /// A = < float a0, float a1, float a2, float a3 >
21305 /// B = < float b0, float b1, float b2, float b3 >
21306 /// then the result of doing a horizontal operation on A and B is
21307 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21308 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21309 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21310 /// set to A, RHS to B, and the routine returns 'true'.
21311 /// Note that the binary operation should have the property that if one of the
21312 /// operands is UNDEF then the result is UNDEF.
21313 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21314 // Look for the following pattern: if
21315 // A = < float a0, float a1, float a2, float a3 >
21316 // B = < float b0, float b1, float b2, float b3 >
21318 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21319 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21320 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21321 // which is A horizontal-op B.
21323 // At least one of the operands should be a vector shuffle.
21324 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21325 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21328 MVT VT = LHS.getSimpleValueType();
21330 assert((VT.is128BitVector() || VT.is256BitVector()) &&
21331 "Unsupported vector type for horizontal add/sub");
21333 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21334 // operate independently on 128-bit lanes.
21335 unsigned NumElts = VT.getVectorNumElements();
21336 unsigned NumLanes = VT.getSizeInBits()/128;
21337 unsigned NumLaneElts = NumElts / NumLanes;
21338 assert((NumLaneElts % 2 == 0) &&
21339 "Vector type should have an even number of elements in each lane");
21340 unsigned HalfLaneElts = NumLaneElts/2;
21342 // View LHS in the form
21343 // LHS = VECTOR_SHUFFLE A, B, LMask
21344 // If LHS is not a shuffle then pretend it is the shuffle
21345 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21346 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21349 SmallVector<int, 16> LMask(NumElts);
21350 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21351 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21352 A = LHS.getOperand(0);
21353 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21354 B = LHS.getOperand(1);
21355 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21356 std::copy(Mask.begin(), Mask.end(), LMask.begin());
21358 if (LHS.getOpcode() != ISD::UNDEF)
21360 for (unsigned i = 0; i != NumElts; ++i)
21364 // Likewise, view RHS in the form
21365 // RHS = VECTOR_SHUFFLE C, D, RMask
21367 SmallVector<int, 16> RMask(NumElts);
21368 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21369 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21370 C = RHS.getOperand(0);
21371 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21372 D = RHS.getOperand(1);
21373 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21374 std::copy(Mask.begin(), Mask.end(), RMask.begin());
21376 if (RHS.getOpcode() != ISD::UNDEF)
21378 for (unsigned i = 0; i != NumElts; ++i)
21382 // Check that the shuffles are both shuffling the same vectors.
21383 if (!(A == C && B == D) && !(A == D && B == C))
21386 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21387 if (!A.getNode() && !B.getNode())
21390 // If A and B occur in reverse order in RHS, then "swap" them (which means
21391 // rewriting the mask).
21393 CommuteVectorShuffleMask(RMask, NumElts);
21395 // At this point LHS and RHS are equivalent to
21396 // LHS = VECTOR_SHUFFLE A, B, LMask
21397 // RHS = VECTOR_SHUFFLE A, B, RMask
21398 // Check that the masks correspond to performing a horizontal operation.
21399 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21400 for (unsigned i = 0; i != NumLaneElts; ++i) {
21401 int LIdx = LMask[i+l], RIdx = RMask[i+l];
21403 // Ignore any UNDEF components.
21404 if (LIdx < 0 || RIdx < 0 ||
21405 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21406 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21409 // Check that successive elements are being operated on. If not, this is
21410 // not a horizontal operation.
21411 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21412 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21413 if (!(LIdx == Index && RIdx == Index + 1) &&
21414 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21419 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21420 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21424 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21425 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21426 const X86Subtarget *Subtarget) {
21427 EVT VT = N->getValueType(0);
21428 SDValue LHS = N->getOperand(0);
21429 SDValue RHS = N->getOperand(1);
21431 // Try to synthesize horizontal adds from adds of shuffles.
21432 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21433 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21434 isHorizontalBinOp(LHS, RHS, true))
21435 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21439 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21440 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21441 const X86Subtarget *Subtarget) {
21442 EVT VT = N->getValueType(0);
21443 SDValue LHS = N->getOperand(0);
21444 SDValue RHS = N->getOperand(1);
21446 // Try to synthesize horizontal subs from subs of shuffles.
21447 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21448 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21449 isHorizontalBinOp(LHS, RHS, false))
21450 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21454 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21455 /// X86ISD::FXOR nodes.
21456 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21457 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21458 // F[X]OR(0.0, x) -> x
21459 // F[X]OR(x, 0.0) -> x
21460 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21461 if (C->getValueAPF().isPosZero())
21462 return N->getOperand(1);
21463 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21464 if (C->getValueAPF().isPosZero())
21465 return N->getOperand(0);
21469 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21470 /// X86ISD::FMAX nodes.
21471 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21472 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21474 // Only perform optimizations if UnsafeMath is used.
21475 if (!DAG.getTarget().Options.UnsafeFPMath)
21478 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21479 // into FMINC and FMAXC, which are Commutative operations.
21480 unsigned NewOp = 0;
21481 switch (N->getOpcode()) {
21482 default: llvm_unreachable("unknown opcode");
21483 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
21484 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
21487 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21488 N->getOperand(0), N->getOperand(1));
21491 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21492 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21493 // FAND(0.0, x) -> 0.0
21494 // FAND(x, 0.0) -> 0.0
21495 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21496 if (C->getValueAPF().isPosZero())
21497 return N->getOperand(0);
21498 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21499 if (C->getValueAPF().isPosZero())
21500 return N->getOperand(1);
21504 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21505 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21506 // FANDN(x, 0.0) -> 0.0
21507 // FANDN(0.0, x) -> x
21508 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21509 if (C->getValueAPF().isPosZero())
21510 return N->getOperand(1);
21511 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21512 if (C->getValueAPF().isPosZero())
21513 return N->getOperand(1);
21517 static SDValue PerformBTCombine(SDNode *N,
21519 TargetLowering::DAGCombinerInfo &DCI) {
21520 // BT ignores high bits in the bit index operand.
21521 SDValue Op1 = N->getOperand(1);
21522 if (Op1.hasOneUse()) {
21523 unsigned BitWidth = Op1.getValueSizeInBits();
21524 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21525 APInt KnownZero, KnownOne;
21526 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21527 !DCI.isBeforeLegalizeOps());
21528 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21529 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21530 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21531 DCI.CommitTargetLoweringOpt(TLO);
21536 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21537 SDValue Op = N->getOperand(0);
21538 if (Op.getOpcode() == ISD::BITCAST)
21539 Op = Op.getOperand(0);
21540 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21541 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21542 VT.getVectorElementType().getSizeInBits() ==
21543 OpVT.getVectorElementType().getSizeInBits()) {
21544 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21549 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21550 const X86Subtarget *Subtarget) {
21551 EVT VT = N->getValueType(0);
21552 if (!VT.isVector())
21555 SDValue N0 = N->getOperand(0);
21556 SDValue N1 = N->getOperand(1);
21557 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21560 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21561 // both SSE and AVX2 since there is no sign-extended shift right
21562 // operation on a vector with 64-bit elements.
21563 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21564 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21565 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21566 N0.getOpcode() == ISD::SIGN_EXTEND)) {
21567 SDValue N00 = N0.getOperand(0);
21569 // EXTLOAD has a better solution on AVX2,
21570 // it may be replaced with X86ISD::VSEXT node.
21571 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21572 if (!ISD::isNormalLoad(N00.getNode()))
21575 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21576 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21578 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21584 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21585 TargetLowering::DAGCombinerInfo &DCI,
21586 const X86Subtarget *Subtarget) {
21587 if (!DCI.isBeforeLegalizeOps())
21590 if (!Subtarget->hasFp256())
21593 EVT VT = N->getValueType(0);
21594 if (VT.isVector() && VT.getSizeInBits() == 256) {
21595 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21603 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21604 const X86Subtarget* Subtarget) {
21606 EVT VT = N->getValueType(0);
21608 // Let legalize expand this if it isn't a legal type yet.
21609 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21612 EVT ScalarVT = VT.getScalarType();
21613 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21614 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21617 SDValue A = N->getOperand(0);
21618 SDValue B = N->getOperand(1);
21619 SDValue C = N->getOperand(2);
21621 bool NegA = (A.getOpcode() == ISD::FNEG);
21622 bool NegB = (B.getOpcode() == ISD::FNEG);
21623 bool NegC = (C.getOpcode() == ISD::FNEG);
21625 // Negative multiplication when NegA xor NegB
21626 bool NegMul = (NegA != NegB);
21628 A = A.getOperand(0);
21630 B = B.getOperand(0);
21632 C = C.getOperand(0);
21636 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21638 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21640 return DAG.getNode(Opcode, dl, VT, A, B, C);
21643 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21644 TargetLowering::DAGCombinerInfo &DCI,
21645 const X86Subtarget *Subtarget) {
21646 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
21647 // (and (i32 x86isd::setcc_carry), 1)
21648 // This eliminates the zext. This transformation is necessary because
21649 // ISD::SETCC is always legalized to i8.
21651 SDValue N0 = N->getOperand(0);
21652 EVT VT = N->getValueType(0);
21654 if (N0.getOpcode() == ISD::AND &&
21656 N0.getOperand(0).hasOneUse()) {
21657 SDValue N00 = N0.getOperand(0);
21658 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21659 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21660 if (!C || C->getZExtValue() != 1)
21662 return DAG.getNode(ISD::AND, dl, VT,
21663 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21664 N00.getOperand(0), N00.getOperand(1)),
21665 DAG.getConstant(1, VT));
21669 if (N0.getOpcode() == ISD::TRUNCATE &&
21671 N0.getOperand(0).hasOneUse()) {
21672 SDValue N00 = N0.getOperand(0);
21673 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21674 return DAG.getNode(ISD::AND, dl, VT,
21675 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21676 N00.getOperand(0), N00.getOperand(1)),
21677 DAG.getConstant(1, VT));
21680 if (VT.is256BitVector()) {
21681 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21689 // Optimize x == -y --> x+y == 0
21690 // x != -y --> x+y != 0
21691 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21692 const X86Subtarget* Subtarget) {
21693 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21694 SDValue LHS = N->getOperand(0);
21695 SDValue RHS = N->getOperand(1);
21696 EVT VT = N->getValueType(0);
21699 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21700 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21701 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21702 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21703 LHS.getValueType(), RHS, LHS.getOperand(1));
21704 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21705 addV, DAG.getConstant(0, addV.getValueType()), CC);
21707 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
21708 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
21709 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
21710 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21711 RHS.getValueType(), LHS, RHS.getOperand(1));
21712 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21713 addV, DAG.getConstant(0, addV.getValueType()), CC);
21716 if (VT.getScalarType() == MVT::i1) {
21717 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
21718 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
21719 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
21720 if (!IsSEXT0 && !IsVZero0)
21722 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
21723 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
21724 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
21726 if (!IsSEXT1 && !IsVZero1)
21729 if (IsSEXT0 && IsVZero1) {
21730 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
21731 if (CC == ISD::SETEQ)
21732 return DAG.getNOT(DL, LHS.getOperand(0), VT);
21733 return LHS.getOperand(0);
21735 if (IsSEXT1 && IsVZero0) {
21736 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
21737 if (CC == ISD::SETEQ)
21738 return DAG.getNOT(DL, RHS.getOperand(0), VT);
21739 return RHS.getOperand(0);
21746 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
21747 const X86Subtarget *Subtarget) {
21749 MVT VT = N->getOperand(1)->getSimpleValueType(0);
21750 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
21751 "X86insertps is only defined for v4x32");
21753 SDValue Ld = N->getOperand(1);
21754 if (MayFoldLoad(Ld)) {
21755 // Extract the countS bits from the immediate so we can get the proper
21756 // address when narrowing the vector load to a specific element.
21757 // When the second source op is a memory address, interps doesn't use
21758 // countS and just gets an f32 from that address.
21759 unsigned DestIndex =
21760 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
21761 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
21765 // Create this as a scalar to vector to match the instruction pattern.
21766 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
21767 // countS bits are ignored when loading from memory on insertps, which
21768 // means we don't need to explicitly set them to 0.
21769 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
21770 LoadScalarToVector, N->getOperand(2));
21773 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
21774 // as "sbb reg,reg", since it can be extended without zext and produces
21775 // an all-ones bit which is more useful than 0/1 in some cases.
21776 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
21779 return DAG.getNode(ISD::AND, DL, VT,
21780 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21781 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
21782 DAG.getConstant(1, VT));
21783 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
21784 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
21785 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21786 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
21789 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
21790 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
21791 TargetLowering::DAGCombinerInfo &DCI,
21792 const X86Subtarget *Subtarget) {
21794 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
21795 SDValue EFLAGS = N->getOperand(1);
21797 if (CC == X86::COND_A) {
21798 // Try to convert COND_A into COND_B in an attempt to facilitate
21799 // materializing "setb reg".
21801 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
21802 // cannot take an immediate as its first operand.
21804 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
21805 EFLAGS.getValueType().isInteger() &&
21806 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
21807 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
21808 EFLAGS.getNode()->getVTList(),
21809 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
21810 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
21811 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
21815 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
21816 // a zext and produces an all-ones bit which is more useful than 0/1 in some
21818 if (CC == X86::COND_B)
21819 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
21823 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21824 if (Flags.getNode()) {
21825 SDValue Cond = DAG.getConstant(CC, MVT::i8);
21826 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
21832 // Optimize branch condition evaluation.
21834 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
21835 TargetLowering::DAGCombinerInfo &DCI,
21836 const X86Subtarget *Subtarget) {
21838 SDValue Chain = N->getOperand(0);
21839 SDValue Dest = N->getOperand(1);
21840 SDValue EFLAGS = N->getOperand(3);
21841 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
21845 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21846 if (Flags.getNode()) {
21847 SDValue Cond = DAG.getConstant(CC, MVT::i8);
21848 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
21855 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
21856 SelectionDAG &DAG) {
21857 // Take advantage of vector comparisons producing 0 or -1 in each lane to
21858 // optimize away operation when it's from a constant.
21860 // The general transformation is:
21861 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
21862 // AND(VECTOR_CMP(x,y), constant2)
21863 // constant2 = UNARYOP(constant)
21865 // Early exit if this isn't a vector operation or if the operand of the
21866 // unary operation isn't a bitwise AND.
21867 EVT VT = N->getValueType(0);
21868 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
21869 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC)
21872 // Now check that the other operand of the AND is a constant splat. We could
21873 // make the transformation for non-constant splats as well, but it's unclear
21874 // that would be a benefit as it would not eliminate any operations, just
21875 // perform one more step in scalar code before moving to the vector unit.
21876 if (BuildVectorSDNode *BV =
21877 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
21878 // Bail out if the vector isn't a constant splat.
21879 if (!BV->getConstantSplatNode())
21882 // Everything checks out. Build up the new and improved node.
21884 EVT IntVT = BV->getValueType(0);
21885 // Create a new constant of the appropriate type for the transformed
21887 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
21888 // The AND node needs bitcasts to/from an integer vector type around it.
21889 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
21890 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
21891 N->getOperand(0)->getOperand(0), MaskConst);
21892 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
21899 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
21900 const X86TargetLowering *XTLI) {
21901 // First try to optimize away the conversion entirely when it's
21902 // conditionally from a constant. Vectors only.
21903 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
21904 if (Res != SDValue())
21907 // Now move on to more general possibilities.
21908 SDValue Op0 = N->getOperand(0);
21909 EVT InVT = Op0->getValueType(0);
21911 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21912 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21914 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21915 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21916 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21919 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21920 // a 32-bit target where SSE doesn't support i64->FP operations.
21921 if (Op0.getOpcode() == ISD::LOAD) {
21922 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21923 EVT VT = Ld->getValueType(0);
21924 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21925 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21926 !XTLI->getSubtarget()->is64Bit() &&
21928 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21929 Ld->getChain(), Op0, DAG);
21930 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21937 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21938 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21939 X86TargetLowering::DAGCombinerInfo &DCI) {
21940 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21941 // the result is either zero or one (depending on the input carry bit).
21942 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21943 if (X86::isZeroNode(N->getOperand(0)) &&
21944 X86::isZeroNode(N->getOperand(1)) &&
21945 // We don't have a good way to replace an EFLAGS use, so only do this when
21947 SDValue(N, 1).use_empty()) {
21949 EVT VT = N->getValueType(0);
21950 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21951 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21952 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21953 DAG.getConstant(X86::COND_B,MVT::i8),
21955 DAG.getConstant(1, VT));
21956 return DCI.CombineTo(N, Res1, CarryOut);
21962 // fold (add Y, (sete X, 0)) -> adc 0, Y
21963 // (add Y, (setne X, 0)) -> sbb -1, Y
21964 // (sub (sete X, 0), Y) -> sbb 0, Y
21965 // (sub (setne X, 0), Y) -> adc -1, Y
21966 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
21969 // Look through ZExts.
21970 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
21971 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
21974 SDValue SetCC = Ext.getOperand(0);
21975 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
21978 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
21979 if (CC != X86::COND_E && CC != X86::COND_NE)
21982 SDValue Cmp = SetCC.getOperand(1);
21983 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
21984 !X86::isZeroNode(Cmp.getOperand(1)) ||
21985 !Cmp.getOperand(0).getValueType().isInteger())
21988 SDValue CmpOp0 = Cmp.getOperand(0);
21989 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
21990 DAG.getConstant(1, CmpOp0.getValueType()));
21992 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
21993 if (CC == X86::COND_NE)
21994 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
21995 DL, OtherVal.getValueType(), OtherVal,
21996 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
21997 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
21998 DL, OtherVal.getValueType(), OtherVal,
21999 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22002 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22003 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22004 const X86Subtarget *Subtarget) {
22005 EVT VT = N->getValueType(0);
22006 SDValue Op0 = N->getOperand(0);
22007 SDValue Op1 = N->getOperand(1);
22009 // Try to synthesize horizontal adds from adds of shuffles.
22010 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22011 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22012 isHorizontalBinOp(Op0, Op1, true))
22013 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22015 return OptimizeConditionalInDecrement(N, DAG);
22018 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22019 const X86Subtarget *Subtarget) {
22020 SDValue Op0 = N->getOperand(0);
22021 SDValue Op1 = N->getOperand(1);
22023 // X86 can't encode an immediate LHS of a sub. See if we can push the
22024 // negation into a preceding instruction.
22025 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22026 // If the RHS of the sub is a XOR with one use and a constant, invert the
22027 // immediate. Then add one to the LHS of the sub so we can turn
22028 // X-Y -> X+~Y+1, saving one register.
22029 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22030 isa<ConstantSDNode>(Op1.getOperand(1))) {
22031 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22032 EVT VT = Op0.getValueType();
22033 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22035 DAG.getConstant(~XorC, VT));
22036 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22037 DAG.getConstant(C->getAPIntValue()+1, VT));
22041 // Try to synthesize horizontal adds from adds of shuffles.
22042 EVT VT = N->getValueType(0);
22043 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22044 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22045 isHorizontalBinOp(Op0, Op1, true))
22046 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22048 return OptimizeConditionalInDecrement(N, DAG);
22051 /// performVZEXTCombine - Performs build vector combines
22052 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22053 TargetLowering::DAGCombinerInfo &DCI,
22054 const X86Subtarget *Subtarget) {
22055 // (vzext (bitcast (vzext (x)) -> (vzext x)
22056 SDValue In = N->getOperand(0);
22057 while (In.getOpcode() == ISD::BITCAST)
22058 In = In.getOperand(0);
22060 if (In.getOpcode() != X86ISD::VZEXT)
22063 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22067 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22068 DAGCombinerInfo &DCI) const {
22069 SelectionDAG &DAG = DCI.DAG;
22070 switch (N->getOpcode()) {
22072 case ISD::EXTRACT_VECTOR_ELT:
22073 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22075 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22076 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22077 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
22078 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
22079 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
22080 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
22083 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
22084 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
22085 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
22086 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
22087 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
22088 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
22089 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
22090 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
22091 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
22093 case X86ISD::FOR: return PerformFORCombine(N, DAG);
22095 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
22096 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
22097 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
22098 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
22099 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
22100 case ISD::ANY_EXTEND:
22101 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
22102 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
22103 case ISD::SIGN_EXTEND_INREG:
22104 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22105 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22106 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
22107 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22108 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22109 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
22110 case X86ISD::SHUFP: // Handle all target specific shuffles
22111 case X86ISD::PALIGNR:
22112 case X86ISD::UNPCKH:
22113 case X86ISD::UNPCKL:
22114 case X86ISD::MOVHLPS:
22115 case X86ISD::MOVLHPS:
22116 case X86ISD::PSHUFD:
22117 case X86ISD::PSHUFHW:
22118 case X86ISD::PSHUFLW:
22119 case X86ISD::MOVSS:
22120 case X86ISD::MOVSD:
22121 case X86ISD::VPERMILP:
22122 case X86ISD::VPERM2X128:
22123 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22124 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
22125 case ISD::INTRINSIC_WO_CHAIN:
22126 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22127 case X86ISD::INSERTPS:
22128 return PerformINSERTPSCombine(N, DAG, Subtarget);
22129 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22135 /// isTypeDesirableForOp - Return true if the target has native support for
22136 /// the specified value type and it is 'desirable' to use the type for the
22137 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22138 /// instruction encodings are longer and some i16 instructions are slow.
22139 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22140 if (!isTypeLegal(VT))
22142 if (VT != MVT::i16)
22149 case ISD::SIGN_EXTEND:
22150 case ISD::ZERO_EXTEND:
22151 case ISD::ANY_EXTEND:
22164 /// IsDesirableToPromoteOp - This method query the target whether it is
22165 /// beneficial for dag combiner to promote the specified node. If true, it
22166 /// should return the desired promotion type by reference.
22167 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22168 EVT VT = Op.getValueType();
22169 if (VT != MVT::i16)
22172 bool Promote = false;
22173 bool Commute = false;
22174 switch (Op.getOpcode()) {
22177 LoadSDNode *LD = cast<LoadSDNode>(Op);
22178 // If the non-extending load has a single use and it's not live out, then it
22179 // might be folded.
22180 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22181 Op.hasOneUse()*/) {
22182 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22183 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22184 // The only case where we'd want to promote LOAD (rather then it being
22185 // promoted as an operand is when it's only use is liveout.
22186 if (UI->getOpcode() != ISD::CopyToReg)
22193 case ISD::SIGN_EXTEND:
22194 case ISD::ZERO_EXTEND:
22195 case ISD::ANY_EXTEND:
22200 SDValue N0 = Op.getOperand(0);
22201 // Look out for (store (shl (load), x)).
22202 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22215 SDValue N0 = Op.getOperand(0);
22216 SDValue N1 = Op.getOperand(1);
22217 if (!Commute && MayFoldLoad(N1))
22219 // Avoid disabling potential load folding opportunities.
22220 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22222 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22232 //===----------------------------------------------------------------------===//
22233 // X86 Inline Assembly Support
22234 //===----------------------------------------------------------------------===//
22237 // Helper to match a string separated by whitespace.
22238 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22239 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22241 for (unsigned i = 0, e = args.size(); i != e; ++i) {
22242 StringRef piece(*args[i]);
22243 if (!s.startswith(piece)) // Check if the piece matches.
22246 s = s.substr(piece.size());
22247 StringRef::size_type pos = s.find_first_not_of(" \t");
22248 if (pos == 0) // We matched a prefix.
22256 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22259 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22261 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22262 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22263 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22264 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22266 if (AsmPieces.size() == 3)
22268 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22275 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22276 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22278 std::string AsmStr = IA->getAsmString();
22280 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22281 if (!Ty || Ty->getBitWidth() % 16 != 0)
22284 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22285 SmallVector<StringRef, 4> AsmPieces;
22286 SplitString(AsmStr, AsmPieces, ";\n");
22288 switch (AsmPieces.size()) {
22289 default: return false;
22291 // FIXME: this should verify that we are targeting a 486 or better. If not,
22292 // we will turn this bswap into something that will be lowered to logical
22293 // ops instead of emitting the bswap asm. For now, we don't support 486 or
22294 // lower so don't worry about this.
22296 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22297 matchAsm(AsmPieces[0], "bswapl", "$0") ||
22298 matchAsm(AsmPieces[0], "bswapq", "$0") ||
22299 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22300 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22301 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22302 // No need to check constraints, nothing other than the equivalent of
22303 // "=r,0" would be valid here.
22304 return IntrinsicLowering::LowerToByteSwap(CI);
22307 // rorw $$8, ${0:w} --> llvm.bswap.i16
22308 if (CI->getType()->isIntegerTy(16) &&
22309 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22310 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22311 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22313 const std::string &ConstraintsStr = IA->getConstraintString();
22314 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22315 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22316 if (clobbersFlagRegisters(AsmPieces))
22317 return IntrinsicLowering::LowerToByteSwap(CI);
22321 if (CI->getType()->isIntegerTy(32) &&
22322 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22323 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22324 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22325 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22327 const std::string &ConstraintsStr = IA->getConstraintString();
22328 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22329 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22330 if (clobbersFlagRegisters(AsmPieces))
22331 return IntrinsicLowering::LowerToByteSwap(CI);
22334 if (CI->getType()->isIntegerTy(64)) {
22335 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22336 if (Constraints.size() >= 2 &&
22337 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22338 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22339 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
22340 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22341 matchAsm(AsmPieces[1], "bswap", "%edx") &&
22342 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22343 return IntrinsicLowering::LowerToByteSwap(CI);
22351 /// getConstraintType - Given a constraint letter, return the type of
22352 /// constraint it is for this target.
22353 X86TargetLowering::ConstraintType
22354 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22355 if (Constraint.size() == 1) {
22356 switch (Constraint[0]) {
22367 return C_RegisterClass;
22391 return TargetLowering::getConstraintType(Constraint);
22394 /// Examine constraint type and operand type and determine a weight value.
22395 /// This object must already have been set up with the operand type
22396 /// and the current alternative constraint selected.
22397 TargetLowering::ConstraintWeight
22398 X86TargetLowering::getSingleConstraintMatchWeight(
22399 AsmOperandInfo &info, const char *constraint) const {
22400 ConstraintWeight weight = CW_Invalid;
22401 Value *CallOperandVal = info.CallOperandVal;
22402 // If we don't have a value, we can't do a match,
22403 // but allow it at the lowest weight.
22404 if (!CallOperandVal)
22406 Type *type = CallOperandVal->getType();
22407 // Look at the constraint type.
22408 switch (*constraint) {
22410 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22421 if (CallOperandVal->getType()->isIntegerTy())
22422 weight = CW_SpecificReg;
22427 if (type->isFloatingPointTy())
22428 weight = CW_SpecificReg;
22431 if (type->isX86_MMXTy() && Subtarget->hasMMX())
22432 weight = CW_SpecificReg;
22436 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22437 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22438 weight = CW_Register;
22441 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22442 if (C->getZExtValue() <= 31)
22443 weight = CW_Constant;
22447 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22448 if (C->getZExtValue() <= 63)
22449 weight = CW_Constant;
22453 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22454 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22455 weight = CW_Constant;
22459 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22460 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22461 weight = CW_Constant;
22465 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22466 if (C->getZExtValue() <= 3)
22467 weight = CW_Constant;
22471 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22472 if (C->getZExtValue() <= 0xff)
22473 weight = CW_Constant;
22478 if (dyn_cast<ConstantFP>(CallOperandVal)) {
22479 weight = CW_Constant;
22483 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22484 if ((C->getSExtValue() >= -0x80000000LL) &&
22485 (C->getSExtValue() <= 0x7fffffffLL))
22486 weight = CW_Constant;
22490 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22491 if (C->getZExtValue() <= 0xffffffff)
22492 weight = CW_Constant;
22499 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22500 /// with another that has more specific requirements based on the type of the
22501 /// corresponding operand.
22502 const char *X86TargetLowering::
22503 LowerXConstraint(EVT ConstraintVT) const {
22504 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22505 // 'f' like normal targets.
22506 if (ConstraintVT.isFloatingPoint()) {
22507 if (Subtarget->hasSSE2())
22509 if (Subtarget->hasSSE1())
22513 return TargetLowering::LowerXConstraint(ConstraintVT);
22516 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22517 /// vector. If it is invalid, don't add anything to Ops.
22518 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22519 std::string &Constraint,
22520 std::vector<SDValue>&Ops,
22521 SelectionDAG &DAG) const {
22524 // Only support length 1 constraints for now.
22525 if (Constraint.length() > 1) return;
22527 char ConstraintLetter = Constraint[0];
22528 switch (ConstraintLetter) {
22531 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22532 if (C->getZExtValue() <= 31) {
22533 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22539 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22540 if (C->getZExtValue() <= 63) {
22541 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22547 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22548 if (isInt<8>(C->getSExtValue())) {
22549 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22555 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22556 if (C->getZExtValue() <= 255) {
22557 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22563 // 32-bit signed value
22564 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22565 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22566 C->getSExtValue())) {
22567 // Widen to 64 bits here to get it sign extended.
22568 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22571 // FIXME gcc accepts some relocatable values here too, but only in certain
22572 // memory models; it's complicated.
22577 // 32-bit unsigned value
22578 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22579 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22580 C->getZExtValue())) {
22581 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22585 // FIXME gcc accepts some relocatable values here too, but only in certain
22586 // memory models; it's complicated.
22590 // Literal immediates are always ok.
22591 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22592 // Widen to 64 bits here to get it sign extended.
22593 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22597 // In any sort of PIC mode addresses need to be computed at runtime by
22598 // adding in a register or some sort of table lookup. These can't
22599 // be used as immediates.
22600 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22603 // If we are in non-pic codegen mode, we allow the address of a global (with
22604 // an optional displacement) to be used with 'i'.
22605 GlobalAddressSDNode *GA = nullptr;
22606 int64_t Offset = 0;
22608 // Match either (GA), (GA+C), (GA+C1+C2), etc.
22610 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22611 Offset += GA->getOffset();
22613 } else if (Op.getOpcode() == ISD::ADD) {
22614 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22615 Offset += C->getZExtValue();
22616 Op = Op.getOperand(0);
22619 } else if (Op.getOpcode() == ISD::SUB) {
22620 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22621 Offset += -C->getZExtValue();
22622 Op = Op.getOperand(0);
22627 // Otherwise, this isn't something we can handle, reject it.
22631 const GlobalValue *GV = GA->getGlobal();
22632 // If we require an extra load to get this address, as in PIC mode, we
22633 // can't accept it.
22634 if (isGlobalStubReference(
22635 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22638 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22639 GA->getValueType(0), Offset);
22644 if (Result.getNode()) {
22645 Ops.push_back(Result);
22648 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22651 std::pair<unsigned, const TargetRegisterClass*>
22652 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22654 // First, see if this is a constraint that directly corresponds to an LLVM
22656 if (Constraint.size() == 1) {
22657 // GCC Constraint Letters
22658 switch (Constraint[0]) {
22660 // TODO: Slight differences here in allocation order and leaving
22661 // RIP in the class. Do they matter any more here than they do
22662 // in the normal allocation?
22663 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22664 if (Subtarget->is64Bit()) {
22665 if (VT == MVT::i32 || VT == MVT::f32)
22666 return std::make_pair(0U, &X86::GR32RegClass);
22667 if (VT == MVT::i16)
22668 return std::make_pair(0U, &X86::GR16RegClass);
22669 if (VT == MVT::i8 || VT == MVT::i1)
22670 return std::make_pair(0U, &X86::GR8RegClass);
22671 if (VT == MVT::i64 || VT == MVT::f64)
22672 return std::make_pair(0U, &X86::GR64RegClass);
22675 // 32-bit fallthrough
22676 case 'Q': // Q_REGS
22677 if (VT == MVT::i32 || VT == MVT::f32)
22678 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22679 if (VT == MVT::i16)
22680 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22681 if (VT == MVT::i8 || VT == MVT::i1)
22682 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22683 if (VT == MVT::i64)
22684 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22686 case 'r': // GENERAL_REGS
22687 case 'l': // INDEX_REGS
22688 if (VT == MVT::i8 || VT == MVT::i1)
22689 return std::make_pair(0U, &X86::GR8RegClass);
22690 if (VT == MVT::i16)
22691 return std::make_pair(0U, &X86::GR16RegClass);
22692 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22693 return std::make_pair(0U, &X86::GR32RegClass);
22694 return std::make_pair(0U, &X86::GR64RegClass);
22695 case 'R': // LEGACY_REGS
22696 if (VT == MVT::i8 || VT == MVT::i1)
22697 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22698 if (VT == MVT::i16)
22699 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22700 if (VT == MVT::i32 || !Subtarget->is64Bit())
22701 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
22702 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
22703 case 'f': // FP Stack registers.
22704 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
22705 // value to the correct fpstack register class.
22706 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
22707 return std::make_pair(0U, &X86::RFP32RegClass);
22708 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
22709 return std::make_pair(0U, &X86::RFP64RegClass);
22710 return std::make_pair(0U, &X86::RFP80RegClass);
22711 case 'y': // MMX_REGS if MMX allowed.
22712 if (!Subtarget->hasMMX()) break;
22713 return std::make_pair(0U, &X86::VR64RegClass);
22714 case 'Y': // SSE_REGS if SSE2 allowed
22715 if (!Subtarget->hasSSE2()) break;
22717 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
22718 if (!Subtarget->hasSSE1()) break;
22720 switch (VT.SimpleTy) {
22722 // Scalar SSE types.
22725 return std::make_pair(0U, &X86::FR32RegClass);
22728 return std::make_pair(0U, &X86::FR64RegClass);
22736 return std::make_pair(0U, &X86::VR128RegClass);
22744 return std::make_pair(0U, &X86::VR256RegClass);
22749 return std::make_pair(0U, &X86::VR512RegClass);
22755 // Use the default implementation in TargetLowering to convert the register
22756 // constraint into a member of a register class.
22757 std::pair<unsigned, const TargetRegisterClass*> Res;
22758 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
22760 // Not found as a standard register?
22762 // Map st(0) -> st(7) -> ST0
22763 if (Constraint.size() == 7 && Constraint[0] == '{' &&
22764 tolower(Constraint[1]) == 's' &&
22765 tolower(Constraint[2]) == 't' &&
22766 Constraint[3] == '(' &&
22767 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
22768 Constraint[5] == ')' &&
22769 Constraint[6] == '}') {
22771 Res.first = X86::ST0+Constraint[4]-'0';
22772 Res.second = &X86::RFP80RegClass;
22776 // GCC allows "st(0)" to be called just plain "st".
22777 if (StringRef("{st}").equals_lower(Constraint)) {
22778 Res.first = X86::ST0;
22779 Res.second = &X86::RFP80RegClass;
22784 if (StringRef("{flags}").equals_lower(Constraint)) {
22785 Res.first = X86::EFLAGS;
22786 Res.second = &X86::CCRRegClass;
22790 // 'A' means EAX + EDX.
22791 if (Constraint == "A") {
22792 Res.first = X86::EAX;
22793 Res.second = &X86::GR32_ADRegClass;
22799 // Otherwise, check to see if this is a register class of the wrong value
22800 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
22801 // turn into {ax},{dx}.
22802 if (Res.second->hasType(VT))
22803 return Res; // Correct type already, nothing to do.
22805 // All of the single-register GCC register classes map their values onto
22806 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
22807 // really want an 8-bit or 32-bit register, map to the appropriate register
22808 // class and return the appropriate register.
22809 if (Res.second == &X86::GR16RegClass) {
22810 if (VT == MVT::i8 || VT == MVT::i1) {
22811 unsigned DestReg = 0;
22812 switch (Res.first) {
22814 case X86::AX: DestReg = X86::AL; break;
22815 case X86::DX: DestReg = X86::DL; break;
22816 case X86::CX: DestReg = X86::CL; break;
22817 case X86::BX: DestReg = X86::BL; break;
22820 Res.first = DestReg;
22821 Res.second = &X86::GR8RegClass;
22823 } else if (VT == MVT::i32 || VT == MVT::f32) {
22824 unsigned DestReg = 0;
22825 switch (Res.first) {
22827 case X86::AX: DestReg = X86::EAX; break;
22828 case X86::DX: DestReg = X86::EDX; break;
22829 case X86::CX: DestReg = X86::ECX; break;
22830 case X86::BX: DestReg = X86::EBX; break;
22831 case X86::SI: DestReg = X86::ESI; break;
22832 case X86::DI: DestReg = X86::EDI; break;
22833 case X86::BP: DestReg = X86::EBP; break;
22834 case X86::SP: DestReg = X86::ESP; break;
22837 Res.first = DestReg;
22838 Res.second = &X86::GR32RegClass;
22840 } else if (VT == MVT::i64 || VT == MVT::f64) {
22841 unsigned DestReg = 0;
22842 switch (Res.first) {
22844 case X86::AX: DestReg = X86::RAX; break;
22845 case X86::DX: DestReg = X86::RDX; break;
22846 case X86::CX: DestReg = X86::RCX; break;
22847 case X86::BX: DestReg = X86::RBX; break;
22848 case X86::SI: DestReg = X86::RSI; break;
22849 case X86::DI: DestReg = X86::RDI; break;
22850 case X86::BP: DestReg = X86::RBP; break;
22851 case X86::SP: DestReg = X86::RSP; break;
22854 Res.first = DestReg;
22855 Res.second = &X86::GR64RegClass;
22858 } else if (Res.second == &X86::FR32RegClass ||
22859 Res.second == &X86::FR64RegClass ||
22860 Res.second == &X86::VR128RegClass ||
22861 Res.second == &X86::VR256RegClass ||
22862 Res.second == &X86::FR32XRegClass ||
22863 Res.second == &X86::FR64XRegClass ||
22864 Res.second == &X86::VR128XRegClass ||
22865 Res.second == &X86::VR256XRegClass ||
22866 Res.second == &X86::VR512RegClass) {
22867 // Handle references to XMM physical registers that got mapped into the
22868 // wrong class. This can happen with constraints like {xmm0} where the
22869 // target independent register mapper will just pick the first match it can
22870 // find, ignoring the required type.
22872 if (VT == MVT::f32 || VT == MVT::i32)
22873 Res.second = &X86::FR32RegClass;
22874 else if (VT == MVT::f64 || VT == MVT::i64)
22875 Res.second = &X86::FR64RegClass;
22876 else if (X86::VR128RegClass.hasType(VT))
22877 Res.second = &X86::VR128RegClass;
22878 else if (X86::VR256RegClass.hasType(VT))
22879 Res.second = &X86::VR256RegClass;
22880 else if (X86::VR512RegClass.hasType(VT))
22881 Res.second = &X86::VR512RegClass;
22887 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
22889 // Scaling factors are not free at all.
22890 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
22891 // will take 2 allocations in the out of order engine instead of 1
22892 // for plain addressing mode, i.e. inst (reg1).
22894 // vaddps (%rsi,%drx), %ymm0, %ymm1
22895 // Requires two allocations (one for the load, one for the computation)
22897 // vaddps (%rsi), %ymm0, %ymm1
22898 // Requires just 1 allocation, i.e., freeing allocations for other operations
22899 // and having less micro operations to execute.
22901 // For some X86 architectures, this is even worse because for instance for
22902 // stores, the complex addressing mode forces the instruction to use the
22903 // "load" ports instead of the dedicated "store" port.
22904 // E.g., on Haswell:
22905 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
22906 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
22907 if (isLegalAddressingMode(AM, Ty))
22908 // Scale represents reg2 * scale, thus account for 1
22909 // as soon as we use a second register.
22910 return AM.Scale != 0;
22914 bool X86TargetLowering::isTargetFTOL() const {
22915 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();