1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "x86-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62 "x86-experimental-vector-widening-legalization", cl::init(false),
63 cl::desc("Enable an experimental vector type legalization through widening "
64 "rather than promotion."),
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68 "x86-experimental-vector-shuffle-lowering", cl::init(false),
69 cl::desc("Enable an experimental vector shuffle lowering code path."),
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77 SelectionDAG &DAG, SDLoc dl,
78 unsigned vectorWidth) {
79 assert((vectorWidth == 128 || vectorWidth == 256) &&
80 "Unsupported vector width");
81 EVT VT = Vec.getValueType();
82 EVT ElVT = VT.getVectorElementType();
83 unsigned Factor = VT.getSizeInBits()/vectorWidth;
84 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85 VT.getVectorNumElements()/Factor);
87 // Extract from UNDEF is UNDEF.
88 if (Vec.getOpcode() == ISD::UNDEF)
89 return DAG.getUNDEF(ResultVT);
91 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
92 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
94 // This is the index of the first element of the vectorWidth-bit chunk
96 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
99 // If the input is a buildvector just emit a smaller one.
100 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
105 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119 SelectionDAG &DAG, SDLoc dl) {
120 assert((Vec.getValueType().is256BitVector() ||
121 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127 SelectionDAG &DAG, SDLoc dl) {
128 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133 unsigned IdxVal, SelectionDAG &DAG,
134 SDLoc dl, unsigned vectorWidth) {
135 assert((vectorWidth == 128 || vectorWidth == 256) &&
136 "Unsupported vector width");
137 // Inserting UNDEF is Result
138 if (Vec.getOpcode() == ISD::UNDEF)
140 EVT VT = Vec.getValueType();
141 EVT ElVT = VT.getVectorElementType();
142 EVT ResultVT = Result.getValueType();
144 // Insert the relevant vectorWidth bits.
145 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
147 // This is the index of the first element of the vectorWidth-bit chunk
149 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
152 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
156 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference. Idx is an index in the 128 bits
160 /// we want. It need not be aligned to a 128-bit bounday. That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163 unsigned IdxVal, SelectionDAG &DAG,
165 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170 unsigned IdxVal, SelectionDAG &DAG,
172 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181 unsigned NumElems, SelectionDAG &DAG,
183 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188 unsigned NumElems, SelectionDAG &DAG,
190 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195 if (TT.isOSBinFormatMachO()) {
196 if (TT.getArch() == Triple::x86_64)
197 return new X86_64MachoTargetObjectFile();
198 return new TargetLoweringObjectFileMachO();
202 return new X86LinuxTargetObjectFile();
203 if (TT.isOSBinFormatELF())
204 return new TargetLoweringObjectFileELF();
205 if (TT.isKnownWindowsMSVCEnvironment())
206 return new X86WindowsTargetObjectFile();
207 if (TT.isOSBinFormatCOFF())
208 return new TargetLoweringObjectFileCOFF();
209 llvm_unreachable("unknown subtarget type");
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216 Subtarget = &TM.getSubtarget<X86Subtarget>();
217 X86ScalarSSEf64 = Subtarget->hasSSE2();
218 X86ScalarSSEf32 = Subtarget->hasSSE1();
219 TD = getDataLayout();
221 resetOperationActions();
224 void X86TargetLowering::resetOperationActions() {
225 const TargetMachine &TM = getTargetMachine();
226 static bool FirstTimeThrough = true;
228 // If none of the target options have changed, then we don't need to reset the
229 // operation actions.
230 if (!FirstTimeThrough && TO == TM.Options) return;
232 if (!FirstTimeThrough) {
233 // Reinitialize the actions.
235 FirstTimeThrough = false;
240 // Set up the TargetLowering object.
241 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
243 // X86 is weird, it always uses i8 for shift amounts and setcc results.
244 setBooleanContents(ZeroOrOneBooleanContent);
245 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
248 // For 64-bit since we have so many registers use the ILP scheduler, for
249 // 32-bit code use the register pressure specific scheduling.
250 // For Atom, always use ILP scheduling.
251 if (Subtarget->isAtom())
252 setSchedulingPreference(Sched::ILP);
253 else if (Subtarget->is64Bit())
254 setSchedulingPreference(Sched::ILP);
256 setSchedulingPreference(Sched::RegPressure);
257 const X86RegisterInfo *RegInfo =
258 TM.getSubtarget<X86Subtarget>().getRegisterInfo();
259 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
261 // Bypass expensive divides on Atom when compiling with O2
262 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263 addBypassSlowDiv(32, 8);
264 if (Subtarget->is64Bit())
265 addBypassSlowDiv(64, 16);
268 if (Subtarget->isTargetKnownWindowsMSVC()) {
269 // Setup Windows compiler runtime calls.
270 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272 setLibcallName(RTLIB::SREM_I64, "_allrem");
273 setLibcallName(RTLIB::UREM_I64, "_aullrem");
274 setLibcallName(RTLIB::MUL_I64, "_allmul");
275 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
281 // The _ftol2 runtime function has an unusual calling conv, which
282 // is modeled by a special pseudo-instruction.
283 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
289 if (Subtarget->isTargetDarwin()) {
290 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291 setUseUnderscoreSetJmp(false);
292 setUseUnderscoreLongJmp(false);
293 } else if (Subtarget->isTargetWindowsGNU()) {
294 // MS runtime is weird: it exports _setjmp, but longjmp!
295 setUseUnderscoreSetJmp(true);
296 setUseUnderscoreLongJmp(false);
298 setUseUnderscoreSetJmp(true);
299 setUseUnderscoreLongJmp(true);
302 // Set up the register classes.
303 addRegisterClass(MVT::i8, &X86::GR8RegClass);
304 addRegisterClass(MVT::i16, &X86::GR16RegClass);
305 addRegisterClass(MVT::i32, &X86::GR32RegClass);
306 if (Subtarget->is64Bit())
307 addRegisterClass(MVT::i64, &X86::GR64RegClass);
309 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
311 // We don't accept any truncstore of integer registers.
312 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
319 // SETOEQ and SETUNE require checking two conditions.
320 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
327 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
329 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
330 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
331 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
333 if (Subtarget->is64Bit()) {
334 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
335 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
336 } else if (!TM.Options.UseSoftFloat) {
337 // We have an algorithm for SSE2->double, and we turn this into a
338 // 64-bit FILD followed by conditional FADD for other targets.
339 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
340 // We have an algorithm for SSE2, and we turn this into a 64-bit
341 // FILD for other targets.
342 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
345 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
347 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
350 if (!TM.Options.UseSoftFloat) {
351 // SSE has no i16 to fp conversion, only i32
352 if (X86ScalarSSEf32) {
353 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
354 // f32 and f64 cases are Legal, f80 case is not
355 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
357 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
358 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
361 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
362 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
365 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
366 // are Legal, f80 is custom lowered.
367 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
368 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
370 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
372 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
373 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
375 if (X86ScalarSSEf32) {
376 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
377 // f32 and f64 cases are Legal, f80 case is not
378 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
380 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
381 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
384 // Handle FP_TO_UINT by promoting the destination to a larger signed
386 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
387 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
388 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
390 if (Subtarget->is64Bit()) {
391 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
392 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
393 } else if (!TM.Options.UseSoftFloat) {
394 // Since AVX is a superset of SSE3, only check for SSE here.
395 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396 // Expand FP_TO_UINT into a select.
397 // FIXME: We would like to use a Custom expander here eventually to do
398 // the optimal thing for SSE vs. the default expansion in the legalizer.
399 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
401 // With SSE3 we can use fisttpll to convert to a signed i64; without
402 // SSE, we're stuck with a fistpll.
403 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
406 if (isTargetFTOL()) {
407 // Use the _ftol2 runtime function, which has a pseudo-instruction
408 // to handle its weird calling convention.
409 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
412 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413 if (!X86ScalarSSEf64) {
414 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
415 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
416 if (Subtarget->is64Bit()) {
417 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
418 // Without SSE, i64->f64 goes through memory.
419 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
423 // Scalar integer divide and remainder are lowered to use operations that
424 // produce two results, to match the available instructions. This exposes
425 // the two-result form to trivial CSE, which is able to combine x/y and x%y
426 // into a single instruction.
428 // Scalar integer multiply-high is also lowered to use two-result
429 // operations, to match the available instructions. However, plain multiply
430 // (low) operations are left as Legal, as there are single-result
431 // instructions for this in x86. Using the two-result multiply instructions
432 // when both high and low results are needed must be arranged by dagcombine.
433 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
435 setOperationAction(ISD::MULHS, VT, Expand);
436 setOperationAction(ISD::MULHU, VT, Expand);
437 setOperationAction(ISD::SDIV, VT, Expand);
438 setOperationAction(ISD::UDIV, VT, Expand);
439 setOperationAction(ISD::SREM, VT, Expand);
440 setOperationAction(ISD::UREM, VT, Expand);
442 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443 setOperationAction(ISD::ADDC, VT, Custom);
444 setOperationAction(ISD::ADDE, VT, Custom);
445 setOperationAction(ISD::SUBC, VT, Custom);
446 setOperationAction(ISD::SUBE, VT, Custom);
449 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
450 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
451 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
452 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
453 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
454 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
455 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
456 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
457 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
458 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
459 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
460 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
461 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
462 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
463 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
464 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
468 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
469 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
470 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
471 setOperationAction(ISD::FREM , MVT::f32 , Expand);
472 setOperationAction(ISD::FREM , MVT::f64 , Expand);
473 setOperationAction(ISD::FREM , MVT::f80 , Expand);
474 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
476 // Promote the i8 variants and force them on up to i32 which has a shorter
478 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
481 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
482 if (Subtarget->hasBMI()) {
483 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
484 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
485 if (Subtarget->is64Bit())
486 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
488 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
489 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
490 if (Subtarget->is64Bit())
491 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
494 if (Subtarget->hasLZCNT()) {
495 // When promoting the i8 variants, force them to i32 for a shorter
497 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
498 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
499 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
500 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
501 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
502 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
503 if (Subtarget->is64Bit())
504 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
506 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
507 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
508 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
509 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
510 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
511 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
512 if (Subtarget->is64Bit()) {
513 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
514 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
518 // Special handling for half-precision floating point conversions.
519 // If we don't have F16C support, then lower half float conversions
520 // into library calls.
521 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
526 // There's never any support for operations beyond MVT::f32.
527 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
532 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
537 if (Subtarget->hasPOPCNT()) {
538 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
540 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
541 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
542 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
543 if (Subtarget->is64Bit())
544 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
547 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
549 if (!Subtarget->hasMOVBE())
550 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
552 // These should be promoted to a larger select which is supported.
553 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
554 // X86 wants to expand cmov itself.
555 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
556 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
557 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
558 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
559 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
560 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
561 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
562 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
563 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
564 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
565 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
566 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
567 if (Subtarget->is64Bit()) {
568 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
569 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
571 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
572 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574 // support continuation, user-level threading, and etc.. As a result, no
575 // other SjLj exception interfaces are implemented and please don't build
576 // your own exception handling based on them.
577 // LLVM/Clang supports zero-cost DWARF exception handling.
578 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
582 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
583 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
584 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
585 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
586 if (Subtarget->is64Bit())
587 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
589 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
590 if (Subtarget->is64Bit()) {
591 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
592 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
593 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
594 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
595 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
597 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
599 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
600 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
601 if (Subtarget->is64Bit()) {
602 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
603 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
604 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
607 if (Subtarget->hasSSE1())
608 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
610 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
612 // Expand certain atomics
613 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
615 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
620 if (Subtarget->hasCmpxchg16b()) {
621 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
624 // FIXME - use subtarget debug flags
625 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
630 if (Subtarget->is64Bit()) {
631 setExceptionPointerRegister(X86::RAX);
632 setExceptionSelectorRegister(X86::RDX);
634 setExceptionPointerRegister(X86::EAX);
635 setExceptionSelectorRegister(X86::EDX);
637 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
640 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
643 setOperationAction(ISD::TRAP, MVT::Other, Legal);
644 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
646 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647 setOperationAction(ISD::VASTART , MVT::Other, Custom);
648 setOperationAction(ISD::VAEND , MVT::Other, Expand);
649 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650 // TargetInfo::X86_64ABIBuiltinVaList
651 setOperationAction(ISD::VAARG , MVT::Other, Custom);
652 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
654 // TargetInfo::CharPtrBuiltinVaList
655 setOperationAction(ISD::VAARG , MVT::Other, Expand);
656 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
659 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
660 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
662 setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
664 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
665 // f32 and f64 use SSE.
666 // Set up the FP register classes.
667 addRegisterClass(MVT::f32, &X86::FR32RegClass);
668 addRegisterClass(MVT::f64, &X86::FR64RegClass);
670 // Use ANDPD to simulate FABS.
671 setOperationAction(ISD::FABS , MVT::f64, Custom);
672 setOperationAction(ISD::FABS , MVT::f32, Custom);
674 // Use XORP to simulate FNEG.
675 setOperationAction(ISD::FNEG , MVT::f64, Custom);
676 setOperationAction(ISD::FNEG , MVT::f32, Custom);
678 // Use ANDPD and ORPD to simulate FCOPYSIGN.
679 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
680 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
682 // Lower this to FGETSIGNx86 plus an AND.
683 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
684 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
686 // We don't support sin/cos/fmod
687 setOperationAction(ISD::FSIN , MVT::f64, Expand);
688 setOperationAction(ISD::FCOS , MVT::f64, Expand);
689 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
690 setOperationAction(ISD::FSIN , MVT::f32, Expand);
691 setOperationAction(ISD::FCOS , MVT::f32, Expand);
692 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
694 // Expand FP immediates into loads from the stack, except for the special
696 addLegalFPImmediate(APFloat(+0.0)); // xorpd
697 addLegalFPImmediate(APFloat(+0.0f)); // xorps
698 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
699 // Use SSE for f32, x87 for f64.
700 // Set up the FP register classes.
701 addRegisterClass(MVT::f32, &X86::FR32RegClass);
702 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
704 // Use ANDPS to simulate FABS.
705 setOperationAction(ISD::FABS , MVT::f32, Custom);
707 // Use XORP to simulate FNEG.
708 setOperationAction(ISD::FNEG , MVT::f32, Custom);
710 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
712 // Use ANDPS and ORPS to simulate FCOPYSIGN.
713 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
714 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
716 // We don't support sin/cos/fmod
717 setOperationAction(ISD::FSIN , MVT::f32, Expand);
718 setOperationAction(ISD::FCOS , MVT::f32, Expand);
719 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
721 // Special cases we handle for FP constants.
722 addLegalFPImmediate(APFloat(+0.0f)); // xorps
723 addLegalFPImmediate(APFloat(+0.0)); // FLD0
724 addLegalFPImmediate(APFloat(+1.0)); // FLD1
725 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
726 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
728 if (!TM.Options.UnsafeFPMath) {
729 setOperationAction(ISD::FSIN , MVT::f64, Expand);
730 setOperationAction(ISD::FCOS , MVT::f64, Expand);
731 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
733 } else if (!TM.Options.UseSoftFloat) {
734 // f32 and f64 in x87.
735 // Set up the FP register classes.
736 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
737 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
739 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
740 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
741 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
742 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
744 if (!TM.Options.UnsafeFPMath) {
745 setOperationAction(ISD::FSIN , MVT::f64, Expand);
746 setOperationAction(ISD::FSIN , MVT::f32, Expand);
747 setOperationAction(ISD::FCOS , MVT::f64, Expand);
748 setOperationAction(ISD::FCOS , MVT::f32, Expand);
749 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
750 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
752 addLegalFPImmediate(APFloat(+0.0)); // FLD0
753 addLegalFPImmediate(APFloat(+1.0)); // FLD1
754 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
755 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
756 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
757 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
758 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
759 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
762 // We don't support FMA.
763 setOperationAction(ISD::FMA, MVT::f64, Expand);
764 setOperationAction(ISD::FMA, MVT::f32, Expand);
766 // Long double always uses X87.
767 if (!TM.Options.UseSoftFloat) {
768 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
769 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
770 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
772 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
773 addLegalFPImmediate(TmpFlt); // FLD0
775 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
778 APFloat TmpFlt2(+1.0);
779 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
781 addLegalFPImmediate(TmpFlt2); // FLD1
782 TmpFlt2.changeSign();
783 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
786 if (!TM.Options.UnsafeFPMath) {
787 setOperationAction(ISD::FSIN , MVT::f80, Expand);
788 setOperationAction(ISD::FCOS , MVT::f80, Expand);
789 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
792 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
793 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
794 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
795 setOperationAction(ISD::FRINT, MVT::f80, Expand);
796 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
797 setOperationAction(ISD::FMA, MVT::f80, Expand);
800 // Always use a library call for pow.
801 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
802 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
803 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
805 setOperationAction(ISD::FLOG, MVT::f80, Expand);
806 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
807 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
808 setOperationAction(ISD::FEXP, MVT::f80, Expand);
809 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
811 // First set operation action for all vector types to either promote
812 // (for widening) or expand (for scalarization). Then we will selectively
813 // turn on ones that can be effectively codegen'd.
814 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
815 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
816 MVT VT = (MVT::SimpleValueType)i;
817 setOperationAction(ISD::ADD , VT, Expand);
818 setOperationAction(ISD::SUB , VT, Expand);
819 setOperationAction(ISD::FADD, VT, Expand);
820 setOperationAction(ISD::FNEG, VT, Expand);
821 setOperationAction(ISD::FSUB, VT, Expand);
822 setOperationAction(ISD::MUL , VT, Expand);
823 setOperationAction(ISD::FMUL, VT, Expand);
824 setOperationAction(ISD::SDIV, VT, Expand);
825 setOperationAction(ISD::UDIV, VT, Expand);
826 setOperationAction(ISD::FDIV, VT, Expand);
827 setOperationAction(ISD::SREM, VT, Expand);
828 setOperationAction(ISD::UREM, VT, Expand);
829 setOperationAction(ISD::LOAD, VT, Expand);
830 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
831 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
832 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
833 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
834 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
835 setOperationAction(ISD::FABS, VT, Expand);
836 setOperationAction(ISD::FSIN, VT, Expand);
837 setOperationAction(ISD::FSINCOS, VT, Expand);
838 setOperationAction(ISD::FCOS, VT, Expand);
839 setOperationAction(ISD::FSINCOS, VT, Expand);
840 setOperationAction(ISD::FREM, VT, Expand);
841 setOperationAction(ISD::FMA, VT, Expand);
842 setOperationAction(ISD::FPOWI, VT, Expand);
843 setOperationAction(ISD::FSQRT, VT, Expand);
844 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
845 setOperationAction(ISD::FFLOOR, VT, Expand);
846 setOperationAction(ISD::FCEIL, VT, Expand);
847 setOperationAction(ISD::FTRUNC, VT, Expand);
848 setOperationAction(ISD::FRINT, VT, Expand);
849 setOperationAction(ISD::FNEARBYINT, VT, Expand);
850 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
851 setOperationAction(ISD::MULHS, VT, Expand);
852 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
853 setOperationAction(ISD::MULHU, VT, Expand);
854 setOperationAction(ISD::SDIVREM, VT, Expand);
855 setOperationAction(ISD::UDIVREM, VT, Expand);
856 setOperationAction(ISD::FPOW, VT, Expand);
857 setOperationAction(ISD::CTPOP, VT, Expand);
858 setOperationAction(ISD::CTTZ, VT, Expand);
859 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
860 setOperationAction(ISD::CTLZ, VT, Expand);
861 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
862 setOperationAction(ISD::SHL, VT, Expand);
863 setOperationAction(ISD::SRA, VT, Expand);
864 setOperationAction(ISD::SRL, VT, Expand);
865 setOperationAction(ISD::ROTL, VT, Expand);
866 setOperationAction(ISD::ROTR, VT, Expand);
867 setOperationAction(ISD::BSWAP, VT, Expand);
868 setOperationAction(ISD::SETCC, VT, Expand);
869 setOperationAction(ISD::FLOG, VT, Expand);
870 setOperationAction(ISD::FLOG2, VT, Expand);
871 setOperationAction(ISD::FLOG10, VT, Expand);
872 setOperationAction(ISD::FEXP, VT, Expand);
873 setOperationAction(ISD::FEXP2, VT, Expand);
874 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
875 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
876 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
877 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
878 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
879 setOperationAction(ISD::TRUNCATE, VT, Expand);
880 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
881 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
882 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
883 setOperationAction(ISD::VSELECT, VT, Expand);
884 setOperationAction(ISD::SELECT_CC, VT, Expand);
885 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
886 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
887 setTruncStoreAction(VT,
888 (MVT::SimpleValueType)InnerVT, Expand);
889 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
890 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
892 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
893 // we have to deal with them whether we ask for Expansion or not. Setting
894 // Expand causes its own optimisation problems though, so leave them legal.
895 if (VT.getVectorElementType() == MVT::i1)
896 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
899 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
900 // with -msoft-float, disable use of MMX as well.
901 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
902 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
903 // No operations on x86mmx supported, everything uses intrinsics.
906 // MMX-sized vectors (other than x86mmx) are expected to be expanded
907 // into smaller operations.
908 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
909 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
910 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
911 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
912 setOperationAction(ISD::AND, MVT::v8i8, Expand);
913 setOperationAction(ISD::AND, MVT::v4i16, Expand);
914 setOperationAction(ISD::AND, MVT::v2i32, Expand);
915 setOperationAction(ISD::AND, MVT::v1i64, Expand);
916 setOperationAction(ISD::OR, MVT::v8i8, Expand);
917 setOperationAction(ISD::OR, MVT::v4i16, Expand);
918 setOperationAction(ISD::OR, MVT::v2i32, Expand);
919 setOperationAction(ISD::OR, MVT::v1i64, Expand);
920 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
921 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
922 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
923 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
924 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
925 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
926 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
927 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
928 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
929 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
930 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
931 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
932 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
933 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
934 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
935 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
936 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
938 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
939 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
941 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
942 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
943 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
944 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
945 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
946 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
947 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
948 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
949 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
950 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
951 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
952 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
955 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
956 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
958 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
959 // registers cannot be used even for integer operations.
960 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
961 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
962 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
963 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
965 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
966 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
967 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
968 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
969 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
970 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
971 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
972 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
973 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
974 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
975 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
976 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
977 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
978 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
979 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
980 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
981 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
982 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
983 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
984 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
985 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
986 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
988 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
989 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
990 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
991 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
993 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
994 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
995 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
999 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1000 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1001 MVT VT = (MVT::SimpleValueType)i;
1002 // Do not attempt to custom lower non-power-of-2 vectors
1003 if (!isPowerOf2_32(VT.getVectorNumElements()))
1005 // Do not attempt to custom lower non-128-bit vectors
1006 if (!VT.is128BitVector())
1008 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1009 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1010 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1013 // We support custom legalizing of sext and anyext loads for specific
1014 // memory vector types which we can load as a scalar (or sequence of
1015 // scalars) and extend in-register to a legal 128-bit vector type. For sext
1016 // loads these must work with a single scalar load.
1017 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1018 if (Subtarget->is64Bit()) {
1019 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1020 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1022 setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1023 setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1024 setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1025 setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1026 setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1027 setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1029 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1030 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1031 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1032 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1033 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1034 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1036 if (Subtarget->is64Bit()) {
1037 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1038 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1041 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1042 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1043 MVT VT = (MVT::SimpleValueType)i;
1045 // Do not attempt to promote non-128-bit vectors
1046 if (!VT.is128BitVector())
1049 setOperationAction(ISD::AND, VT, Promote);
1050 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1051 setOperationAction(ISD::OR, VT, Promote);
1052 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1053 setOperationAction(ISD::XOR, VT, Promote);
1054 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1055 setOperationAction(ISD::LOAD, VT, Promote);
1056 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1057 setOperationAction(ISD::SELECT, VT, Promote);
1058 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1061 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1063 // Custom lower v2i64 and v2f64 selects.
1064 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1065 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1066 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1067 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1069 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1070 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1072 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1073 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1074 // As there is no 64-bit GPR available, we need build a special custom
1075 // sequence to convert from v2i32 to v2f32.
1076 if (!Subtarget->is64Bit())
1077 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1079 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1080 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1082 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1084 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1085 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1086 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1089 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1090 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1091 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1092 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1093 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1094 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1095 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1096 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1097 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1098 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1099 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1101 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1102 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1103 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1104 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1105 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1106 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1107 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1108 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1109 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1110 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1112 // FIXME: Do we need to handle scalar-to-vector here?
1113 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1115 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1116 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1117 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1118 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1119 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1120 // There is no BLENDI for byte vectors. We don't need to custom lower
1121 // some vselects for now.
1122 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1124 // SSE41 brings specific instructions for doing vector sign extend even in
1125 // cases where we don't have SRA.
1126 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1127 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1128 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1130 // i8 and i16 vectors are custom because the source register and source
1131 // source memory operand types are not the same width. f32 vectors are
1132 // custom since the immediate controlling the insert encodes additional
1134 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1135 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1136 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1137 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1139 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1140 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1141 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1142 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1144 // FIXME: these should be Legal, but that's only for the case where
1145 // the index is constant. For now custom expand to deal with that.
1146 if (Subtarget->is64Bit()) {
1147 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1148 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1152 if (Subtarget->hasSSE2()) {
1153 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1154 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1156 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1157 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1159 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1160 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1162 // In the customized shift lowering, the legal cases in AVX2 will be
1164 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1165 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1167 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1168 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1170 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1173 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1174 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1175 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1176 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1177 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1178 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1179 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1181 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1182 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1183 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1185 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1186 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1187 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1188 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1189 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1190 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1191 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1192 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1193 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1194 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1195 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1196 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1198 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1199 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1200 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1201 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1202 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1203 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1204 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1205 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1206 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1207 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1208 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1209 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1211 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1212 // even though v8i16 is a legal type.
1213 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1214 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1215 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1217 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1218 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1219 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1221 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1222 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1224 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1226 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1227 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1229 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1230 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1232 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1233 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1235 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1236 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1237 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1238 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1240 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1241 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1242 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1244 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1245 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1246 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1247 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1249 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1250 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1251 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1252 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1253 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1254 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1255 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1256 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1257 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1258 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1259 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1260 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1262 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1263 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1264 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1265 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1266 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1267 setOperationAction(ISD::FMA, MVT::f32, Legal);
1268 setOperationAction(ISD::FMA, MVT::f64, Legal);
1271 if (Subtarget->hasInt256()) {
1272 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1273 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1274 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1275 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1277 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1278 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1279 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1280 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1282 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1283 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1284 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1285 // Don't lower v32i8 because there is no 128-bit byte mul
1287 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1288 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1289 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1290 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1292 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1293 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1295 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1296 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1297 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1298 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1300 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1301 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1302 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1303 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1305 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1306 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1307 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1308 // Don't lower v32i8 because there is no 128-bit byte mul
1311 // In the customized shift lowering, the legal cases in AVX2 will be
1313 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1314 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1316 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1317 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1319 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1321 // Custom lower several nodes for 256-bit types.
1322 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1323 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1324 MVT VT = (MVT::SimpleValueType)i;
1326 // Extract subvector is special because the value type
1327 // (result) is 128-bit but the source is 256-bit wide.
1328 if (VT.is128BitVector())
1329 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1331 // Do not attempt to custom lower other non-256-bit vectors
1332 if (!VT.is256BitVector())
1335 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1336 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1337 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1338 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1339 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1340 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1341 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1344 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1345 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1346 MVT VT = (MVT::SimpleValueType)i;
1348 // Do not attempt to promote non-256-bit vectors
1349 if (!VT.is256BitVector())
1352 setOperationAction(ISD::AND, VT, Promote);
1353 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1354 setOperationAction(ISD::OR, VT, Promote);
1355 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1356 setOperationAction(ISD::XOR, VT, Promote);
1357 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1358 setOperationAction(ISD::LOAD, VT, Promote);
1359 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1360 setOperationAction(ISD::SELECT, VT, Promote);
1361 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1365 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1366 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1367 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1368 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1369 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1371 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1372 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1373 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1375 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1376 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1377 setOperationAction(ISD::XOR, MVT::i1, Legal);
1378 setOperationAction(ISD::OR, MVT::i1, Legal);
1379 setOperationAction(ISD::AND, MVT::i1, Legal);
1380 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1381 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1382 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1383 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1384 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1385 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1387 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1388 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1389 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1390 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1391 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1392 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1394 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1395 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1396 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1397 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1398 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1399 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1400 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1401 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1403 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1404 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1405 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1406 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1407 if (Subtarget->is64Bit()) {
1408 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1409 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1410 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1411 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1413 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1414 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1415 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1416 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1417 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1418 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1419 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1420 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1421 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1422 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1424 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1425 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1426 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1427 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1428 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1429 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1430 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1431 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1432 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1433 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1434 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1435 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1436 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1438 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1439 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1440 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1441 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1442 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1443 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1445 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1446 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1448 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1450 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1451 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1452 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1453 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1454 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1455 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1456 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1457 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1458 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1460 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1461 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1463 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1464 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1466 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1468 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1469 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1471 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1472 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1474 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1475 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1477 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1478 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1479 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1480 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1481 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1482 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1484 if (Subtarget->hasCDI()) {
1485 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1486 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1489 // Custom lower several nodes.
1490 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1491 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1492 MVT VT = (MVT::SimpleValueType)i;
1494 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1495 // Extract subvector is special because the value type
1496 // (result) is 256/128-bit but the source is 512-bit wide.
1497 if (VT.is128BitVector() || VT.is256BitVector())
1498 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1500 if (VT.getVectorElementType() == MVT::i1)
1501 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1503 // Do not attempt to custom lower other non-512-bit vectors
1504 if (!VT.is512BitVector())
1507 if ( EltSize >= 32) {
1508 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1509 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1510 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1511 setOperationAction(ISD::VSELECT, VT, Legal);
1512 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1513 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1514 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1517 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1518 MVT VT = (MVT::SimpleValueType)i;
1520 // Do not attempt to promote non-256-bit vectors
1521 if (!VT.is512BitVector())
1524 setOperationAction(ISD::SELECT, VT, Promote);
1525 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1529 if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1530 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1531 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1534 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1535 // of this type with custom code.
1536 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1537 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1538 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1542 // We want to custom lower some of our intrinsics.
1543 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1544 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1545 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1546 if (!Subtarget->is64Bit())
1547 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1549 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1550 // handle type legalization for these operations here.
1552 // FIXME: We really should do custom legalization for addition and
1553 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1554 // than generic legalization for 64-bit multiplication-with-overflow, though.
1555 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1556 // Add/Sub/Mul with overflow operations are custom lowered.
1558 setOperationAction(ISD::SADDO, VT, Custom);
1559 setOperationAction(ISD::UADDO, VT, Custom);
1560 setOperationAction(ISD::SSUBO, VT, Custom);
1561 setOperationAction(ISD::USUBO, VT, Custom);
1562 setOperationAction(ISD::SMULO, VT, Custom);
1563 setOperationAction(ISD::UMULO, VT, Custom);
1566 // There are no 8-bit 3-address imul/mul instructions
1567 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1568 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1570 if (!Subtarget->is64Bit()) {
1571 // These libcalls are not available in 32-bit.
1572 setLibcallName(RTLIB::SHL_I128, nullptr);
1573 setLibcallName(RTLIB::SRL_I128, nullptr);
1574 setLibcallName(RTLIB::SRA_I128, nullptr);
1577 // Combine sin / cos into one node or libcall if possible.
1578 if (Subtarget->hasSinCos()) {
1579 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1580 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1581 if (Subtarget->isTargetDarwin()) {
1582 // For MacOSX, we don't want to the normal expansion of a libcall to
1583 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1585 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1586 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1590 if (Subtarget->isTargetWin64()) {
1591 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1592 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1593 setOperationAction(ISD::SREM, MVT::i128, Custom);
1594 setOperationAction(ISD::UREM, MVT::i128, Custom);
1595 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1596 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1599 // We have target-specific dag combine patterns for the following nodes:
1600 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1601 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1602 setTargetDAGCombine(ISD::VSELECT);
1603 setTargetDAGCombine(ISD::SELECT);
1604 setTargetDAGCombine(ISD::SHL);
1605 setTargetDAGCombine(ISD::SRA);
1606 setTargetDAGCombine(ISD::SRL);
1607 setTargetDAGCombine(ISD::OR);
1608 setTargetDAGCombine(ISD::AND);
1609 setTargetDAGCombine(ISD::ADD);
1610 setTargetDAGCombine(ISD::FADD);
1611 setTargetDAGCombine(ISD::FSUB);
1612 setTargetDAGCombine(ISD::FMA);
1613 setTargetDAGCombine(ISD::SUB);
1614 setTargetDAGCombine(ISD::LOAD);
1615 setTargetDAGCombine(ISD::STORE);
1616 setTargetDAGCombine(ISD::ZERO_EXTEND);
1617 setTargetDAGCombine(ISD::ANY_EXTEND);
1618 setTargetDAGCombine(ISD::SIGN_EXTEND);
1619 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1620 setTargetDAGCombine(ISD::TRUNCATE);
1621 setTargetDAGCombine(ISD::SINT_TO_FP);
1622 setTargetDAGCombine(ISD::SETCC);
1623 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1624 setTargetDAGCombine(ISD::BUILD_VECTOR);
1625 if (Subtarget->is64Bit())
1626 setTargetDAGCombine(ISD::MUL);
1627 setTargetDAGCombine(ISD::XOR);
1629 computeRegisterProperties();
1631 // On Darwin, -Os means optimize for size without hurting performance,
1632 // do not reduce the limit.
1633 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1634 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1635 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1636 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1637 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1638 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1639 setPrefLoopAlignment(4); // 2^4 bytes.
1641 // Predictable cmov don't hurt on atom because it's in-order.
1642 PredictableSelectIsExpensive = !Subtarget->isAtom();
1644 setPrefFunctionAlignment(4); // 2^4 bytes.
1647 // This has so far only been implemented for 64-bit MachO.
1648 bool X86TargetLowering::useLoadStackGuardNode() const {
1649 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1650 Subtarget->is64Bit();
1653 TargetLoweringBase::LegalizeTypeAction
1654 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1655 if (ExperimentalVectorWideningLegalization &&
1656 VT.getVectorNumElements() != 1 &&
1657 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1658 return TypeWidenVector;
1660 return TargetLoweringBase::getPreferredVectorAction(VT);
1663 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1665 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1667 if (Subtarget->hasAVX512())
1668 switch(VT.getVectorNumElements()) {
1669 case 8: return MVT::v8i1;
1670 case 16: return MVT::v16i1;
1673 return VT.changeVectorElementTypeToInteger();
1676 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1677 /// the desired ByVal argument alignment.
1678 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1681 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1682 if (VTy->getBitWidth() == 128)
1684 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1685 unsigned EltAlign = 0;
1686 getMaxByValAlign(ATy->getElementType(), EltAlign);
1687 if (EltAlign > MaxAlign)
1688 MaxAlign = EltAlign;
1689 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1690 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1691 unsigned EltAlign = 0;
1692 getMaxByValAlign(STy->getElementType(i), EltAlign);
1693 if (EltAlign > MaxAlign)
1694 MaxAlign = EltAlign;
1701 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1702 /// function arguments in the caller parameter area. For X86, aggregates
1703 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1704 /// are at 4-byte boundaries.
1705 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1706 if (Subtarget->is64Bit()) {
1707 // Max of 8 and alignment of type.
1708 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1715 if (Subtarget->hasSSE1())
1716 getMaxByValAlign(Ty, Align);
1720 /// getOptimalMemOpType - Returns the target specific optimal type for load
1721 /// and store operations as a result of memset, memcpy, and memmove
1722 /// lowering. If DstAlign is zero that means it's safe to destination
1723 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1724 /// means there isn't a need to check it against alignment requirement,
1725 /// probably because the source does not need to be loaded. If 'IsMemset' is
1726 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1727 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1728 /// source is constant so it does not need to be loaded.
1729 /// It returns EVT::Other if the type should be determined using generic
1730 /// target-independent logic.
1732 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1733 unsigned DstAlign, unsigned SrcAlign,
1734 bool IsMemset, bool ZeroMemset,
1736 MachineFunction &MF) const {
1737 const Function *F = MF.getFunction();
1738 if ((!IsMemset || ZeroMemset) &&
1739 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1740 Attribute::NoImplicitFloat)) {
1742 (Subtarget->isUnalignedMemAccessFast() ||
1743 ((DstAlign == 0 || DstAlign >= 16) &&
1744 (SrcAlign == 0 || SrcAlign >= 16)))) {
1746 if (Subtarget->hasInt256())
1748 if (Subtarget->hasFp256())
1751 if (Subtarget->hasSSE2())
1753 if (Subtarget->hasSSE1())
1755 } else if (!MemcpyStrSrc && Size >= 8 &&
1756 !Subtarget->is64Bit() &&
1757 Subtarget->hasSSE2()) {
1758 // Do not use f64 to lower memcpy if source is string constant. It's
1759 // better to use i32 to avoid the loads.
1763 if (Subtarget->is64Bit() && Size >= 8)
1768 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1770 return X86ScalarSSEf32;
1771 else if (VT == MVT::f64)
1772 return X86ScalarSSEf64;
1777 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1782 *Fast = Subtarget->isUnalignedMemAccessFast();
1786 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1787 /// current function. The returned value is a member of the
1788 /// MachineJumpTableInfo::JTEntryKind enum.
1789 unsigned X86TargetLowering::getJumpTableEncoding() const {
1790 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1792 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1793 Subtarget->isPICStyleGOT())
1794 return MachineJumpTableInfo::EK_Custom32;
1796 // Otherwise, use the normal jump table encoding heuristics.
1797 return TargetLowering::getJumpTableEncoding();
1801 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1802 const MachineBasicBlock *MBB,
1803 unsigned uid,MCContext &Ctx) const{
1804 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1805 Subtarget->isPICStyleGOT());
1806 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1808 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1809 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1812 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1814 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1815 SelectionDAG &DAG) const {
1816 if (!Subtarget->is64Bit())
1817 // This doesn't have SDLoc associated with it, but is not really the
1818 // same as a Register.
1819 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1823 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1824 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1826 const MCExpr *X86TargetLowering::
1827 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1828 MCContext &Ctx) const {
1829 // X86-64 uses RIP relative addressing based on the jump table label.
1830 if (Subtarget->isPICStyleRIPRel())
1831 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1833 // Otherwise, the reference is relative to the PIC base.
1834 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1837 // FIXME: Why this routine is here? Move to RegInfo!
1838 std::pair<const TargetRegisterClass*, uint8_t>
1839 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1840 const TargetRegisterClass *RRC = nullptr;
1842 switch (VT.SimpleTy) {
1844 return TargetLowering::findRepresentativeClass(VT);
1845 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1846 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1849 RRC = &X86::VR64RegClass;
1851 case MVT::f32: case MVT::f64:
1852 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1853 case MVT::v4f32: case MVT::v2f64:
1854 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1856 RRC = &X86::VR128RegClass;
1859 return std::make_pair(RRC, Cost);
1862 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1863 unsigned &Offset) const {
1864 if (!Subtarget->isTargetLinux())
1867 if (Subtarget->is64Bit()) {
1868 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1870 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1882 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1883 unsigned DestAS) const {
1884 assert(SrcAS != DestAS && "Expected different address spaces!");
1886 return SrcAS < 256 && DestAS < 256;
1889 //===----------------------------------------------------------------------===//
1890 // Return Value Calling Convention Implementation
1891 //===----------------------------------------------------------------------===//
1893 #include "X86GenCallingConv.inc"
1896 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1897 MachineFunction &MF, bool isVarArg,
1898 const SmallVectorImpl<ISD::OutputArg> &Outs,
1899 LLVMContext &Context) const {
1900 SmallVector<CCValAssign, 16> RVLocs;
1901 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1902 return CCInfo.CheckReturn(Outs, RetCC_X86);
1905 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1906 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1911 X86TargetLowering::LowerReturn(SDValue Chain,
1912 CallingConv::ID CallConv, bool isVarArg,
1913 const SmallVectorImpl<ISD::OutputArg> &Outs,
1914 const SmallVectorImpl<SDValue> &OutVals,
1915 SDLoc dl, SelectionDAG &DAG) const {
1916 MachineFunction &MF = DAG.getMachineFunction();
1917 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1919 SmallVector<CCValAssign, 16> RVLocs;
1920 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1921 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1924 SmallVector<SDValue, 6> RetOps;
1925 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1926 // Operand #1 = Bytes To Pop
1927 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1930 // Copy the result values into the output registers.
1931 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1932 CCValAssign &VA = RVLocs[i];
1933 assert(VA.isRegLoc() && "Can only return in registers!");
1934 SDValue ValToCopy = OutVals[i];
1935 EVT ValVT = ValToCopy.getValueType();
1937 // Promote values to the appropriate types
1938 if (VA.getLocInfo() == CCValAssign::SExt)
1939 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1940 else if (VA.getLocInfo() == CCValAssign::ZExt)
1941 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1942 else if (VA.getLocInfo() == CCValAssign::AExt)
1943 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1944 else if (VA.getLocInfo() == CCValAssign::BCvt)
1945 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1947 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1948 "Unexpected FP-extend for return value.");
1950 // If this is x86-64, and we disabled SSE, we can't return FP values,
1951 // or SSE or MMX vectors.
1952 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1953 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1954 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1955 report_fatal_error("SSE register return with SSE disabled");
1957 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1958 // llvm-gcc has never done it right and no one has noticed, so this
1959 // should be OK for now.
1960 if (ValVT == MVT::f64 &&
1961 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1962 report_fatal_error("SSE2 register return with SSE2 disabled");
1964 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1965 // the RET instruction and handled by the FP Stackifier.
1966 if (VA.getLocReg() == X86::FP0 ||
1967 VA.getLocReg() == X86::FP1) {
1968 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1969 // change the value to the FP stack register class.
1970 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1971 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1972 RetOps.push_back(ValToCopy);
1973 // Don't emit a copytoreg.
1977 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1978 // which is returned in RAX / RDX.
1979 if (Subtarget->is64Bit()) {
1980 if (ValVT == MVT::x86mmx) {
1981 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1982 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1983 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1985 // If we don't have SSE2 available, convert to v4f32 so the generated
1986 // register is legal.
1987 if (!Subtarget->hasSSE2())
1988 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1993 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1994 Flag = Chain.getValue(1);
1995 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1998 // The x86-64 ABIs require that for returning structs by value we copy
1999 // the sret argument into %rax/%eax (depending on ABI) for the return.
2000 // Win32 requires us to put the sret argument to %eax as well.
2001 // We saved the argument into a virtual register in the entry block,
2002 // so now we copy the value out and into %rax/%eax.
2003 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2004 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2005 MachineFunction &MF = DAG.getMachineFunction();
2006 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2007 unsigned Reg = FuncInfo->getSRetReturnReg();
2009 "SRetReturnReg should have been set in LowerFormalArguments().");
2010 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2013 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2014 X86::RAX : X86::EAX;
2015 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2016 Flag = Chain.getValue(1);
2018 // RAX/EAX now acts like a return value.
2019 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2022 RetOps[0] = Chain; // Update chain.
2024 // Add the flag if we have it.
2026 RetOps.push_back(Flag);
2028 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2031 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2032 if (N->getNumValues() != 1)
2034 if (!N->hasNUsesOfValue(1, 0))
2037 SDValue TCChain = Chain;
2038 SDNode *Copy = *N->use_begin();
2039 if (Copy->getOpcode() == ISD::CopyToReg) {
2040 // If the copy has a glue operand, we conservatively assume it isn't safe to
2041 // perform a tail call.
2042 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2044 TCChain = Copy->getOperand(0);
2045 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2048 bool HasRet = false;
2049 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2051 if (UI->getOpcode() != X86ISD::RET_FLAG)
2053 // If we are returning more than one value, we can definitely
2054 // not make a tail call see PR19530
2055 if (UI->getNumOperands() > 4)
2057 if (UI->getNumOperands() == 4 &&
2058 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2071 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2072 ISD::NodeType ExtendKind) const {
2074 // TODO: Is this also valid on 32-bit?
2075 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2076 ReturnMVT = MVT::i8;
2078 ReturnMVT = MVT::i32;
2080 EVT MinVT = getRegisterType(Context, ReturnMVT);
2081 return VT.bitsLT(MinVT) ? MinVT : VT;
2084 /// LowerCallResult - Lower the result values of a call into the
2085 /// appropriate copies out of appropriate physical registers.
2088 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2089 CallingConv::ID CallConv, bool isVarArg,
2090 const SmallVectorImpl<ISD::InputArg> &Ins,
2091 SDLoc dl, SelectionDAG &DAG,
2092 SmallVectorImpl<SDValue> &InVals) const {
2094 // Assign locations to each value returned by this call.
2095 SmallVector<CCValAssign, 16> RVLocs;
2096 bool Is64Bit = Subtarget->is64Bit();
2097 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2099 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2101 // Copy all of the result registers out of their specified physreg.
2102 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2103 CCValAssign &VA = RVLocs[i];
2104 EVT CopyVT = VA.getValVT();
2106 // If this is x86-64, and we disabled SSE, we can't return FP values
2107 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2108 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2109 report_fatal_error("SSE register return with SSE disabled");
2112 // If we prefer to use the value in xmm registers, copy it out as f80 and
2113 // use a truncate to move it from fp stack reg to xmm reg.
2114 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2115 isScalarFPTypeInSSEReg(VA.getValVT()))
2118 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2119 CopyVT, InFlag).getValue(1);
2120 SDValue Val = Chain.getValue(0);
2122 if (CopyVT != VA.getValVT())
2123 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2124 // This truncation won't change the value.
2125 DAG.getIntPtrConstant(1));
2127 InFlag = Chain.getValue(2);
2128 InVals.push_back(Val);
2134 //===----------------------------------------------------------------------===//
2135 // C & StdCall & Fast Calling Convention implementation
2136 //===----------------------------------------------------------------------===//
2137 // StdCall calling convention seems to be standard for many Windows' API
2138 // routines and around. It differs from C calling convention just a little:
2139 // callee should clean up the stack, not caller. Symbols should be also
2140 // decorated in some fancy way :) It doesn't support any vector arguments.
2141 // For info on fast calling convention see Fast Calling Convention (tail call)
2142 // implementation LowerX86_32FastCCCallTo.
2144 /// CallIsStructReturn - Determines whether a call uses struct return
2146 enum StructReturnType {
2151 static StructReturnType
2152 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2154 return NotStructReturn;
2156 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2157 if (!Flags.isSRet())
2158 return NotStructReturn;
2159 if (Flags.isInReg())
2160 return RegStructReturn;
2161 return StackStructReturn;
2164 /// ArgsAreStructReturn - Determines whether a function uses struct
2165 /// return semantics.
2166 static StructReturnType
2167 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2169 return NotStructReturn;
2171 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2172 if (!Flags.isSRet())
2173 return NotStructReturn;
2174 if (Flags.isInReg())
2175 return RegStructReturn;
2176 return StackStructReturn;
2179 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2180 /// by "Src" to address "Dst" with size and alignment information specified by
2181 /// the specific parameter attribute. The copy will be passed as a byval
2182 /// function parameter.
2184 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2185 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2187 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2189 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2190 /*isVolatile*/false, /*AlwaysInline=*/true,
2191 MachinePointerInfo(), MachinePointerInfo());
2194 /// IsTailCallConvention - Return true if the calling convention is one that
2195 /// supports tail call optimization.
2196 static bool IsTailCallConvention(CallingConv::ID CC) {
2197 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2198 CC == CallingConv::HiPE);
2201 /// \brief Return true if the calling convention is a C calling convention.
2202 static bool IsCCallConvention(CallingConv::ID CC) {
2203 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2204 CC == CallingConv::X86_64_SysV);
2207 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2208 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2212 CallingConv::ID CalleeCC = CS.getCallingConv();
2213 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2219 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2220 /// a tailcall target by changing its ABI.
2221 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2222 bool GuaranteedTailCallOpt) {
2223 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2227 X86TargetLowering::LowerMemArgument(SDValue Chain,
2228 CallingConv::ID CallConv,
2229 const SmallVectorImpl<ISD::InputArg> &Ins,
2230 SDLoc dl, SelectionDAG &DAG,
2231 const CCValAssign &VA,
2232 MachineFrameInfo *MFI,
2234 // Create the nodes corresponding to a load from this parameter slot.
2235 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2236 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2237 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2238 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2241 // If value is passed by pointer we have address passed instead of the value
2243 if (VA.getLocInfo() == CCValAssign::Indirect)
2244 ValVT = VA.getLocVT();
2246 ValVT = VA.getValVT();
2248 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2249 // changed with more analysis.
2250 // In case of tail call optimization mark all arguments mutable. Since they
2251 // could be overwritten by lowering of arguments in case of a tail call.
2252 if (Flags.isByVal()) {
2253 unsigned Bytes = Flags.getByValSize();
2254 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2255 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2256 return DAG.getFrameIndex(FI, getPointerTy());
2258 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2259 VA.getLocMemOffset(), isImmutable);
2260 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2261 return DAG.getLoad(ValVT, dl, Chain, FIN,
2262 MachinePointerInfo::getFixedStack(FI),
2263 false, false, false, 0);
2268 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2269 CallingConv::ID CallConv,
2271 const SmallVectorImpl<ISD::InputArg> &Ins,
2274 SmallVectorImpl<SDValue> &InVals)
2276 MachineFunction &MF = DAG.getMachineFunction();
2277 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2279 const Function* Fn = MF.getFunction();
2280 if (Fn->hasExternalLinkage() &&
2281 Subtarget->isTargetCygMing() &&
2282 Fn->getName() == "main")
2283 FuncInfo->setForceFramePointer(true);
2285 MachineFrameInfo *MFI = MF.getFrameInfo();
2286 bool Is64Bit = Subtarget->is64Bit();
2287 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2289 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2290 "Var args not supported with calling convention fastcc, ghc or hipe");
2292 // Assign locations to all of the incoming arguments.
2293 SmallVector<CCValAssign, 16> ArgLocs;
2294 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2296 // Allocate shadow area for Win64
2298 CCInfo.AllocateStack(32, 8);
2300 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2302 unsigned LastVal = ~0U;
2304 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2305 CCValAssign &VA = ArgLocs[i];
2306 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2308 assert(VA.getValNo() != LastVal &&
2309 "Don't support value assigned to multiple locs yet");
2311 LastVal = VA.getValNo();
2313 if (VA.isRegLoc()) {
2314 EVT RegVT = VA.getLocVT();
2315 const TargetRegisterClass *RC;
2316 if (RegVT == MVT::i32)
2317 RC = &X86::GR32RegClass;
2318 else if (Is64Bit && RegVT == MVT::i64)
2319 RC = &X86::GR64RegClass;
2320 else if (RegVT == MVT::f32)
2321 RC = &X86::FR32RegClass;
2322 else if (RegVT == MVT::f64)
2323 RC = &X86::FR64RegClass;
2324 else if (RegVT.is512BitVector())
2325 RC = &X86::VR512RegClass;
2326 else if (RegVT.is256BitVector())
2327 RC = &X86::VR256RegClass;
2328 else if (RegVT.is128BitVector())
2329 RC = &X86::VR128RegClass;
2330 else if (RegVT == MVT::x86mmx)
2331 RC = &X86::VR64RegClass;
2332 else if (RegVT == MVT::i1)
2333 RC = &X86::VK1RegClass;
2334 else if (RegVT == MVT::v8i1)
2335 RC = &X86::VK8RegClass;
2336 else if (RegVT == MVT::v16i1)
2337 RC = &X86::VK16RegClass;
2338 else if (RegVT == MVT::v32i1)
2339 RC = &X86::VK32RegClass;
2340 else if (RegVT == MVT::v64i1)
2341 RC = &X86::VK64RegClass;
2343 llvm_unreachable("Unknown argument type!");
2345 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2346 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2348 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2349 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2351 if (VA.getLocInfo() == CCValAssign::SExt)
2352 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2353 DAG.getValueType(VA.getValVT()));
2354 else if (VA.getLocInfo() == CCValAssign::ZExt)
2355 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2356 DAG.getValueType(VA.getValVT()));
2357 else if (VA.getLocInfo() == CCValAssign::BCvt)
2358 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2360 if (VA.isExtInLoc()) {
2361 // Handle MMX values passed in XMM regs.
2362 if (RegVT.isVector())
2363 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2365 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2368 assert(VA.isMemLoc());
2369 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2372 // If value is passed via pointer - do a load.
2373 if (VA.getLocInfo() == CCValAssign::Indirect)
2374 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2375 MachinePointerInfo(), false, false, false, 0);
2377 InVals.push_back(ArgValue);
2380 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2381 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2382 // The x86-64 ABIs require that for returning structs by value we copy
2383 // the sret argument into %rax/%eax (depending on ABI) for the return.
2384 // Win32 requires us to put the sret argument to %eax as well.
2385 // Save the argument into a virtual register so that we can access it
2386 // from the return points.
2387 if (Ins[i].Flags.isSRet()) {
2388 unsigned Reg = FuncInfo->getSRetReturnReg();
2390 MVT PtrTy = getPointerTy();
2391 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2392 FuncInfo->setSRetReturnReg(Reg);
2394 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2395 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2401 unsigned StackSize = CCInfo.getNextStackOffset();
2402 // Align stack specially for tail calls.
2403 if (FuncIsMadeTailCallSafe(CallConv,
2404 MF.getTarget().Options.GuaranteedTailCallOpt))
2405 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2407 // If the function takes variable number of arguments, make a frame index for
2408 // the start of the first vararg value... for expansion of llvm.va_start. We
2409 // can skip this if there are no va_start calls.
2410 if (isVarArg && MFI->hasVAStart()) {
2411 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2412 CallConv != CallingConv::X86_ThisCall)) {
2413 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2416 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2418 // FIXME: We should really autogenerate these arrays
2419 static const MCPhysReg GPR64ArgRegsWin64[] = {
2420 X86::RCX, X86::RDX, X86::R8, X86::R9
2422 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2423 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2425 static const MCPhysReg XMMArgRegs64Bit[] = {
2426 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2427 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2429 const MCPhysReg *GPR64ArgRegs;
2430 unsigned NumXMMRegs = 0;
2433 // The XMM registers which might contain var arg parameters are shadowed
2434 // in their paired GPR. So we only need to save the GPR to their home
2436 TotalNumIntRegs = 4;
2437 GPR64ArgRegs = GPR64ArgRegsWin64;
2439 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2440 GPR64ArgRegs = GPR64ArgRegs64Bit;
2442 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2445 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2448 bool NoImplicitFloatOps = Fn->getAttributes().
2449 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2450 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2451 "SSE register cannot be used when SSE is disabled!");
2452 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2453 NoImplicitFloatOps) &&
2454 "SSE register cannot be used when SSE is disabled!");
2455 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2456 !Subtarget->hasSSE1())
2457 // Kernel mode asks for SSE to be disabled, so don't push them
2459 TotalNumXMMRegs = 0;
2462 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2463 // Get to the caller-allocated home save location. Add 8 to account
2464 // for the return address.
2465 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2466 FuncInfo->setRegSaveFrameIndex(
2467 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2468 // Fixup to set vararg frame on shadow area (4 x i64).
2470 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2472 // For X86-64, if there are vararg parameters that are passed via
2473 // registers, then we must store them to their spots on the stack so
2474 // they may be loaded by deferencing the result of va_next.
2475 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2476 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2477 FuncInfo->setRegSaveFrameIndex(
2478 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2482 // Store the integer parameter registers.
2483 SmallVector<SDValue, 8> MemOps;
2484 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2486 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2487 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2488 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2489 DAG.getIntPtrConstant(Offset));
2490 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2491 &X86::GR64RegClass);
2492 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2494 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2495 MachinePointerInfo::getFixedStack(
2496 FuncInfo->getRegSaveFrameIndex(), Offset),
2498 MemOps.push_back(Store);
2502 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2503 // Now store the XMM (fp + vector) parameter registers.
2504 SmallVector<SDValue, 12> SaveXMMOps;
2505 SaveXMMOps.push_back(Chain);
2507 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2508 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2509 SaveXMMOps.push_back(ALVal);
2511 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2512 FuncInfo->getRegSaveFrameIndex()));
2513 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2514 FuncInfo->getVarArgsFPOffset()));
2516 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2517 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2518 &X86::VR128RegClass);
2519 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2520 SaveXMMOps.push_back(Val);
2522 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2523 MVT::Other, SaveXMMOps));
2526 if (!MemOps.empty())
2527 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2531 // Some CCs need callee pop.
2532 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2533 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2534 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2536 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2537 // If this is an sret function, the return should pop the hidden pointer.
2538 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2539 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2540 argsAreStructReturn(Ins) == StackStructReturn)
2541 FuncInfo->setBytesToPopOnReturn(4);
2545 // RegSaveFrameIndex is X86-64 only.
2546 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2547 if (CallConv == CallingConv::X86_FastCall ||
2548 CallConv == CallingConv::X86_ThisCall)
2549 // fastcc functions can't have varargs.
2550 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2553 FuncInfo->setArgumentStackSize(StackSize);
2559 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2560 SDValue StackPtr, SDValue Arg,
2561 SDLoc dl, SelectionDAG &DAG,
2562 const CCValAssign &VA,
2563 ISD::ArgFlagsTy Flags) const {
2564 unsigned LocMemOffset = VA.getLocMemOffset();
2565 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2566 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2567 if (Flags.isByVal())
2568 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2570 return DAG.getStore(Chain, dl, Arg, PtrOff,
2571 MachinePointerInfo::getStack(LocMemOffset),
2575 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2576 /// optimization is performed and it is required.
2578 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2579 SDValue &OutRetAddr, SDValue Chain,
2580 bool IsTailCall, bool Is64Bit,
2581 int FPDiff, SDLoc dl) const {
2582 // Adjust the Return address stack slot.
2583 EVT VT = getPointerTy();
2584 OutRetAddr = getReturnAddressFrameIndex(DAG);
2586 // Load the "old" Return address.
2587 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2588 false, false, false, 0);
2589 return SDValue(OutRetAddr.getNode(), 1);
2592 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2593 /// optimization is performed and it is required (FPDiff!=0).
2594 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2595 SDValue Chain, SDValue RetAddrFrIdx,
2596 EVT PtrVT, unsigned SlotSize,
2597 int FPDiff, SDLoc dl) {
2598 // Store the return address to the appropriate stack slot.
2599 if (!FPDiff) return Chain;
2600 // Calculate the new stack slot for the return address.
2601 int NewReturnAddrFI =
2602 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2604 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2605 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2606 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2612 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2613 SmallVectorImpl<SDValue> &InVals) const {
2614 SelectionDAG &DAG = CLI.DAG;
2616 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2617 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2618 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2619 SDValue Chain = CLI.Chain;
2620 SDValue Callee = CLI.Callee;
2621 CallingConv::ID CallConv = CLI.CallConv;
2622 bool &isTailCall = CLI.IsTailCall;
2623 bool isVarArg = CLI.IsVarArg;
2625 MachineFunction &MF = DAG.getMachineFunction();
2626 bool Is64Bit = Subtarget->is64Bit();
2627 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2628 StructReturnType SR = callIsStructReturn(Outs);
2629 bool IsSibcall = false;
2631 if (MF.getTarget().Options.DisableTailCalls)
2634 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2636 // Force this to be a tail call. The verifier rules are enough to ensure
2637 // that we can lower this successfully without moving the return address
2640 } else if (isTailCall) {
2641 // Check if it's really possible to do a tail call.
2642 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2643 isVarArg, SR != NotStructReturn,
2644 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2645 Outs, OutVals, Ins, DAG);
2647 // Sibcalls are automatically detected tailcalls which do not require
2649 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2656 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2657 "Var args not supported with calling convention fastcc, ghc or hipe");
2659 // Analyze operands of the call, assigning locations to each operand.
2660 SmallVector<CCValAssign, 16> ArgLocs;
2661 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2663 // Allocate shadow area for Win64
2665 CCInfo.AllocateStack(32, 8);
2667 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2669 // Get a count of how many bytes are to be pushed on the stack.
2670 unsigned NumBytes = CCInfo.getNextStackOffset();
2672 // This is a sibcall. The memory operands are available in caller's
2673 // own caller's stack.
2675 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2676 IsTailCallConvention(CallConv))
2677 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2680 if (isTailCall && !IsSibcall && !IsMustTail) {
2681 // Lower arguments at fp - stackoffset + fpdiff.
2682 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2683 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2685 FPDiff = NumBytesCallerPushed - NumBytes;
2687 // Set the delta of movement of the returnaddr stackslot.
2688 // But only set if delta is greater than previous delta.
2689 if (FPDiff < X86Info->getTCReturnAddrDelta())
2690 X86Info->setTCReturnAddrDelta(FPDiff);
2693 unsigned NumBytesToPush = NumBytes;
2694 unsigned NumBytesToPop = NumBytes;
2696 // If we have an inalloca argument, all stack space has already been allocated
2697 // for us and be right at the top of the stack. We don't support multiple
2698 // arguments passed in memory when using inalloca.
2699 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2701 if (!ArgLocs.back().isMemLoc())
2702 report_fatal_error("cannot use inalloca attribute on a register "
2704 if (ArgLocs.back().getLocMemOffset() != 0)
2705 report_fatal_error("any parameter with the inalloca attribute must be "
2706 "the only memory argument");
2710 Chain = DAG.getCALLSEQ_START(
2711 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2713 SDValue RetAddrFrIdx;
2714 // Load return address for tail calls.
2715 if (isTailCall && FPDiff)
2716 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2717 Is64Bit, FPDiff, dl);
2719 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2720 SmallVector<SDValue, 8> MemOpChains;
2723 // Walk the register/memloc assignments, inserting copies/loads. In the case
2724 // of tail call optimization arguments are handle later.
2725 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2726 DAG.getSubtarget().getRegisterInfo());
2727 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2728 // Skip inalloca arguments, they have already been written.
2729 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2730 if (Flags.isInAlloca())
2733 CCValAssign &VA = ArgLocs[i];
2734 EVT RegVT = VA.getLocVT();
2735 SDValue Arg = OutVals[i];
2736 bool isByVal = Flags.isByVal();
2738 // Promote the value if needed.
2739 switch (VA.getLocInfo()) {
2740 default: llvm_unreachable("Unknown loc info!");
2741 case CCValAssign::Full: break;
2742 case CCValAssign::SExt:
2743 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2745 case CCValAssign::ZExt:
2746 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2748 case CCValAssign::AExt:
2749 if (RegVT.is128BitVector()) {
2750 // Special case: passing MMX values in XMM registers.
2751 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2752 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2753 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2755 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2757 case CCValAssign::BCvt:
2758 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2760 case CCValAssign::Indirect: {
2761 // Store the argument.
2762 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2763 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2764 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2765 MachinePointerInfo::getFixedStack(FI),
2772 if (VA.isRegLoc()) {
2773 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2774 if (isVarArg && IsWin64) {
2775 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2776 // shadow reg if callee is a varargs function.
2777 unsigned ShadowReg = 0;
2778 switch (VA.getLocReg()) {
2779 case X86::XMM0: ShadowReg = X86::RCX; break;
2780 case X86::XMM1: ShadowReg = X86::RDX; break;
2781 case X86::XMM2: ShadowReg = X86::R8; break;
2782 case X86::XMM3: ShadowReg = X86::R9; break;
2785 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2787 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2788 assert(VA.isMemLoc());
2789 if (!StackPtr.getNode())
2790 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2792 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2793 dl, DAG, VA, Flags));
2797 if (!MemOpChains.empty())
2798 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2800 if (Subtarget->isPICStyleGOT()) {
2801 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2804 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2805 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2807 // If we are tail calling and generating PIC/GOT style code load the
2808 // address of the callee into ECX. The value in ecx is used as target of
2809 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2810 // for tail calls on PIC/GOT architectures. Normally we would just put the
2811 // address of GOT into ebx and then call target@PLT. But for tail calls
2812 // ebx would be restored (since ebx is callee saved) before jumping to the
2815 // Note: The actual moving to ECX is done further down.
2816 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2817 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2818 !G->getGlobal()->hasProtectedVisibility())
2819 Callee = LowerGlobalAddress(Callee, DAG);
2820 else if (isa<ExternalSymbolSDNode>(Callee))
2821 Callee = LowerExternalSymbol(Callee, DAG);
2825 if (Is64Bit && isVarArg && !IsWin64) {
2826 // From AMD64 ABI document:
2827 // For calls that may call functions that use varargs or stdargs
2828 // (prototype-less calls or calls to functions containing ellipsis (...) in
2829 // the declaration) %al is used as hidden argument to specify the number
2830 // of SSE registers used. The contents of %al do not need to match exactly
2831 // the number of registers, but must be an ubound on the number of SSE
2832 // registers used and is in the range 0 - 8 inclusive.
2834 // Count the number of XMM registers allocated.
2835 static const MCPhysReg XMMArgRegs[] = {
2836 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2837 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2839 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2840 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2841 && "SSE registers cannot be used when SSE is disabled");
2843 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2844 DAG.getConstant(NumXMMRegs, MVT::i8)));
2847 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2848 // don't need this because the eligibility check rejects calls that require
2849 // shuffling arguments passed in memory.
2850 if (!IsSibcall && isTailCall) {
2851 // Force all the incoming stack arguments to be loaded from the stack
2852 // before any new outgoing arguments are stored to the stack, because the
2853 // outgoing stack slots may alias the incoming argument stack slots, and
2854 // the alias isn't otherwise explicit. This is slightly more conservative
2855 // than necessary, because it means that each store effectively depends
2856 // on every argument instead of just those arguments it would clobber.
2857 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2859 SmallVector<SDValue, 8> MemOpChains2;
2862 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2863 CCValAssign &VA = ArgLocs[i];
2866 assert(VA.isMemLoc());
2867 SDValue Arg = OutVals[i];
2868 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2869 // Skip inalloca arguments. They don't require any work.
2870 if (Flags.isInAlloca())
2872 // Create frame index.
2873 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2874 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2875 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2876 FIN = DAG.getFrameIndex(FI, getPointerTy());
2878 if (Flags.isByVal()) {
2879 // Copy relative to framepointer.
2880 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2881 if (!StackPtr.getNode())
2882 StackPtr = DAG.getCopyFromReg(Chain, dl,
2883 RegInfo->getStackRegister(),
2885 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2887 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2891 // Store relative to framepointer.
2892 MemOpChains2.push_back(
2893 DAG.getStore(ArgChain, dl, Arg, FIN,
2894 MachinePointerInfo::getFixedStack(FI),
2899 if (!MemOpChains2.empty())
2900 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2902 // Store the return address to the appropriate stack slot.
2903 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2904 getPointerTy(), RegInfo->getSlotSize(),
2908 // Build a sequence of copy-to-reg nodes chained together with token chain
2909 // and flag operands which copy the outgoing args into registers.
2911 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2912 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2913 RegsToPass[i].second, InFlag);
2914 InFlag = Chain.getValue(1);
2917 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2918 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2919 // In the 64-bit large code model, we have to make all calls
2920 // through a register, since the call instruction's 32-bit
2921 // pc-relative offset may not be large enough to hold the whole
2923 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2924 // If the callee is a GlobalAddress node (quite common, every direct call
2925 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2928 // We should use extra load for direct calls to dllimported functions in
2930 const GlobalValue *GV = G->getGlobal();
2931 if (!GV->hasDLLImportStorageClass()) {
2932 unsigned char OpFlags = 0;
2933 bool ExtraLoad = false;
2934 unsigned WrapperKind = ISD::DELETED_NODE;
2936 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2937 // external symbols most go through the PLT in PIC mode. If the symbol
2938 // has hidden or protected visibility, or if it is static or local, then
2939 // we don't need to use the PLT - we can directly call it.
2940 if (Subtarget->isTargetELF() &&
2941 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2942 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2943 OpFlags = X86II::MO_PLT;
2944 } else if (Subtarget->isPICStyleStubAny() &&
2945 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2946 (!Subtarget->getTargetTriple().isMacOSX() ||
2947 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2948 // PC-relative references to external symbols should go through $stub,
2949 // unless we're building with the leopard linker or later, which
2950 // automatically synthesizes these stubs.
2951 OpFlags = X86II::MO_DARWIN_STUB;
2952 } else if (Subtarget->isPICStyleRIPRel() &&
2953 isa<Function>(GV) &&
2954 cast<Function>(GV)->getAttributes().
2955 hasAttribute(AttributeSet::FunctionIndex,
2956 Attribute::NonLazyBind)) {
2957 // If the function is marked as non-lazy, generate an indirect call
2958 // which loads from the GOT directly. This avoids runtime overhead
2959 // at the cost of eager binding (and one extra byte of encoding).
2960 OpFlags = X86II::MO_GOTPCREL;
2961 WrapperKind = X86ISD::WrapperRIP;
2965 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2966 G->getOffset(), OpFlags);
2968 // Add a wrapper if needed.
2969 if (WrapperKind != ISD::DELETED_NODE)
2970 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2971 // Add extra indirection if needed.
2973 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2974 MachinePointerInfo::getGOT(),
2975 false, false, false, 0);
2977 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2978 unsigned char OpFlags = 0;
2980 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2981 // external symbols should go through the PLT.
2982 if (Subtarget->isTargetELF() &&
2983 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2984 OpFlags = X86II::MO_PLT;
2985 } else if (Subtarget->isPICStyleStubAny() &&
2986 (!Subtarget->getTargetTriple().isMacOSX() ||
2987 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2988 // PC-relative references to external symbols should go through $stub,
2989 // unless we're building with the leopard linker or later, which
2990 // automatically synthesizes these stubs.
2991 OpFlags = X86II::MO_DARWIN_STUB;
2994 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2998 // Returns a chain & a flag for retval copy to use.
2999 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3000 SmallVector<SDValue, 8> Ops;
3002 if (!IsSibcall && isTailCall) {
3003 Chain = DAG.getCALLSEQ_END(Chain,
3004 DAG.getIntPtrConstant(NumBytesToPop, true),
3005 DAG.getIntPtrConstant(0, true), InFlag, dl);
3006 InFlag = Chain.getValue(1);
3009 Ops.push_back(Chain);
3010 Ops.push_back(Callee);
3013 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3015 // Add argument registers to the end of the list so that they are known live
3017 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3018 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3019 RegsToPass[i].second.getValueType()));
3021 // Add a register mask operand representing the call-preserved registers.
3022 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3023 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3024 assert(Mask && "Missing call preserved mask for calling convention");
3025 Ops.push_back(DAG.getRegisterMask(Mask));
3027 if (InFlag.getNode())
3028 Ops.push_back(InFlag);
3032 //// If this is the first return lowered for this function, add the regs
3033 //// to the liveout set for the function.
3034 // This isn't right, although it's probably harmless on x86; liveouts
3035 // should be computed from returns not tail calls. Consider a void
3036 // function making a tail call to a function returning int.
3037 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3040 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3041 InFlag = Chain.getValue(1);
3043 // Create the CALLSEQ_END node.
3044 unsigned NumBytesForCalleeToPop;
3045 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3046 DAG.getTarget().Options.GuaranteedTailCallOpt))
3047 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3048 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3049 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3050 SR == StackStructReturn)
3051 // If this is a call to a struct-return function, the callee
3052 // pops the hidden struct pointer, so we have to push it back.
3053 // This is common for Darwin/X86, Linux & Mingw32 targets.
3054 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3055 NumBytesForCalleeToPop = 4;
3057 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3059 // Returns a flag for retval copy to use.
3061 Chain = DAG.getCALLSEQ_END(Chain,
3062 DAG.getIntPtrConstant(NumBytesToPop, true),
3063 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3066 InFlag = Chain.getValue(1);
3069 // Handle result values, copying them out of physregs into vregs that we
3071 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3072 Ins, dl, DAG, InVals);
3075 //===----------------------------------------------------------------------===//
3076 // Fast Calling Convention (tail call) implementation
3077 //===----------------------------------------------------------------------===//
3079 // Like std call, callee cleans arguments, convention except that ECX is
3080 // reserved for storing the tail called function address. Only 2 registers are
3081 // free for argument passing (inreg). Tail call optimization is performed
3083 // * tailcallopt is enabled
3084 // * caller/callee are fastcc
3085 // On X86_64 architecture with GOT-style position independent code only local
3086 // (within module) calls are supported at the moment.
3087 // To keep the stack aligned according to platform abi the function
3088 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3089 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3090 // If a tail called function callee has more arguments than the caller the
3091 // caller needs to make sure that there is room to move the RETADDR to. This is
3092 // achieved by reserving an area the size of the argument delta right after the
3093 // original RETADDR, but before the saved framepointer or the spilled registers
3094 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3106 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3107 /// for a 16 byte align requirement.
3109 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3110 SelectionDAG& DAG) const {
3111 MachineFunction &MF = DAG.getMachineFunction();
3112 const TargetMachine &TM = MF.getTarget();
3113 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3114 TM.getSubtargetImpl()->getRegisterInfo());
3115 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3116 unsigned StackAlignment = TFI.getStackAlignment();
3117 uint64_t AlignMask = StackAlignment - 1;
3118 int64_t Offset = StackSize;
3119 unsigned SlotSize = RegInfo->getSlotSize();
3120 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3121 // Number smaller than 12 so just add the difference.
3122 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3124 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3125 Offset = ((~AlignMask) & Offset) + StackAlignment +
3126 (StackAlignment-SlotSize);
3131 /// MatchingStackOffset - Return true if the given stack call argument is
3132 /// already available in the same position (relatively) of the caller's
3133 /// incoming argument stack.
3135 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3136 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3137 const X86InstrInfo *TII) {
3138 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3140 if (Arg.getOpcode() == ISD::CopyFromReg) {
3141 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3142 if (!TargetRegisterInfo::isVirtualRegister(VR))
3144 MachineInstr *Def = MRI->getVRegDef(VR);
3147 if (!Flags.isByVal()) {
3148 if (!TII->isLoadFromStackSlot(Def, FI))
3151 unsigned Opcode = Def->getOpcode();
3152 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3153 Def->getOperand(1).isFI()) {
3154 FI = Def->getOperand(1).getIndex();
3155 Bytes = Flags.getByValSize();
3159 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3160 if (Flags.isByVal())
3161 // ByVal argument is passed in as a pointer but it's now being
3162 // dereferenced. e.g.
3163 // define @foo(%struct.X* %A) {
3164 // tail call @bar(%struct.X* byval %A)
3167 SDValue Ptr = Ld->getBasePtr();
3168 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3171 FI = FINode->getIndex();
3172 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3173 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3174 FI = FINode->getIndex();
3175 Bytes = Flags.getByValSize();
3179 assert(FI != INT_MAX);
3180 if (!MFI->isFixedObjectIndex(FI))
3182 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3185 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3186 /// for tail call optimization. Targets which want to do tail call
3187 /// optimization should implement this function.
3189 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3190 CallingConv::ID CalleeCC,
3192 bool isCalleeStructRet,
3193 bool isCallerStructRet,
3195 const SmallVectorImpl<ISD::OutputArg> &Outs,
3196 const SmallVectorImpl<SDValue> &OutVals,
3197 const SmallVectorImpl<ISD::InputArg> &Ins,
3198 SelectionDAG &DAG) const {
3199 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3202 // If -tailcallopt is specified, make fastcc functions tail-callable.
3203 const MachineFunction &MF = DAG.getMachineFunction();
3204 const Function *CallerF = MF.getFunction();
3206 // If the function return type is x86_fp80 and the callee return type is not,
3207 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3208 // perform a tailcall optimization here.
3209 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3212 CallingConv::ID CallerCC = CallerF->getCallingConv();
3213 bool CCMatch = CallerCC == CalleeCC;
3214 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3215 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3217 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3218 if (IsTailCallConvention(CalleeCC) && CCMatch)
3223 // Look for obvious safe cases to perform tail call optimization that do not
3224 // require ABI changes. This is what gcc calls sibcall.
3226 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3227 // emit a special epilogue.
3228 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3229 DAG.getSubtarget().getRegisterInfo());
3230 if (RegInfo->needsStackRealignment(MF))
3233 // Also avoid sibcall optimization if either caller or callee uses struct
3234 // return semantics.
3235 if (isCalleeStructRet || isCallerStructRet)
3238 // An stdcall/thiscall caller is expected to clean up its arguments; the
3239 // callee isn't going to do that.
3240 // FIXME: this is more restrictive than needed. We could produce a tailcall
3241 // when the stack adjustment matches. For example, with a thiscall that takes
3242 // only one argument.
3243 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3244 CallerCC == CallingConv::X86_ThisCall))
3247 // Do not sibcall optimize vararg calls unless all arguments are passed via
3249 if (isVarArg && !Outs.empty()) {
3251 // Optimizing for varargs on Win64 is unlikely to be safe without
3252 // additional testing.
3253 if (IsCalleeWin64 || IsCallerWin64)
3256 SmallVector<CCValAssign, 16> ArgLocs;
3257 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3260 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3261 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3262 if (!ArgLocs[i].isRegLoc())
3266 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3267 // stack. Therefore, if it's not used by the call it is not safe to optimize
3268 // this into a sibcall.
3269 bool Unused = false;
3270 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3277 SmallVector<CCValAssign, 16> RVLocs;
3278 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3280 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3281 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3282 CCValAssign &VA = RVLocs[i];
3283 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3288 // If the calling conventions do not match, then we'd better make sure the
3289 // results are returned in the same way as what the caller expects.
3291 SmallVector<CCValAssign, 16> RVLocs1;
3292 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3294 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3296 SmallVector<CCValAssign, 16> RVLocs2;
3297 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3299 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3301 if (RVLocs1.size() != RVLocs2.size())
3303 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3304 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3306 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3308 if (RVLocs1[i].isRegLoc()) {
3309 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3312 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3318 // If the callee takes no arguments then go on to check the results of the
3320 if (!Outs.empty()) {
3321 // Check if stack adjustment is needed. For now, do not do this if any
3322 // argument is passed on the stack.
3323 SmallVector<CCValAssign, 16> ArgLocs;
3324 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3327 // Allocate shadow area for Win64
3329 CCInfo.AllocateStack(32, 8);
3331 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3332 if (CCInfo.getNextStackOffset()) {
3333 MachineFunction &MF = DAG.getMachineFunction();
3334 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3337 // Check if the arguments are already laid out in the right way as
3338 // the caller's fixed stack objects.
3339 MachineFrameInfo *MFI = MF.getFrameInfo();
3340 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3341 const X86InstrInfo *TII =
3342 static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3343 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3344 CCValAssign &VA = ArgLocs[i];
3345 SDValue Arg = OutVals[i];
3346 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3347 if (VA.getLocInfo() == CCValAssign::Indirect)
3349 if (!VA.isRegLoc()) {
3350 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3357 // If the tailcall address may be in a register, then make sure it's
3358 // possible to register allocate for it. In 32-bit, the call address can
3359 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3360 // callee-saved registers are restored. These happen to be the same
3361 // registers used to pass 'inreg' arguments so watch out for those.
3362 if (!Subtarget->is64Bit() &&
3363 ((!isa<GlobalAddressSDNode>(Callee) &&
3364 !isa<ExternalSymbolSDNode>(Callee)) ||
3365 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3366 unsigned NumInRegs = 0;
3367 // In PIC we need an extra register to formulate the address computation
3369 unsigned MaxInRegs =
3370 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3372 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3373 CCValAssign &VA = ArgLocs[i];
3376 unsigned Reg = VA.getLocReg();
3379 case X86::EAX: case X86::EDX: case X86::ECX:
3380 if (++NumInRegs == MaxInRegs)
3392 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3393 const TargetLibraryInfo *libInfo) const {
3394 return X86::createFastISel(funcInfo, libInfo);
3397 //===----------------------------------------------------------------------===//
3398 // Other Lowering Hooks
3399 //===----------------------------------------------------------------------===//
3401 static bool MayFoldLoad(SDValue Op) {
3402 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3405 static bool MayFoldIntoStore(SDValue Op) {
3406 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3409 static bool isTargetShuffle(unsigned Opcode) {
3411 default: return false;
3412 case X86ISD::PSHUFB:
3413 case X86ISD::PSHUFD:
3414 case X86ISD::PSHUFHW:
3415 case X86ISD::PSHUFLW:
3417 case X86ISD::PALIGNR:
3418 case X86ISD::MOVLHPS:
3419 case X86ISD::MOVLHPD:
3420 case X86ISD::MOVHLPS:
3421 case X86ISD::MOVLPS:
3422 case X86ISD::MOVLPD:
3423 case X86ISD::MOVSHDUP:
3424 case X86ISD::MOVSLDUP:
3425 case X86ISD::MOVDDUP:
3428 case X86ISD::UNPCKL:
3429 case X86ISD::UNPCKH:
3430 case X86ISD::VPERMILP:
3431 case X86ISD::VPERM2X128:
3432 case X86ISD::VPERMI:
3437 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3438 SDValue V1, SelectionDAG &DAG) {
3440 default: llvm_unreachable("Unknown x86 shuffle node");
3441 case X86ISD::MOVSHDUP:
3442 case X86ISD::MOVSLDUP:
3443 case X86ISD::MOVDDUP:
3444 return DAG.getNode(Opc, dl, VT, V1);
3448 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3449 SDValue V1, unsigned TargetMask,
3450 SelectionDAG &DAG) {
3452 default: llvm_unreachable("Unknown x86 shuffle node");
3453 case X86ISD::PSHUFD:
3454 case X86ISD::PSHUFHW:
3455 case X86ISD::PSHUFLW:
3456 case X86ISD::VPERMILP:
3457 case X86ISD::VPERMI:
3458 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3462 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3463 SDValue V1, SDValue V2, unsigned TargetMask,
3464 SelectionDAG &DAG) {
3466 default: llvm_unreachable("Unknown x86 shuffle node");
3467 case X86ISD::PALIGNR:
3468 case X86ISD::VALIGN:
3470 case X86ISD::VPERM2X128:
3471 return DAG.getNode(Opc, dl, VT, V1, V2,
3472 DAG.getConstant(TargetMask, MVT::i8));
3476 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3477 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3479 default: llvm_unreachable("Unknown x86 shuffle node");
3480 case X86ISD::MOVLHPS:
3481 case X86ISD::MOVLHPD:
3482 case X86ISD::MOVHLPS:
3483 case X86ISD::MOVLPS:
3484 case X86ISD::MOVLPD:
3487 case X86ISD::UNPCKL:
3488 case X86ISD::UNPCKH:
3489 return DAG.getNode(Opc, dl, VT, V1, V2);
3493 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3494 MachineFunction &MF = DAG.getMachineFunction();
3495 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3496 DAG.getSubtarget().getRegisterInfo());
3497 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3498 int ReturnAddrIndex = FuncInfo->getRAIndex();
3500 if (ReturnAddrIndex == 0) {
3501 // Set up a frame object for the return address.
3502 unsigned SlotSize = RegInfo->getSlotSize();
3503 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3506 FuncInfo->setRAIndex(ReturnAddrIndex);
3509 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3512 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3513 bool hasSymbolicDisplacement) {
3514 // Offset should fit into 32 bit immediate field.
3515 if (!isInt<32>(Offset))
3518 // If we don't have a symbolic displacement - we don't have any extra
3520 if (!hasSymbolicDisplacement)
3523 // FIXME: Some tweaks might be needed for medium code model.
3524 if (M != CodeModel::Small && M != CodeModel::Kernel)
3527 // For small code model we assume that latest object is 16MB before end of 31
3528 // bits boundary. We may also accept pretty large negative constants knowing
3529 // that all objects are in the positive half of address space.
3530 if (M == CodeModel::Small && Offset < 16*1024*1024)
3533 // For kernel code model we know that all object resist in the negative half
3534 // of 32bits address space. We may not accept negative offsets, since they may
3535 // be just off and we may accept pretty large positive ones.
3536 if (M == CodeModel::Kernel && Offset > 0)
3542 /// isCalleePop - Determines whether the callee is required to pop its
3543 /// own arguments. Callee pop is necessary to support tail calls.
3544 bool X86::isCalleePop(CallingConv::ID CallingConv,
3545 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3549 switch (CallingConv) {
3552 case CallingConv::X86_StdCall:
3554 case CallingConv::X86_FastCall:
3556 case CallingConv::X86_ThisCall:
3558 case CallingConv::Fast:
3560 case CallingConv::GHC:
3562 case CallingConv::HiPE:
3567 /// \brief Return true if the condition is an unsigned comparison operation.
3568 static bool isX86CCUnsigned(unsigned X86CC) {
3570 default: llvm_unreachable("Invalid integer condition!");
3571 case X86::COND_E: return true;
3572 case X86::COND_G: return false;
3573 case X86::COND_GE: return false;
3574 case X86::COND_L: return false;
3575 case X86::COND_LE: return false;
3576 case X86::COND_NE: return true;
3577 case X86::COND_B: return true;
3578 case X86::COND_A: return true;
3579 case X86::COND_BE: return true;
3580 case X86::COND_AE: return true;
3582 llvm_unreachable("covered switch fell through?!");
3585 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3586 /// specific condition code, returning the condition code and the LHS/RHS of the
3587 /// comparison to make.
3588 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3589 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3591 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3592 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3593 // X > -1 -> X == 0, jump !sign.
3594 RHS = DAG.getConstant(0, RHS.getValueType());
3595 return X86::COND_NS;
3597 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3598 // X < 0 -> X == 0, jump on sign.
3601 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3603 RHS = DAG.getConstant(0, RHS.getValueType());
3604 return X86::COND_LE;
3608 switch (SetCCOpcode) {
3609 default: llvm_unreachable("Invalid integer condition!");
3610 case ISD::SETEQ: return X86::COND_E;
3611 case ISD::SETGT: return X86::COND_G;
3612 case ISD::SETGE: return X86::COND_GE;
3613 case ISD::SETLT: return X86::COND_L;
3614 case ISD::SETLE: return X86::COND_LE;
3615 case ISD::SETNE: return X86::COND_NE;
3616 case ISD::SETULT: return X86::COND_B;
3617 case ISD::SETUGT: return X86::COND_A;
3618 case ISD::SETULE: return X86::COND_BE;
3619 case ISD::SETUGE: return X86::COND_AE;
3623 // First determine if it is required or is profitable to flip the operands.
3625 // If LHS is a foldable load, but RHS is not, flip the condition.
3626 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3627 !ISD::isNON_EXTLoad(RHS.getNode())) {
3628 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3629 std::swap(LHS, RHS);
3632 switch (SetCCOpcode) {
3638 std::swap(LHS, RHS);
3642 // On a floating point condition, the flags are set as follows:
3644 // 0 | 0 | 0 | X > Y
3645 // 0 | 0 | 1 | X < Y
3646 // 1 | 0 | 0 | X == Y
3647 // 1 | 1 | 1 | unordered
3648 switch (SetCCOpcode) {
3649 default: llvm_unreachable("Condcode should be pre-legalized away");
3651 case ISD::SETEQ: return X86::COND_E;
3652 case ISD::SETOLT: // flipped
3654 case ISD::SETGT: return X86::COND_A;
3655 case ISD::SETOLE: // flipped
3657 case ISD::SETGE: return X86::COND_AE;
3658 case ISD::SETUGT: // flipped
3660 case ISD::SETLT: return X86::COND_B;
3661 case ISD::SETUGE: // flipped
3663 case ISD::SETLE: return X86::COND_BE;
3665 case ISD::SETNE: return X86::COND_NE;
3666 case ISD::SETUO: return X86::COND_P;
3667 case ISD::SETO: return X86::COND_NP;
3669 case ISD::SETUNE: return X86::COND_INVALID;
3673 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3674 /// code. Current x86 isa includes the following FP cmov instructions:
3675 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3676 static bool hasFPCMov(unsigned X86CC) {
3692 /// isFPImmLegal - Returns true if the target can instruction select the
3693 /// specified FP immediate natively. If false, the legalizer will
3694 /// materialize the FP immediate as a load from a constant pool.
3695 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3696 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3697 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3703 /// \brief Returns true if it is beneficial to convert a load of a constant
3704 /// to just the constant itself.
3705 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3707 assert(Ty->isIntegerTy());
3709 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3710 if (BitSize == 0 || BitSize > 64)
3715 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3716 /// the specified range (L, H].
3717 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3718 return (Val < 0) || (Val >= Low && Val < Hi);
3721 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3722 /// specified value.
3723 static bool isUndefOrEqual(int Val, int CmpVal) {
3724 return (Val < 0 || Val == CmpVal);
3727 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3728 /// from position Pos and ending in Pos+Size, falls within the specified
3729 /// sequential range (L, L+Pos]. or is undef.
3730 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3731 unsigned Pos, unsigned Size, int Low) {
3732 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3733 if (!isUndefOrEqual(Mask[i], Low))
3738 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3739 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3740 /// the second operand.
3741 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3742 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3743 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3744 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3745 return (Mask[0] < 2 && Mask[1] < 2);
3749 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3750 /// is suitable for input to PSHUFHW.
3751 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3752 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3755 // Lower quadword copied in order or undef.
3756 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3759 // Upper quadword shuffled.
3760 for (unsigned i = 4; i != 8; ++i)
3761 if (!isUndefOrInRange(Mask[i], 4, 8))
3764 if (VT == MVT::v16i16) {
3765 // Lower quadword copied in order or undef.
3766 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3769 // Upper quadword shuffled.
3770 for (unsigned i = 12; i != 16; ++i)
3771 if (!isUndefOrInRange(Mask[i], 12, 16))
3778 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3779 /// is suitable for input to PSHUFLW.
3780 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3781 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3784 // Upper quadword copied in order.
3785 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3788 // Lower quadword shuffled.
3789 for (unsigned i = 0; i != 4; ++i)
3790 if (!isUndefOrInRange(Mask[i], 0, 4))
3793 if (VT == MVT::v16i16) {
3794 // Upper quadword copied in order.
3795 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3798 // Lower quadword shuffled.
3799 for (unsigned i = 8; i != 12; ++i)
3800 if (!isUndefOrInRange(Mask[i], 8, 12))
3807 /// \brief Return true if the mask specifies a shuffle of elements that is
3808 /// suitable for input to intralane (palignr) or interlane (valign) vector
3810 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3811 unsigned NumElts = VT.getVectorNumElements();
3812 unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3813 unsigned NumLaneElts = NumElts/NumLanes;
3815 // Do not handle 64-bit element shuffles with palignr.
3816 if (NumLaneElts == 2)
3819 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3821 for (i = 0; i != NumLaneElts; ++i) {
3826 // Lane is all undef, go to next lane
3827 if (i == NumLaneElts)
3830 int Start = Mask[i+l];
3832 // Make sure its in this lane in one of the sources
3833 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3834 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3837 // If not lane 0, then we must match lane 0
3838 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3841 // Correct second source to be contiguous with first source
3842 if (Start >= (int)NumElts)
3843 Start -= NumElts - NumLaneElts;
3845 // Make sure we're shifting in the right direction.
3846 if (Start <= (int)(i+l))
3851 // Check the rest of the elements to see if they are consecutive.
3852 for (++i; i != NumLaneElts; ++i) {
3853 int Idx = Mask[i+l];
3855 // Make sure its in this lane
3856 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3857 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3860 // If not lane 0, then we must match lane 0
3861 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3864 if (Idx >= (int)NumElts)
3865 Idx -= NumElts - NumLaneElts;
3867 if (!isUndefOrEqual(Idx, Start+i))
3876 /// \brief Return true if the node specifies a shuffle of elements that is
3877 /// suitable for input to PALIGNR.
3878 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3879 const X86Subtarget *Subtarget) {
3880 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3881 (VT.is256BitVector() && !Subtarget->hasInt256()) ||
3882 VT.is512BitVector())
3883 // FIXME: Add AVX512BW.
3886 return isAlignrMask(Mask, VT, false);
3889 /// \brief Return true if the node specifies a shuffle of elements that is
3890 /// suitable for input to VALIGN.
3891 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
3892 const X86Subtarget *Subtarget) {
3893 // FIXME: Add AVX512VL.
3894 if (!VT.is512BitVector() || !Subtarget->hasAVX512())
3896 return isAlignrMask(Mask, VT, true);
3899 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3900 /// the two vector operands have swapped position.
3901 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3902 unsigned NumElems) {
3903 for (unsigned i = 0; i != NumElems; ++i) {
3907 else if (idx < (int)NumElems)
3908 Mask[i] = idx + NumElems;
3910 Mask[i] = idx - NumElems;
3914 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3915 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3916 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3917 /// reverse of what x86 shuffles want.
3918 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3920 unsigned NumElems = VT.getVectorNumElements();
3921 unsigned NumLanes = VT.getSizeInBits()/128;
3922 unsigned NumLaneElems = NumElems/NumLanes;
3924 if (NumLaneElems != 2 && NumLaneElems != 4)
3927 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3928 bool symetricMaskRequired =
3929 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3931 // VSHUFPSY divides the resulting vector into 4 chunks.
3932 // The sources are also splitted into 4 chunks, and each destination
3933 // chunk must come from a different source chunk.
3935 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3936 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3938 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3939 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3941 // VSHUFPDY divides the resulting vector into 4 chunks.
3942 // The sources are also splitted into 4 chunks, and each destination
3943 // chunk must come from a different source chunk.
3945 // SRC1 => X3 X2 X1 X0
3946 // SRC2 => Y3 Y2 Y1 Y0
3948 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3950 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3951 unsigned HalfLaneElems = NumLaneElems/2;
3952 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3953 for (unsigned i = 0; i != NumLaneElems; ++i) {
3954 int Idx = Mask[i+l];
3955 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3956 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3958 // For VSHUFPSY, the mask of the second half must be the same as the
3959 // first but with the appropriate offsets. This works in the same way as
3960 // VPERMILPS works with masks.
3961 if (!symetricMaskRequired || Idx < 0)
3963 if (MaskVal[i] < 0) {
3964 MaskVal[i] = Idx - l;
3967 if ((signed)(Idx - l) != MaskVal[i])
3975 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3976 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3977 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3978 if (!VT.is128BitVector())
3981 unsigned NumElems = VT.getVectorNumElements();
3986 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3987 return isUndefOrEqual(Mask[0], 6) &&
3988 isUndefOrEqual(Mask[1], 7) &&
3989 isUndefOrEqual(Mask[2], 2) &&
3990 isUndefOrEqual(Mask[3], 3);
3993 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3994 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3996 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3997 if (!VT.is128BitVector())
4000 unsigned NumElems = VT.getVectorNumElements();
4005 return isUndefOrEqual(Mask[0], 2) &&
4006 isUndefOrEqual(Mask[1], 3) &&
4007 isUndefOrEqual(Mask[2], 2) &&
4008 isUndefOrEqual(Mask[3], 3);
4011 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4012 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4013 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4014 if (!VT.is128BitVector())
4017 unsigned NumElems = VT.getVectorNumElements();
4019 if (NumElems != 2 && NumElems != 4)
4022 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4023 if (!isUndefOrEqual(Mask[i], i + NumElems))
4026 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4027 if (!isUndefOrEqual(Mask[i], i))
4033 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4034 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4035 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4036 if (!VT.is128BitVector())
4039 unsigned NumElems = VT.getVectorNumElements();
4041 if (NumElems != 2 && NumElems != 4)
4044 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4045 if (!isUndefOrEqual(Mask[i], i))
4048 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4049 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4055 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4056 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4057 /// i. e: If all but one element come from the same vector.
4058 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4059 // TODO: Deal with AVX's VINSERTPS
4060 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4063 unsigned CorrectPosV1 = 0;
4064 unsigned CorrectPosV2 = 0;
4065 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4066 if (Mask[i] == -1) {
4074 else if (Mask[i] == i + 4)
4078 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4079 // We have 3 elements (undefs count as elements from any vector) from one
4080 // vector, and one from another.
4087 // Some special combinations that can be optimized.
4090 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4091 SelectionDAG &DAG) {
4092 MVT VT = SVOp->getSimpleValueType(0);
4095 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4098 ArrayRef<int> Mask = SVOp->getMask();
4100 // These are the special masks that may be optimized.
4101 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4102 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4103 bool MatchEvenMask = true;
4104 bool MatchOddMask = true;
4105 for (int i=0; i<8; ++i) {
4106 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4107 MatchEvenMask = false;
4108 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4109 MatchOddMask = false;
4112 if (!MatchEvenMask && !MatchOddMask)
4115 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4117 SDValue Op0 = SVOp->getOperand(0);
4118 SDValue Op1 = SVOp->getOperand(1);
4120 if (MatchEvenMask) {
4121 // Shift the second operand right to 32 bits.
4122 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4123 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4125 // Shift the first operand left to 32 bits.
4126 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4127 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4129 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4130 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4133 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4134 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4135 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4136 bool HasInt256, bool V2IsSplat = false) {
4138 assert(VT.getSizeInBits() >= 128 &&
4139 "Unsupported vector type for unpckl");
4141 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4143 unsigned NumOf256BitLanes;
4144 unsigned NumElts = VT.getVectorNumElements();
4145 if (VT.is256BitVector()) {
4146 if (NumElts != 4 && NumElts != 8 &&
4147 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4150 NumOf256BitLanes = 1;
4151 } else if (VT.is512BitVector()) {
4152 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4153 "Unsupported vector type for unpckh");
4155 NumOf256BitLanes = 2;
4158 NumOf256BitLanes = 1;
4161 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4162 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4164 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4165 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4166 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4167 int BitI = Mask[l256*NumEltsInStride+l+i];
4168 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4169 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4171 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4173 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4181 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4182 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4183 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4184 bool HasInt256, bool V2IsSplat = false) {
4185 assert(VT.getSizeInBits() >= 128 &&
4186 "Unsupported vector type for unpckh");
4188 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4190 unsigned NumOf256BitLanes;
4191 unsigned NumElts = VT.getVectorNumElements();
4192 if (VT.is256BitVector()) {
4193 if (NumElts != 4 && NumElts != 8 &&
4194 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4197 NumOf256BitLanes = 1;
4198 } else if (VT.is512BitVector()) {
4199 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4200 "Unsupported vector type for unpckh");
4202 NumOf256BitLanes = 2;
4205 NumOf256BitLanes = 1;
4208 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4209 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4211 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4212 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4213 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4214 int BitI = Mask[l256*NumEltsInStride+l+i];
4215 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4216 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4218 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4220 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4228 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4229 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4231 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4232 unsigned NumElts = VT.getVectorNumElements();
4233 bool Is256BitVec = VT.is256BitVector();
4235 if (VT.is512BitVector())
4237 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4238 "Unsupported vector type for unpckh");
4240 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4241 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4244 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4245 // FIXME: Need a better way to get rid of this, there's no latency difference
4246 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4247 // the former later. We should also remove the "_undef" special mask.
4248 if (NumElts == 4 && Is256BitVec)
4251 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4252 // independently on 128-bit lanes.
4253 unsigned NumLanes = VT.getSizeInBits()/128;
4254 unsigned NumLaneElts = NumElts/NumLanes;
4256 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4257 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4258 int BitI = Mask[l+i];
4259 int BitI1 = Mask[l+i+1];
4261 if (!isUndefOrEqual(BitI, j))
4263 if (!isUndefOrEqual(BitI1, j))
4271 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4272 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4274 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4275 unsigned NumElts = VT.getVectorNumElements();
4277 if (VT.is512BitVector())
4280 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4281 "Unsupported vector type for unpckh");
4283 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4284 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4287 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4288 // independently on 128-bit lanes.
4289 unsigned NumLanes = VT.getSizeInBits()/128;
4290 unsigned NumLaneElts = NumElts/NumLanes;
4292 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4293 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4294 int BitI = Mask[l+i];
4295 int BitI1 = Mask[l+i+1];
4296 if (!isUndefOrEqual(BitI, j))
4298 if (!isUndefOrEqual(BitI1, j))
4305 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4306 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4307 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4308 if (!VT.is512BitVector())
4311 unsigned NumElts = VT.getVectorNumElements();
4312 unsigned HalfSize = NumElts/2;
4313 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4314 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4319 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4320 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4328 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4329 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4330 /// MOVSD, and MOVD, i.e. setting the lowest element.
4331 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4332 if (VT.getVectorElementType().getSizeInBits() < 32)
4334 if (!VT.is128BitVector())
4337 unsigned NumElts = VT.getVectorNumElements();
4339 if (!isUndefOrEqual(Mask[0], NumElts))
4342 for (unsigned i = 1; i != NumElts; ++i)
4343 if (!isUndefOrEqual(Mask[i], i))
4349 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4350 /// as permutations between 128-bit chunks or halves. As an example: this
4352 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4353 /// The first half comes from the second half of V1 and the second half from the
4354 /// the second half of V2.
4355 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4356 if (!HasFp256 || !VT.is256BitVector())
4359 // The shuffle result is divided into half A and half B. In total the two
4360 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4361 // B must come from C, D, E or F.
4362 unsigned HalfSize = VT.getVectorNumElements()/2;
4363 bool MatchA = false, MatchB = false;
4365 // Check if A comes from one of C, D, E, F.
4366 for (unsigned Half = 0; Half != 4; ++Half) {
4367 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4373 // Check if B comes from one of C, D, E, F.
4374 for (unsigned Half = 0; Half != 4; ++Half) {
4375 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4381 return MatchA && MatchB;
4384 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4385 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4386 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4387 MVT VT = SVOp->getSimpleValueType(0);
4389 unsigned HalfSize = VT.getVectorNumElements()/2;
4391 unsigned FstHalf = 0, SndHalf = 0;
4392 for (unsigned i = 0; i < HalfSize; ++i) {
4393 if (SVOp->getMaskElt(i) > 0) {
4394 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4398 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4399 if (SVOp->getMaskElt(i) > 0) {
4400 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4405 return (FstHalf | (SndHalf << 4));
4408 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4409 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4410 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4414 unsigned NumElts = VT.getVectorNumElements();
4416 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4417 for (unsigned i = 0; i != NumElts; ++i) {
4420 Imm8 |= Mask[i] << (i*2);
4425 unsigned LaneSize = 4;
4426 SmallVector<int, 4> MaskVal(LaneSize, -1);
4428 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4429 for (unsigned i = 0; i != LaneSize; ++i) {
4430 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4434 if (MaskVal[i] < 0) {
4435 MaskVal[i] = Mask[i+l] - l;
4436 Imm8 |= MaskVal[i] << (i*2);
4439 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4446 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4447 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4448 /// Note that VPERMIL mask matching is different depending whether theunderlying
4449 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4450 /// to the same elements of the low, but to the higher half of the source.
4451 /// In VPERMILPD the two lanes could be shuffled independently of each other
4452 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4453 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4454 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4455 if (VT.getSizeInBits() < 256 || EltSize < 32)
4457 bool symetricMaskRequired = (EltSize == 32);
4458 unsigned NumElts = VT.getVectorNumElements();
4460 unsigned NumLanes = VT.getSizeInBits()/128;
4461 unsigned LaneSize = NumElts/NumLanes;
4462 // 2 or 4 elements in one lane
4464 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4465 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4466 for (unsigned i = 0; i != LaneSize; ++i) {
4467 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4469 if (symetricMaskRequired) {
4470 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4471 ExpectedMaskVal[i] = Mask[i+l] - l;
4474 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4482 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4483 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4484 /// element of vector 2 and the other elements to come from vector 1 in order.
4485 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4486 bool V2IsSplat = false, bool V2IsUndef = false) {
4487 if (!VT.is128BitVector())
4490 unsigned NumOps = VT.getVectorNumElements();
4491 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4494 if (!isUndefOrEqual(Mask[0], 0))
4497 for (unsigned i = 1; i != NumOps; ++i)
4498 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4499 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4500 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4506 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4507 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4508 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4509 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4510 const X86Subtarget *Subtarget) {
4511 if (!Subtarget->hasSSE3())
4514 unsigned NumElems = VT.getVectorNumElements();
4516 if ((VT.is128BitVector() && NumElems != 4) ||
4517 (VT.is256BitVector() && NumElems != 8) ||
4518 (VT.is512BitVector() && NumElems != 16))
4521 // "i+1" is the value the indexed mask element must have
4522 for (unsigned i = 0; i != NumElems; i += 2)
4523 if (!isUndefOrEqual(Mask[i], i+1) ||
4524 !isUndefOrEqual(Mask[i+1], i+1))
4530 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4531 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4532 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4533 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4534 const X86Subtarget *Subtarget) {
4535 if (!Subtarget->hasSSE3())
4538 unsigned NumElems = VT.getVectorNumElements();
4540 if ((VT.is128BitVector() && NumElems != 4) ||
4541 (VT.is256BitVector() && NumElems != 8) ||
4542 (VT.is512BitVector() && NumElems != 16))
4545 // "i" is the value the indexed mask element must have
4546 for (unsigned i = 0; i != NumElems; i += 2)
4547 if (!isUndefOrEqual(Mask[i], i) ||
4548 !isUndefOrEqual(Mask[i+1], i))
4554 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4555 /// specifies a shuffle of elements that is suitable for input to 256-bit
4556 /// version of MOVDDUP.
4557 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4558 if (!HasFp256 || !VT.is256BitVector())
4561 unsigned NumElts = VT.getVectorNumElements();
4565 for (unsigned i = 0; i != NumElts/2; ++i)
4566 if (!isUndefOrEqual(Mask[i], 0))
4568 for (unsigned i = NumElts/2; i != NumElts; ++i)
4569 if (!isUndefOrEqual(Mask[i], NumElts/2))
4574 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4575 /// specifies a shuffle of elements that is suitable for input to 128-bit
4576 /// version of MOVDDUP.
4577 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4578 if (!VT.is128BitVector())
4581 unsigned e = VT.getVectorNumElements() / 2;
4582 for (unsigned i = 0; i != e; ++i)
4583 if (!isUndefOrEqual(Mask[i], i))
4585 for (unsigned i = 0; i != e; ++i)
4586 if (!isUndefOrEqual(Mask[e+i], i))
4591 /// isVEXTRACTIndex - Return true if the specified
4592 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4593 /// suitable for instruction that extract 128 or 256 bit vectors
4594 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4595 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4596 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4599 // The index should be aligned on a vecWidth-bit boundary.
4601 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4603 MVT VT = N->getSimpleValueType(0);
4604 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4605 bool Result = (Index * ElSize) % vecWidth == 0;
4610 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4611 /// operand specifies a subvector insert that is suitable for input to
4612 /// insertion of 128 or 256-bit subvectors
4613 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4614 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4615 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4617 // The index should be aligned on a vecWidth-bit boundary.
4619 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4621 MVT VT = N->getSimpleValueType(0);
4622 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4623 bool Result = (Index * ElSize) % vecWidth == 0;
4628 bool X86::isVINSERT128Index(SDNode *N) {
4629 return isVINSERTIndex(N, 128);
4632 bool X86::isVINSERT256Index(SDNode *N) {
4633 return isVINSERTIndex(N, 256);
4636 bool X86::isVEXTRACT128Index(SDNode *N) {
4637 return isVEXTRACTIndex(N, 128);
4640 bool X86::isVEXTRACT256Index(SDNode *N) {
4641 return isVEXTRACTIndex(N, 256);
4644 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4645 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4646 /// Handles 128-bit and 256-bit.
4647 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4648 MVT VT = N->getSimpleValueType(0);
4650 assert((VT.getSizeInBits() >= 128) &&
4651 "Unsupported vector type for PSHUF/SHUFP");
4653 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4654 // independently on 128-bit lanes.
4655 unsigned NumElts = VT.getVectorNumElements();
4656 unsigned NumLanes = VT.getSizeInBits()/128;
4657 unsigned NumLaneElts = NumElts/NumLanes;
4659 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4660 "Only supports 2, 4 or 8 elements per lane");
4662 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4664 for (unsigned i = 0; i != NumElts; ++i) {
4665 int Elt = N->getMaskElt(i);
4666 if (Elt < 0) continue;
4667 Elt &= NumLaneElts - 1;
4668 unsigned ShAmt = (i << Shift) % 8;
4669 Mask |= Elt << ShAmt;
4675 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4676 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4677 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4678 MVT VT = N->getSimpleValueType(0);
4680 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4681 "Unsupported vector type for PSHUFHW");
4683 unsigned NumElts = VT.getVectorNumElements();
4686 for (unsigned l = 0; l != NumElts; l += 8) {
4687 // 8 nodes per lane, but we only care about the last 4.
4688 for (unsigned i = 0; i < 4; ++i) {
4689 int Elt = N->getMaskElt(l+i+4);
4690 if (Elt < 0) continue;
4691 Elt &= 0x3; // only 2-bits.
4692 Mask |= Elt << (i * 2);
4699 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4700 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4701 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4702 MVT VT = N->getSimpleValueType(0);
4704 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4705 "Unsupported vector type for PSHUFHW");
4707 unsigned NumElts = VT.getVectorNumElements();
4710 for (unsigned l = 0; l != NumElts; l += 8) {
4711 // 8 nodes per lane, but we only care about the first 4.
4712 for (unsigned i = 0; i < 4; ++i) {
4713 int Elt = N->getMaskElt(l+i);
4714 if (Elt < 0) continue;
4715 Elt &= 0x3; // only 2-bits
4716 Mask |= Elt << (i * 2);
4723 /// \brief Return the appropriate immediate to shuffle the specified
4724 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4725 /// VALIGN (if Interlane is true) instructions.
4726 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4728 MVT VT = SVOp->getSimpleValueType(0);
4729 unsigned EltSize = InterLane ? 1 :
4730 VT.getVectorElementType().getSizeInBits() >> 3;
4732 unsigned NumElts = VT.getVectorNumElements();
4733 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4734 unsigned NumLaneElts = NumElts/NumLanes;
4738 for (i = 0; i != NumElts; ++i) {
4739 Val = SVOp->getMaskElt(i);
4743 if (Val >= (int)NumElts)
4744 Val -= NumElts - NumLaneElts;
4746 assert(Val - i > 0 && "PALIGNR imm should be positive");
4747 return (Val - i) * EltSize;
4750 /// \brief Return the appropriate immediate to shuffle the specified
4751 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4752 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4753 return getShuffleAlignrImmediate(SVOp, false);
4756 /// \brief Return the appropriate immediate to shuffle the specified
4757 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4758 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4759 return getShuffleAlignrImmediate(SVOp, true);
4763 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4764 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4765 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4766 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4769 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4771 MVT VecVT = N->getOperand(0).getSimpleValueType();
4772 MVT ElVT = VecVT.getVectorElementType();
4774 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4775 return Index / NumElemsPerChunk;
4778 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4779 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4780 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4781 llvm_unreachable("Illegal insert subvector for VINSERT");
4784 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4786 MVT VecVT = N->getSimpleValueType(0);
4787 MVT ElVT = VecVT.getVectorElementType();
4789 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4790 return Index / NumElemsPerChunk;
4793 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4794 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4795 /// and VINSERTI128 instructions.
4796 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4797 return getExtractVEXTRACTImmediate(N, 128);
4800 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4801 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4802 /// and VINSERTI64x4 instructions.
4803 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4804 return getExtractVEXTRACTImmediate(N, 256);
4807 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4808 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4809 /// and VINSERTI128 instructions.
4810 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4811 return getInsertVINSERTImmediate(N, 128);
4814 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4815 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4816 /// and VINSERTI64x4 instructions.
4817 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4818 return getInsertVINSERTImmediate(N, 256);
4821 /// isZero - Returns true if Elt is a constant integer zero
4822 static bool isZero(SDValue V) {
4823 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4824 return C && C->isNullValue();
4827 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4829 bool X86::isZeroNode(SDValue Elt) {
4832 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4833 return CFP->getValueAPF().isPosZero();
4837 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4838 /// match movhlps. The lower half elements should come from upper half of
4839 /// V1 (and in order), and the upper half elements should come from the upper
4840 /// half of V2 (and in order).
4841 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4842 if (!VT.is128BitVector())
4844 if (VT.getVectorNumElements() != 4)
4846 for (unsigned i = 0, e = 2; i != e; ++i)
4847 if (!isUndefOrEqual(Mask[i], i+2))
4849 for (unsigned i = 2; i != 4; ++i)
4850 if (!isUndefOrEqual(Mask[i], i+4))
4855 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4856 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4858 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4859 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4861 N = N->getOperand(0).getNode();
4862 if (!ISD::isNON_EXTLoad(N))
4865 *LD = cast<LoadSDNode>(N);
4869 // Test whether the given value is a vector value which will be legalized
4871 static bool WillBeConstantPoolLoad(SDNode *N) {
4872 if (N->getOpcode() != ISD::BUILD_VECTOR)
4875 // Check for any non-constant elements.
4876 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4877 switch (N->getOperand(i).getNode()->getOpcode()) {
4879 case ISD::ConstantFP:
4886 // Vectors of all-zeros and all-ones are materialized with special
4887 // instructions rather than being loaded.
4888 return !ISD::isBuildVectorAllZeros(N) &&
4889 !ISD::isBuildVectorAllOnes(N);
4892 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4893 /// match movlp{s|d}. The lower half elements should come from lower half of
4894 /// V1 (and in order), and the upper half elements should come from the upper
4895 /// half of V2 (and in order). And since V1 will become the source of the
4896 /// MOVLP, it must be either a vector load or a scalar load to vector.
4897 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4898 ArrayRef<int> Mask, MVT VT) {
4899 if (!VT.is128BitVector())
4902 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4904 // Is V2 is a vector load, don't do this transformation. We will try to use
4905 // load folding shufps op.
4906 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4909 unsigned NumElems = VT.getVectorNumElements();
4911 if (NumElems != 2 && NumElems != 4)
4913 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4914 if (!isUndefOrEqual(Mask[i], i))
4916 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4917 if (!isUndefOrEqual(Mask[i], i+NumElems))
4922 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4923 /// to an zero vector.
4924 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4925 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4926 SDValue V1 = N->getOperand(0);
4927 SDValue V2 = N->getOperand(1);
4928 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4929 for (unsigned i = 0; i != NumElems; ++i) {
4930 int Idx = N->getMaskElt(i);
4931 if (Idx >= (int)NumElems) {
4932 unsigned Opc = V2.getOpcode();
4933 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4935 if (Opc != ISD::BUILD_VECTOR ||
4936 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4938 } else if (Idx >= 0) {
4939 unsigned Opc = V1.getOpcode();
4940 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4942 if (Opc != ISD::BUILD_VECTOR ||
4943 !X86::isZeroNode(V1.getOperand(Idx)))
4950 /// getZeroVector - Returns a vector of specified type with all zero elements.
4952 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4953 SelectionDAG &DAG, SDLoc dl) {
4954 assert(VT.isVector() && "Expected a vector type");
4956 // Always build SSE zero vectors as <4 x i32> bitcasted
4957 // to their dest type. This ensures they get CSE'd.
4959 if (VT.is128BitVector()) { // SSE
4960 if (Subtarget->hasSSE2()) { // SSE2
4961 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4962 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4964 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4965 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4967 } else if (VT.is256BitVector()) { // AVX
4968 if (Subtarget->hasInt256()) { // AVX2
4969 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4970 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4971 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4973 // 256-bit logic and arithmetic instructions in AVX are all
4974 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4975 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4976 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4977 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4979 } else if (VT.is512BitVector()) { // AVX-512
4980 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4981 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4982 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4983 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4984 } else if (VT.getScalarType() == MVT::i1) {
4985 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4986 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4987 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4988 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4990 llvm_unreachable("Unexpected vector type");
4992 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4995 /// getOnesVector - Returns a vector of specified type with all bits set.
4996 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4997 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4998 /// Then bitcast to their original type, ensuring they get CSE'd.
4999 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5001 assert(VT.isVector() && "Expected a vector type");
5003 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5005 if (VT.is256BitVector()) {
5006 if (HasInt256) { // AVX2
5007 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5008 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5010 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5011 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5013 } else if (VT.is128BitVector()) {
5014 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5016 llvm_unreachable("Unexpected vector type");
5018 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5021 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5022 /// that point to V2 points to its first element.
5023 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5024 for (unsigned i = 0; i != NumElems; ++i) {
5025 if (Mask[i] > (int)NumElems) {
5031 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5032 /// operation of specified width.
5033 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5035 unsigned NumElems = VT.getVectorNumElements();
5036 SmallVector<int, 8> Mask;
5037 Mask.push_back(NumElems);
5038 for (unsigned i = 1; i != NumElems; ++i)
5040 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5043 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5044 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5046 unsigned NumElems = VT.getVectorNumElements();
5047 SmallVector<int, 8> Mask;
5048 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5050 Mask.push_back(i + NumElems);
5052 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5055 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5056 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5058 unsigned NumElems = VT.getVectorNumElements();
5059 SmallVector<int, 8> Mask;
5060 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5061 Mask.push_back(i + Half);
5062 Mask.push_back(i + NumElems + Half);
5064 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5067 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5068 // a generic shuffle instruction because the target has no such instructions.
5069 // Generate shuffles which repeat i16 and i8 several times until they can be
5070 // represented by v4f32 and then be manipulated by target suported shuffles.
5071 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5072 MVT VT = V.getSimpleValueType();
5073 int NumElems = VT.getVectorNumElements();
5076 while (NumElems > 4) {
5077 if (EltNo < NumElems/2) {
5078 V = getUnpackl(DAG, dl, VT, V, V);
5080 V = getUnpackh(DAG, dl, VT, V, V);
5081 EltNo -= NumElems/2;
5088 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5089 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5090 MVT VT = V.getSimpleValueType();
5093 if (VT.is128BitVector()) {
5094 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5095 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5096 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5098 } else if (VT.is256BitVector()) {
5099 // To use VPERMILPS to splat scalars, the second half of indicies must
5100 // refer to the higher part, which is a duplication of the lower one,
5101 // because VPERMILPS can only handle in-lane permutations.
5102 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5103 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5105 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5106 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5109 llvm_unreachable("Vector size not supported");
5111 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5114 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5115 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5116 MVT SrcVT = SV->getSimpleValueType(0);
5117 SDValue V1 = SV->getOperand(0);
5120 int EltNo = SV->getSplatIndex();
5121 int NumElems = SrcVT.getVectorNumElements();
5122 bool Is256BitVec = SrcVT.is256BitVector();
5124 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5125 "Unknown how to promote splat for type");
5127 // Extract the 128-bit part containing the splat element and update
5128 // the splat element index when it refers to the higher register.
5130 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5131 if (EltNo >= NumElems/2)
5132 EltNo -= NumElems/2;
5135 // All i16 and i8 vector types can't be used directly by a generic shuffle
5136 // instruction because the target has no such instruction. Generate shuffles
5137 // which repeat i16 and i8 several times until they fit in i32, and then can
5138 // be manipulated by target suported shuffles.
5139 MVT EltVT = SrcVT.getVectorElementType();
5140 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5141 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5143 // Recreate the 256-bit vector and place the same 128-bit vector
5144 // into the low and high part. This is necessary because we want
5145 // to use VPERM* to shuffle the vectors
5147 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5150 return getLegalSplat(DAG, V1, EltNo);
5153 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5154 /// vector of zero or undef vector. This produces a shuffle where the low
5155 /// element of V2 is swizzled into the zero/undef vector, landing at element
5156 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5157 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5159 const X86Subtarget *Subtarget,
5160 SelectionDAG &DAG) {
5161 MVT VT = V2.getSimpleValueType();
5163 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5164 unsigned NumElems = VT.getVectorNumElements();
5165 SmallVector<int, 16> MaskVec;
5166 for (unsigned i = 0; i != NumElems; ++i)
5167 // If this is the insertion idx, put the low elt of V2 here.
5168 MaskVec.push_back(i == Idx ? NumElems : i);
5169 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5172 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5173 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5174 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5175 /// shuffles which use a single input multiple times, and in those cases it will
5176 /// adjust the mask to only have indices within that single input.
5177 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5178 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5179 unsigned NumElems = VT.getVectorNumElements();
5183 bool IsFakeUnary = false;
5184 switch(N->getOpcode()) {
5186 ImmN = N->getOperand(N->getNumOperands()-1);
5187 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5188 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5190 case X86ISD::UNPCKH:
5191 DecodeUNPCKHMask(VT, Mask);
5192 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5194 case X86ISD::UNPCKL:
5195 DecodeUNPCKLMask(VT, Mask);
5196 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5198 case X86ISD::MOVHLPS:
5199 DecodeMOVHLPSMask(NumElems, Mask);
5200 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5202 case X86ISD::MOVLHPS:
5203 DecodeMOVLHPSMask(NumElems, Mask);
5204 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5206 case X86ISD::PALIGNR:
5207 ImmN = N->getOperand(N->getNumOperands()-1);
5208 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5210 case X86ISD::PSHUFD:
5211 case X86ISD::VPERMILP:
5212 ImmN = N->getOperand(N->getNumOperands()-1);
5213 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5216 case X86ISD::PSHUFHW:
5217 ImmN = N->getOperand(N->getNumOperands()-1);
5218 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5221 case X86ISD::PSHUFLW:
5222 ImmN = N->getOperand(N->getNumOperands()-1);
5223 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5226 case X86ISD::PSHUFB: {
5228 SDValue MaskNode = N->getOperand(1);
5229 while (MaskNode->getOpcode() == ISD::BITCAST)
5230 MaskNode = MaskNode->getOperand(0);
5232 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5233 // If we have a build-vector, then things are easy.
5234 EVT VT = MaskNode.getValueType();
5235 assert(VT.isVector() &&
5236 "Can't produce a non-vector with a build_vector!");
5237 if (!VT.isInteger())
5240 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5242 SmallVector<uint64_t, 32> RawMask;
5243 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5244 auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5247 APInt MaskElement = CN->getAPIntValue();
5249 // We now have to decode the element which could be any integer size and
5250 // extract each byte of it.
5251 for (int j = 0; j < NumBytesPerElement; ++j) {
5252 // Note that this is x86 and so always little endian: the low byte is
5253 // the first byte of the mask.
5254 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5255 MaskElement = MaskElement.lshr(8);
5258 DecodePSHUFBMask(RawMask, Mask);
5262 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5266 SDValue Ptr = MaskLoad->getBasePtr();
5267 if (Ptr->getOpcode() == X86ISD::Wrapper)
5268 Ptr = Ptr->getOperand(0);
5270 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5271 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5274 if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5275 // FIXME: Support AVX-512 here.
5276 if (!C->getType()->isVectorTy() ||
5277 (C->getNumElements() != 16 && C->getNumElements() != 32))
5280 assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5281 DecodePSHUFBMask(C, Mask);
5287 case X86ISD::VPERMI:
5288 ImmN = N->getOperand(N->getNumOperands()-1);
5289 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5293 case X86ISD::MOVSD: {
5294 // The index 0 always comes from the first element of the second source,
5295 // this is why MOVSS and MOVSD are used in the first place. The other
5296 // elements come from the other positions of the first source vector
5297 Mask.push_back(NumElems);
5298 for (unsigned i = 1; i != NumElems; ++i) {
5303 case X86ISD::VPERM2X128:
5304 ImmN = N->getOperand(N->getNumOperands()-1);
5305 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5306 if (Mask.empty()) return false;
5308 case X86ISD::MOVDDUP:
5309 case X86ISD::MOVLHPD:
5310 case X86ISD::MOVLPD:
5311 case X86ISD::MOVLPS:
5312 case X86ISD::MOVSHDUP:
5313 case X86ISD::MOVSLDUP:
5314 // Not yet implemented
5316 default: llvm_unreachable("unknown target shuffle node");
5319 // If we have a fake unary shuffle, the shuffle mask is spread across two
5320 // inputs that are actually the same node. Re-map the mask to always point
5321 // into the first input.
5324 if (M >= (int)Mask.size())
5330 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5331 /// element of the result of the vector shuffle.
5332 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5335 return SDValue(); // Limit search depth.
5337 SDValue V = SDValue(N, 0);
5338 EVT VT = V.getValueType();
5339 unsigned Opcode = V.getOpcode();
5341 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5342 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5343 int Elt = SV->getMaskElt(Index);
5346 return DAG.getUNDEF(VT.getVectorElementType());
5348 unsigned NumElems = VT.getVectorNumElements();
5349 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5350 : SV->getOperand(1);
5351 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5354 // Recurse into target specific vector shuffles to find scalars.
5355 if (isTargetShuffle(Opcode)) {
5356 MVT ShufVT = V.getSimpleValueType();
5357 unsigned NumElems = ShufVT.getVectorNumElements();
5358 SmallVector<int, 16> ShuffleMask;
5361 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5364 int Elt = ShuffleMask[Index];
5366 return DAG.getUNDEF(ShufVT.getVectorElementType());
5368 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5370 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5374 // Actual nodes that may contain scalar elements
5375 if (Opcode == ISD::BITCAST) {
5376 V = V.getOperand(0);
5377 EVT SrcVT = V.getValueType();
5378 unsigned NumElems = VT.getVectorNumElements();
5380 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5384 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5385 return (Index == 0) ? V.getOperand(0)
5386 : DAG.getUNDEF(VT.getVectorElementType());
5388 if (V.getOpcode() == ISD::BUILD_VECTOR)
5389 return V.getOperand(Index);
5394 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5395 /// shuffle operation which come from a consecutively from a zero. The
5396 /// search can start in two different directions, from left or right.
5397 /// We count undefs as zeros until PreferredNum is reached.
5398 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5399 unsigned NumElems, bool ZerosFromLeft,
5401 unsigned PreferredNum = -1U) {
5402 unsigned NumZeros = 0;
5403 for (unsigned i = 0; i != NumElems; ++i) {
5404 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5405 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5409 if (X86::isZeroNode(Elt))
5411 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5412 NumZeros = std::min(NumZeros + 1, PreferredNum);
5420 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5421 /// correspond consecutively to elements from one of the vector operands,
5422 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5424 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5425 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5426 unsigned NumElems, unsigned &OpNum) {
5427 bool SeenV1 = false;
5428 bool SeenV2 = false;
5430 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5431 int Idx = SVOp->getMaskElt(i);
5432 // Ignore undef indicies
5436 if (Idx < (int)NumElems)
5441 // Only accept consecutive elements from the same vector
5442 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5446 OpNum = SeenV1 ? 0 : 1;
5450 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5451 /// logical left shift of a vector.
5452 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5453 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5455 SVOp->getSimpleValueType(0).getVectorNumElements();
5456 unsigned NumZeros = getNumOfConsecutiveZeros(
5457 SVOp, NumElems, false /* check zeros from right */, DAG,
5458 SVOp->getMaskElt(0));
5464 // Considering the elements in the mask that are not consecutive zeros,
5465 // check if they consecutively come from only one of the source vectors.
5467 // V1 = {X, A, B, C} 0
5469 // vector_shuffle V1, V2 <1, 2, 3, X>
5471 if (!isShuffleMaskConsecutive(SVOp,
5472 0, // Mask Start Index
5473 NumElems-NumZeros, // Mask End Index(exclusive)
5474 NumZeros, // Where to start looking in the src vector
5475 NumElems, // Number of elements in vector
5476 OpSrc)) // Which source operand ?
5481 ShVal = SVOp->getOperand(OpSrc);
5485 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5486 /// logical left shift of a vector.
5487 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5488 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5490 SVOp->getSimpleValueType(0).getVectorNumElements();
5491 unsigned NumZeros = getNumOfConsecutiveZeros(
5492 SVOp, NumElems, true /* check zeros from left */, DAG,
5493 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5499 // Considering the elements in the mask that are not consecutive zeros,
5500 // check if they consecutively come from only one of the source vectors.
5502 // 0 { A, B, X, X } = V2
5504 // vector_shuffle V1, V2 <X, X, 4, 5>
5506 if (!isShuffleMaskConsecutive(SVOp,
5507 NumZeros, // Mask Start Index
5508 NumElems, // Mask End Index(exclusive)
5509 0, // Where to start looking in the src vector
5510 NumElems, // Number of elements in vector
5511 OpSrc)) // Which source operand ?
5516 ShVal = SVOp->getOperand(OpSrc);
5520 /// isVectorShift - Returns true if the shuffle can be implemented as a
5521 /// logical left or right shift of a vector.
5522 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5523 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5524 // Although the logic below support any bitwidth size, there are no
5525 // shift instructions which handle more than 128-bit vectors.
5526 if (!SVOp->getSimpleValueType(0).is128BitVector())
5529 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5530 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5536 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5538 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5539 unsigned NumNonZero, unsigned NumZero,
5541 const X86Subtarget* Subtarget,
5542 const TargetLowering &TLI) {
5549 for (unsigned i = 0; i < 16; ++i) {
5550 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5551 if (ThisIsNonZero && First) {
5553 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5555 V = DAG.getUNDEF(MVT::v8i16);
5560 SDValue ThisElt, LastElt;
5561 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5562 if (LastIsNonZero) {
5563 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5564 MVT::i16, Op.getOperand(i-1));
5566 if (ThisIsNonZero) {
5567 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5568 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5569 ThisElt, DAG.getConstant(8, MVT::i8));
5571 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5575 if (ThisElt.getNode())
5576 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5577 DAG.getIntPtrConstant(i/2));
5581 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5584 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5586 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5587 unsigned NumNonZero, unsigned NumZero,
5589 const X86Subtarget* Subtarget,
5590 const TargetLowering &TLI) {
5597 for (unsigned i = 0; i < 8; ++i) {
5598 bool isNonZero = (NonZeros & (1 << i)) != 0;
5602 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5604 V = DAG.getUNDEF(MVT::v8i16);
5607 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5608 MVT::v8i16, V, Op.getOperand(i),
5609 DAG.getIntPtrConstant(i));
5616 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5617 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5618 unsigned NonZeros, unsigned NumNonZero,
5619 unsigned NumZero, SelectionDAG &DAG,
5620 const X86Subtarget *Subtarget,
5621 const TargetLowering &TLI) {
5622 // We know there's at least one non-zero element
5623 unsigned FirstNonZeroIdx = 0;
5624 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5625 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5626 X86::isZeroNode(FirstNonZero)) {
5628 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5631 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5632 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5635 SDValue V = FirstNonZero.getOperand(0);
5636 MVT VVT = V.getSimpleValueType();
5637 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5640 unsigned FirstNonZeroDst =
5641 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5642 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5643 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5644 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5646 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5647 SDValue Elem = Op.getOperand(Idx);
5648 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5651 // TODO: What else can be here? Deal with it.
5652 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5655 // TODO: Some optimizations are still possible here
5656 // ex: Getting one element from a vector, and the rest from another.
5657 if (Elem.getOperand(0) != V)
5660 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5663 else if (IncorrectIdx == -1U) {
5667 // There was already one element with an incorrect index.
5668 // We can't optimize this case to an insertps.
5672 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5674 EVT VT = Op.getSimpleValueType();
5675 unsigned ElementMoveMask = 0;
5676 if (IncorrectIdx == -1U)
5677 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5679 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5681 SDValue InsertpsMask =
5682 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5683 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5689 /// getVShift - Return a vector logical shift node.
5691 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5692 unsigned NumBits, SelectionDAG &DAG,
5693 const TargetLowering &TLI, SDLoc dl) {
5694 assert(VT.is128BitVector() && "Unknown type for VShift");
5695 EVT ShVT = MVT::v2i64;
5696 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5697 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5698 return DAG.getNode(ISD::BITCAST, dl, VT,
5699 DAG.getNode(Opc, dl, ShVT, SrcOp,
5700 DAG.getConstant(NumBits,
5701 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5705 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5707 // Check if the scalar load can be widened into a vector load. And if
5708 // the address is "base + cst" see if the cst can be "absorbed" into
5709 // the shuffle mask.
5710 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5711 SDValue Ptr = LD->getBasePtr();
5712 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5714 EVT PVT = LD->getValueType(0);
5715 if (PVT != MVT::i32 && PVT != MVT::f32)
5720 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5721 FI = FINode->getIndex();
5723 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5724 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5725 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5726 Offset = Ptr.getConstantOperandVal(1);
5727 Ptr = Ptr.getOperand(0);
5732 // FIXME: 256-bit vector instructions don't require a strict alignment,
5733 // improve this code to support it better.
5734 unsigned RequiredAlign = VT.getSizeInBits()/8;
5735 SDValue Chain = LD->getChain();
5736 // Make sure the stack object alignment is at least 16 or 32.
5737 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5738 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5739 if (MFI->isFixedObjectIndex(FI)) {
5740 // Can't change the alignment. FIXME: It's possible to compute
5741 // the exact stack offset and reference FI + adjust offset instead.
5742 // If someone *really* cares about this. That's the way to implement it.
5745 MFI->setObjectAlignment(FI, RequiredAlign);
5749 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5750 // Ptr + (Offset & ~15).
5753 if ((Offset % RequiredAlign) & 3)
5755 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5757 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5758 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5760 int EltNo = (Offset - StartOffset) >> 2;
5761 unsigned NumElems = VT.getVectorNumElements();
5763 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5764 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5765 LD->getPointerInfo().getWithOffset(StartOffset),
5766 false, false, false, 0);
5768 SmallVector<int, 8> Mask;
5769 for (unsigned i = 0; i != NumElems; ++i)
5770 Mask.push_back(EltNo);
5772 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5778 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5779 /// vector of type 'VT', see if the elements can be replaced by a single large
5780 /// load which has the same value as a build_vector whose operands are 'elts'.
5782 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5784 /// FIXME: we'd also like to handle the case where the last elements are zero
5785 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5786 /// There's even a handy isZeroNode for that purpose.
5787 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5788 SDLoc &DL, SelectionDAG &DAG,
5789 bool isAfterLegalize) {
5790 EVT EltVT = VT.getVectorElementType();
5791 unsigned NumElems = Elts.size();
5793 LoadSDNode *LDBase = nullptr;
5794 unsigned LastLoadedElt = -1U;
5796 // For each element in the initializer, see if we've found a load or an undef.
5797 // If we don't find an initial load element, or later load elements are
5798 // non-consecutive, bail out.
5799 for (unsigned i = 0; i < NumElems; ++i) {
5800 SDValue Elt = Elts[i];
5802 if (!Elt.getNode() ||
5803 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5806 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5808 LDBase = cast<LoadSDNode>(Elt.getNode());
5812 if (Elt.getOpcode() == ISD::UNDEF)
5815 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5816 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5821 // If we have found an entire vector of loads and undefs, then return a large
5822 // load of the entire vector width starting at the base pointer. If we found
5823 // consecutive loads for the low half, generate a vzext_load node.
5824 if (LastLoadedElt == NumElems - 1) {
5826 if (isAfterLegalize &&
5827 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5830 SDValue NewLd = SDValue();
5832 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5833 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5834 LDBase->getPointerInfo(),
5835 LDBase->isVolatile(), LDBase->isNonTemporal(),
5836 LDBase->isInvariant(), 0);
5837 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5838 LDBase->getPointerInfo(),
5839 LDBase->isVolatile(), LDBase->isNonTemporal(),
5840 LDBase->isInvariant(), LDBase->getAlignment());
5842 if (LDBase->hasAnyUseOfValue(1)) {
5843 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5845 SDValue(NewLd.getNode(), 1));
5846 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5847 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5848 SDValue(NewLd.getNode(), 1));
5853 if (NumElems == 4 && LastLoadedElt == 1 &&
5854 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5855 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5856 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5858 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5859 LDBase->getPointerInfo(),
5860 LDBase->getAlignment(),
5861 false/*isVolatile*/, true/*ReadMem*/,
5864 // Make sure the newly-created LOAD is in the same position as LDBase in
5865 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5866 // update uses of LDBase's output chain to use the TokenFactor.
5867 if (LDBase->hasAnyUseOfValue(1)) {
5868 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5869 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5870 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5871 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5872 SDValue(ResNode.getNode(), 1));
5875 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5880 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5881 /// to generate a splat value for the following cases:
5882 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5883 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5884 /// a scalar load, or a constant.
5885 /// The VBROADCAST node is returned when a pattern is found,
5886 /// or SDValue() otherwise.
5887 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5888 SelectionDAG &DAG) {
5889 if (!Subtarget->hasFp256())
5892 MVT VT = Op.getSimpleValueType();
5895 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5896 "Unsupported vector type for broadcast.");
5901 switch (Op.getOpcode()) {
5903 // Unknown pattern found.
5906 case ISD::BUILD_VECTOR: {
5907 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5908 BitVector UndefElements;
5909 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5911 // We need a splat of a single value to use broadcast, and it doesn't
5912 // make any sense if the value is only in one element of the vector.
5913 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5917 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5918 Ld.getOpcode() == ISD::ConstantFP);
5920 // Make sure that all of the users of a non-constant load are from the
5921 // BUILD_VECTOR node.
5922 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5927 case ISD::VECTOR_SHUFFLE: {
5928 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5930 // Shuffles must have a splat mask where the first element is
5932 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5935 SDValue Sc = Op.getOperand(0);
5936 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5937 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5939 if (!Subtarget->hasInt256())
5942 // Use the register form of the broadcast instruction available on AVX2.
5943 if (VT.getSizeInBits() >= 256)
5944 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5945 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5948 Ld = Sc.getOperand(0);
5949 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5950 Ld.getOpcode() == ISD::ConstantFP);
5952 // The scalar_to_vector node and the suspected
5953 // load node must have exactly one user.
5954 // Constants may have multiple users.
5956 // AVX-512 has register version of the broadcast
5957 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5958 Ld.getValueType().getSizeInBits() >= 32;
5959 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5966 bool IsGE256 = (VT.getSizeInBits() >= 256);
5968 // Handle the broadcasting a single constant scalar from the constant pool
5969 // into a vector. On Sandybridge it is still better to load a constant vector
5970 // from the constant pool and not to broadcast it from a scalar.
5971 if (ConstSplatVal && Subtarget->hasInt256()) {
5972 EVT CVT = Ld.getValueType();
5973 assert(!CVT.isVector() && "Must not broadcast a vector type");
5974 unsigned ScalarSize = CVT.getSizeInBits();
5976 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5977 const Constant *C = nullptr;
5978 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5979 C = CI->getConstantIntValue();
5980 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5981 C = CF->getConstantFPValue();
5983 assert(C && "Invalid constant type");
5985 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5986 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5987 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5988 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5989 MachinePointerInfo::getConstantPool(),
5990 false, false, false, Alignment);
5992 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5996 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5997 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5999 // Handle AVX2 in-register broadcasts.
6000 if (!IsLoad && Subtarget->hasInt256() &&
6001 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6002 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6004 // The scalar source must be a normal load.
6008 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6009 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6011 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6012 // double since there is no vbroadcastsd xmm
6013 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6014 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6015 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6018 // Unsupported broadcast.
6022 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6023 /// underlying vector and index.
6025 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6027 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6029 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6030 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6033 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6035 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6037 // (extract_vector_elt (vector_shuffle<2,u,u,u>
6038 // (extract_subvector (v8f32 %vreg0), Constant<4>),
6041 // In this case the vector is the extract_subvector expression and the index
6042 // is 2, as specified by the shuffle.
6043 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6044 SDValue ShuffleVec = SVOp->getOperand(0);
6045 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6046 assert(ShuffleVecVT.getVectorElementType() ==
6047 ExtractedFromVec.getSimpleValueType().getVectorElementType());
6049 int ShuffleIdx = SVOp->getMaskElt(Idx);
6050 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6051 ExtractedFromVec = ShuffleVec;
6057 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6058 MVT VT = Op.getSimpleValueType();
6060 // Skip if insert_vec_elt is not supported.
6061 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6062 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6066 unsigned NumElems = Op.getNumOperands();
6070 SmallVector<unsigned, 4> InsertIndices;
6071 SmallVector<int, 8> Mask(NumElems, -1);
6073 for (unsigned i = 0; i != NumElems; ++i) {
6074 unsigned Opc = Op.getOperand(i).getOpcode();
6076 if (Opc == ISD::UNDEF)
6079 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6080 // Quit if more than 1 elements need inserting.
6081 if (InsertIndices.size() > 1)
6084 InsertIndices.push_back(i);
6088 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6089 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6090 // Quit if non-constant index.
6091 if (!isa<ConstantSDNode>(ExtIdx))
6093 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6095 // Quit if extracted from vector of different type.
6096 if (ExtractedFromVec.getValueType() != VT)
6099 if (!VecIn1.getNode())
6100 VecIn1 = ExtractedFromVec;
6101 else if (VecIn1 != ExtractedFromVec) {
6102 if (!VecIn2.getNode())
6103 VecIn2 = ExtractedFromVec;
6104 else if (VecIn2 != ExtractedFromVec)
6105 // Quit if more than 2 vectors to shuffle
6109 if (ExtractedFromVec == VecIn1)
6111 else if (ExtractedFromVec == VecIn2)
6112 Mask[i] = Idx + NumElems;
6115 if (!VecIn1.getNode())
6118 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6119 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6120 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6121 unsigned Idx = InsertIndices[i];
6122 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6123 DAG.getIntPtrConstant(Idx));
6129 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6131 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6133 MVT VT = Op.getSimpleValueType();
6134 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6135 "Unexpected type in LowerBUILD_VECTORvXi1!");
6138 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6139 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6140 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6141 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6144 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6145 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6146 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6147 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6150 bool AllContants = true;
6151 uint64_t Immediate = 0;
6152 int NonConstIdx = -1;
6153 bool IsSplat = true;
6154 unsigned NumNonConsts = 0;
6155 unsigned NumConsts = 0;
6156 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6157 SDValue In = Op.getOperand(idx);
6158 if (In.getOpcode() == ISD::UNDEF)
6160 if (!isa<ConstantSDNode>(In)) {
6161 AllContants = false;
6167 if (cast<ConstantSDNode>(In)->getZExtValue())
6168 Immediate |= (1ULL << idx);
6170 if (In != Op.getOperand(0))
6175 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6176 DAG.getConstant(Immediate, MVT::i16));
6177 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6178 DAG.getIntPtrConstant(0));
6181 if (NumNonConsts == 1 && NonConstIdx != 0) {
6184 SDValue VecAsImm = DAG.getConstant(Immediate,
6185 MVT::getIntegerVT(VT.getSizeInBits()));
6186 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6189 DstVec = DAG.getUNDEF(VT);
6190 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6191 Op.getOperand(NonConstIdx),
6192 DAG.getIntPtrConstant(NonConstIdx));
6194 if (!IsSplat && (NonConstIdx != 0))
6195 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6196 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6199 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6200 DAG.getConstant(-1, SelectVT),
6201 DAG.getConstant(0, SelectVT));
6203 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6204 DAG.getConstant((Immediate | 1), SelectVT),
6205 DAG.getConstant(Immediate, SelectVT));
6206 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6209 /// \brief Return true if \p N implements a horizontal binop and return the
6210 /// operands for the horizontal binop into V0 and V1.
6212 /// This is a helper function of PerformBUILD_VECTORCombine.
6213 /// This function checks that the build_vector \p N in input implements a
6214 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6215 /// operation to match.
6216 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6217 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6218 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6221 /// This function only analyzes elements of \p N whose indices are
6222 /// in range [BaseIdx, LastIdx).
6223 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6225 unsigned BaseIdx, unsigned LastIdx,
6226 SDValue &V0, SDValue &V1) {
6227 EVT VT = N->getValueType(0);
6229 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6230 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6231 "Invalid Vector in input!");
6233 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6234 bool CanFold = true;
6235 unsigned ExpectedVExtractIdx = BaseIdx;
6236 unsigned NumElts = LastIdx - BaseIdx;
6237 V0 = DAG.getUNDEF(VT);
6238 V1 = DAG.getUNDEF(VT);
6240 // Check if N implements a horizontal binop.
6241 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6242 SDValue Op = N->getOperand(i + BaseIdx);
6245 if (Op->getOpcode() == ISD::UNDEF) {
6246 // Update the expected vector extract index.
6247 if (i * 2 == NumElts)
6248 ExpectedVExtractIdx = BaseIdx;
6249 ExpectedVExtractIdx += 2;
6253 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6258 SDValue Op0 = Op.getOperand(0);
6259 SDValue Op1 = Op.getOperand(1);
6261 // Try to match the following pattern:
6262 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6263 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6264 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6265 Op0.getOperand(0) == Op1.getOperand(0) &&
6266 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6267 isa<ConstantSDNode>(Op1.getOperand(1)));
6271 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6272 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6274 if (i * 2 < NumElts) {
6275 if (V0.getOpcode() == ISD::UNDEF)
6276 V0 = Op0.getOperand(0);
6278 if (V1.getOpcode() == ISD::UNDEF)
6279 V1 = Op0.getOperand(0);
6280 if (i * 2 == NumElts)
6281 ExpectedVExtractIdx = BaseIdx;
6284 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6285 if (I0 == ExpectedVExtractIdx)
6286 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6287 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6288 // Try to match the following dag sequence:
6289 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6290 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6294 ExpectedVExtractIdx += 2;
6300 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6301 /// a concat_vector.
6303 /// This is a helper function of PerformBUILD_VECTORCombine.
6304 /// This function expects two 256-bit vectors called V0 and V1.
6305 /// At first, each vector is split into two separate 128-bit vectors.
6306 /// Then, the resulting 128-bit vectors are used to implement two
6307 /// horizontal binary operations.
6309 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6311 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6312 /// the two new horizontal binop.
6313 /// When Mode is set, the first horizontal binop dag node would take as input
6314 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6315 /// horizontal binop dag node would take as input the lower 128-bit of V1
6316 /// and the upper 128-bit of V1.
6318 /// HADD V0_LO, V0_HI
6319 /// HADD V1_LO, V1_HI
6321 /// Otherwise, the first horizontal binop dag node takes as input the lower
6322 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6323 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6325 /// HADD V0_LO, V1_LO
6326 /// HADD V0_HI, V1_HI
6328 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6329 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6330 /// the upper 128-bits of the result.
6331 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6332 SDLoc DL, SelectionDAG &DAG,
6333 unsigned X86Opcode, bool Mode,
6334 bool isUndefLO, bool isUndefHI) {
6335 EVT VT = V0.getValueType();
6336 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6337 "Invalid nodes in input!");
6339 unsigned NumElts = VT.getVectorNumElements();
6340 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6341 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6342 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6343 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6344 EVT NewVT = V0_LO.getValueType();
6346 SDValue LO = DAG.getUNDEF(NewVT);
6347 SDValue HI = DAG.getUNDEF(NewVT);
6350 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6351 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6352 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6353 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6354 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6356 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6357 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6358 V1_LO->getOpcode() != ISD::UNDEF))
6359 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6361 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6362 V1_HI->getOpcode() != ISD::UNDEF))
6363 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6366 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6369 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6370 /// sequence of 'vadd + vsub + blendi'.
6371 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6372 const X86Subtarget *Subtarget) {
6374 EVT VT = BV->getValueType(0);
6375 unsigned NumElts = VT.getVectorNumElements();
6376 SDValue InVec0 = DAG.getUNDEF(VT);
6377 SDValue InVec1 = DAG.getUNDEF(VT);
6379 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6380 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6382 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6383 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6384 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6387 // Odd-numbered elements in the input build vector are obtained from
6388 // adding two integer/float elements.
6389 // Even-numbered elements in the input build vector are obtained from
6390 // subtracting two integer/float elements.
6391 unsigned ExpectedOpcode = ISD::FSUB;
6392 unsigned NextExpectedOpcode = ISD::FADD;
6393 bool AddFound = false;
6394 bool SubFound = false;
6396 for (unsigned i = 0, e = NumElts; i != e; i++) {
6397 SDValue Op = BV->getOperand(i);
6399 // Skip 'undef' values.
6400 unsigned Opcode = Op.getOpcode();
6401 if (Opcode == ISD::UNDEF) {
6402 std::swap(ExpectedOpcode, NextExpectedOpcode);
6406 // Early exit if we found an unexpected opcode.
6407 if (Opcode != ExpectedOpcode)
6410 SDValue Op0 = Op.getOperand(0);
6411 SDValue Op1 = Op.getOperand(1);
6413 // Try to match the following pattern:
6414 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6415 // Early exit if we cannot match that sequence.
6416 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6417 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6418 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6419 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6420 Op0.getOperand(1) != Op1.getOperand(1))
6423 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6427 // We found a valid add/sub node. Update the information accordingly.
6433 // Update InVec0 and InVec1.
6434 if (InVec0.getOpcode() == ISD::UNDEF)
6435 InVec0 = Op0.getOperand(0);
6436 if (InVec1.getOpcode() == ISD::UNDEF)
6437 InVec1 = Op1.getOperand(0);
6439 // Make sure that operands in input to each add/sub node always
6440 // come from a same pair of vectors.
6441 if (InVec0 != Op0.getOperand(0)) {
6442 if (ExpectedOpcode == ISD::FSUB)
6445 // FADD is commutable. Try to commute the operands
6446 // and then test again.
6447 std::swap(Op0, Op1);
6448 if (InVec0 != Op0.getOperand(0))
6452 if (InVec1 != Op1.getOperand(0))
6455 // Update the pair of expected opcodes.
6456 std::swap(ExpectedOpcode, NextExpectedOpcode);
6459 // Don't try to fold this build_vector into a VSELECT if it has
6460 // too many UNDEF operands.
6461 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6462 InVec1.getOpcode() != ISD::UNDEF) {
6463 // Emit a sequence of vector add and sub followed by a VSELECT.
6464 // The new VSELECT will be lowered into a BLENDI.
6465 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6466 // and emit a single ADDSUB instruction.
6467 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6468 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6470 // Construct the VSELECT mask.
6471 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6472 EVT SVT = MaskVT.getVectorElementType();
6473 unsigned SVTBits = SVT.getSizeInBits();
6474 SmallVector<SDValue, 8> Ops;
6476 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6477 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6478 APInt::getAllOnesValue(SVTBits);
6479 SDValue Constant = DAG.getConstant(Value, SVT);
6480 Ops.push_back(Constant);
6483 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6484 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6490 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6491 const X86Subtarget *Subtarget) {
6493 EVT VT = N->getValueType(0);
6494 unsigned NumElts = VT.getVectorNumElements();
6495 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6496 SDValue InVec0, InVec1;
6498 // Try to match an ADDSUB.
6499 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6500 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6501 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6502 if (Value.getNode())
6506 // Try to match horizontal ADD/SUB.
6507 unsigned NumUndefsLO = 0;
6508 unsigned NumUndefsHI = 0;
6509 unsigned Half = NumElts/2;
6511 // Count the number of UNDEF operands in the build_vector in input.
6512 for (unsigned i = 0, e = Half; i != e; ++i)
6513 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6516 for (unsigned i = Half, e = NumElts; i != e; ++i)
6517 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6520 // Early exit if this is either a build_vector of all UNDEFs or all the
6521 // operands but one are UNDEF.
6522 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6525 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6526 // Try to match an SSE3 float HADD/HSUB.
6527 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6528 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6530 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6531 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6532 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6533 // Try to match an SSSE3 integer HADD/HSUB.
6534 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6535 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6537 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6538 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6541 if (!Subtarget->hasAVX())
6544 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6545 // Try to match an AVX horizontal add/sub of packed single/double
6546 // precision floating point values from 256-bit vectors.
6547 SDValue InVec2, InVec3;
6548 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6549 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6550 ((InVec0.getOpcode() == ISD::UNDEF ||
6551 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6552 ((InVec1.getOpcode() == ISD::UNDEF ||
6553 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6554 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6556 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6557 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6558 ((InVec0.getOpcode() == ISD::UNDEF ||
6559 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6560 ((InVec1.getOpcode() == ISD::UNDEF ||
6561 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6562 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6563 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6564 // Try to match an AVX2 horizontal add/sub of signed integers.
6565 SDValue InVec2, InVec3;
6567 bool CanFold = true;
6569 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6570 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6571 ((InVec0.getOpcode() == ISD::UNDEF ||
6572 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6573 ((InVec1.getOpcode() == ISD::UNDEF ||
6574 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6575 X86Opcode = X86ISD::HADD;
6576 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6577 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6578 ((InVec0.getOpcode() == ISD::UNDEF ||
6579 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6580 ((InVec1.getOpcode() == ISD::UNDEF ||
6581 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6582 X86Opcode = X86ISD::HSUB;
6587 // Fold this build_vector into a single horizontal add/sub.
6588 // Do this only if the target has AVX2.
6589 if (Subtarget->hasAVX2())
6590 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6592 // Do not try to expand this build_vector into a pair of horizontal
6593 // add/sub if we can emit a pair of scalar add/sub.
6594 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6597 // Convert this build_vector into a pair of horizontal binop followed by
6599 bool isUndefLO = NumUndefsLO == Half;
6600 bool isUndefHI = NumUndefsHI == Half;
6601 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6602 isUndefLO, isUndefHI);
6606 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6607 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6609 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6610 X86Opcode = X86ISD::HADD;
6611 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6612 X86Opcode = X86ISD::HSUB;
6613 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6614 X86Opcode = X86ISD::FHADD;
6615 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6616 X86Opcode = X86ISD::FHSUB;
6620 // Don't try to expand this build_vector into a pair of horizontal add/sub
6621 // if we can simply emit a pair of scalar add/sub.
6622 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6625 // Convert this build_vector into two horizontal add/sub followed by
6627 bool isUndefLO = NumUndefsLO == Half;
6628 bool isUndefHI = NumUndefsHI == Half;
6629 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6630 isUndefLO, isUndefHI);
6637 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6640 MVT VT = Op.getSimpleValueType();
6641 MVT ExtVT = VT.getVectorElementType();
6642 unsigned NumElems = Op.getNumOperands();
6644 // Generate vectors for predicate vectors.
6645 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6646 return LowerBUILD_VECTORvXi1(Op, DAG);
6648 // Vectors containing all zeros can be matched by pxor and xorps later
6649 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6650 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6651 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6652 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6655 return getZeroVector(VT, Subtarget, DAG, dl);
6658 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6659 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6660 // vpcmpeqd on 256-bit vectors.
6661 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6662 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6665 if (!VT.is512BitVector())
6666 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6669 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6670 if (Broadcast.getNode())
6673 unsigned EVTBits = ExtVT.getSizeInBits();
6675 unsigned NumZero = 0;
6676 unsigned NumNonZero = 0;
6677 unsigned NonZeros = 0;
6678 bool IsAllConstants = true;
6679 SmallSet<SDValue, 8> Values;
6680 for (unsigned i = 0; i < NumElems; ++i) {
6681 SDValue Elt = Op.getOperand(i);
6682 if (Elt.getOpcode() == ISD::UNDEF)
6685 if (Elt.getOpcode() != ISD::Constant &&
6686 Elt.getOpcode() != ISD::ConstantFP)
6687 IsAllConstants = false;
6688 if (X86::isZeroNode(Elt))
6691 NonZeros |= (1 << i);
6696 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6697 if (NumNonZero == 0)
6698 return DAG.getUNDEF(VT);
6700 // Special case for single non-zero, non-undef, element.
6701 if (NumNonZero == 1) {
6702 unsigned Idx = countTrailingZeros(NonZeros);
6703 SDValue Item = Op.getOperand(Idx);
6705 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6706 // the value are obviously zero, truncate the value to i32 and do the
6707 // insertion that way. Only do this if the value is non-constant or if the
6708 // value is a constant being inserted into element 0. It is cheaper to do
6709 // a constant pool load than it is to do a movd + shuffle.
6710 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6711 (!IsAllConstants || Idx == 0)) {
6712 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6714 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6715 EVT VecVT = MVT::v4i32;
6716 unsigned VecElts = 4;
6718 // Truncate the value (which may itself be a constant) to i32, and
6719 // convert it to a vector with movd (S2V+shuffle to zero extend).
6720 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6721 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6722 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6724 // Now we have our 32-bit value zero extended in the low element of
6725 // a vector. If Idx != 0, swizzle it into place.
6727 SmallVector<int, 4> Mask;
6728 Mask.push_back(Idx);
6729 for (unsigned i = 1; i != VecElts; ++i)
6731 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6734 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6738 // If we have a constant or non-constant insertion into the low element of
6739 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6740 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6741 // depending on what the source datatype is.
6744 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6746 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6747 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6748 if (VT.is256BitVector() || VT.is512BitVector()) {
6749 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6750 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6751 Item, DAG.getIntPtrConstant(0));
6753 assert(VT.is128BitVector() && "Expected an SSE value type!");
6754 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6755 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6756 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6759 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6760 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6761 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6762 if (VT.is256BitVector()) {
6763 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6764 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6766 assert(VT.is128BitVector() && "Expected an SSE value type!");
6767 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6769 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6773 // Is it a vector logical left shift?
6774 if (NumElems == 2 && Idx == 1 &&
6775 X86::isZeroNode(Op.getOperand(0)) &&
6776 !X86::isZeroNode(Op.getOperand(1))) {
6777 unsigned NumBits = VT.getSizeInBits();
6778 return getVShift(true, VT,
6779 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6780 VT, Op.getOperand(1)),
6781 NumBits/2, DAG, *this, dl);
6784 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6787 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6788 // is a non-constant being inserted into an element other than the low one,
6789 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6790 // movd/movss) to move this into the low element, then shuffle it into
6792 if (EVTBits == 32) {
6793 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6795 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6796 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6797 SmallVector<int, 8> MaskVec;
6798 for (unsigned i = 0; i != NumElems; ++i)
6799 MaskVec.push_back(i == Idx ? 0 : 1);
6800 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6804 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6805 if (Values.size() == 1) {
6806 if (EVTBits == 32) {
6807 // Instead of a shuffle like this:
6808 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6809 // Check if it's possible to issue this instead.
6810 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6811 unsigned Idx = countTrailingZeros(NonZeros);
6812 SDValue Item = Op.getOperand(Idx);
6813 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6814 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6819 // A vector full of immediates; various special cases are already
6820 // handled, so this is best done with a single constant-pool load.
6824 // For AVX-length vectors, build the individual 128-bit pieces and use
6825 // shuffles to put them in place.
6826 if (VT.is256BitVector() || VT.is512BitVector()) {
6827 SmallVector<SDValue, 64> V;
6828 for (unsigned i = 0; i != NumElems; ++i)
6829 V.push_back(Op.getOperand(i));
6831 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6833 // Build both the lower and upper subvector.
6834 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6835 makeArrayRef(&V[0], NumElems/2));
6836 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6837 makeArrayRef(&V[NumElems / 2], NumElems/2));
6839 // Recreate the wider vector with the lower and upper part.
6840 if (VT.is256BitVector())
6841 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6842 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6845 // Let legalizer expand 2-wide build_vectors.
6846 if (EVTBits == 64) {
6847 if (NumNonZero == 1) {
6848 // One half is zero or undef.
6849 unsigned Idx = countTrailingZeros(NonZeros);
6850 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6851 Op.getOperand(Idx));
6852 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6857 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6858 if (EVTBits == 8 && NumElems == 16) {
6859 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6861 if (V.getNode()) return V;
6864 if (EVTBits == 16 && NumElems == 8) {
6865 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6867 if (V.getNode()) return V;
6870 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6871 if (EVTBits == 32 && NumElems == 4) {
6872 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6873 NumZero, DAG, Subtarget, *this);
6878 // If element VT is == 32 bits, turn it into a number of shuffles.
6879 SmallVector<SDValue, 8> V(NumElems);
6880 if (NumElems == 4 && NumZero > 0) {
6881 for (unsigned i = 0; i < 4; ++i) {
6882 bool isZero = !(NonZeros & (1 << i));
6884 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6886 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6889 for (unsigned i = 0; i < 2; ++i) {
6890 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6893 V[i] = V[i*2]; // Must be a zero vector.
6896 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6899 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6902 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6907 bool Reverse1 = (NonZeros & 0x3) == 2;
6908 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6912 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6913 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6915 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6918 if (Values.size() > 1 && VT.is128BitVector()) {
6919 // Check for a build vector of consecutive loads.
6920 for (unsigned i = 0; i < NumElems; ++i)
6921 V[i] = Op.getOperand(i);
6923 // Check for elements which are consecutive loads.
6924 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6928 // Check for a build vector from mostly shuffle plus few inserting.
6929 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6933 // For SSE 4.1, use insertps to put the high elements into the low element.
6934 if (getSubtarget()->hasSSE41()) {
6936 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6937 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6939 Result = DAG.getUNDEF(VT);
6941 for (unsigned i = 1; i < NumElems; ++i) {
6942 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6943 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6944 Op.getOperand(i), DAG.getIntPtrConstant(i));
6949 // Otherwise, expand into a number of unpckl*, start by extending each of
6950 // our (non-undef) elements to the full vector width with the element in the
6951 // bottom slot of the vector (which generates no code for SSE).
6952 for (unsigned i = 0; i < NumElems; ++i) {
6953 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6954 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6956 V[i] = DAG.getUNDEF(VT);
6959 // Next, we iteratively mix elements, e.g. for v4f32:
6960 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6961 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6962 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6963 unsigned EltStride = NumElems >> 1;
6964 while (EltStride != 0) {
6965 for (unsigned i = 0; i < EltStride; ++i) {
6966 // If V[i+EltStride] is undef and this is the first round of mixing,
6967 // then it is safe to just drop this shuffle: V[i] is already in the
6968 // right place, the one element (since it's the first round) being
6969 // inserted as undef can be dropped. This isn't safe for successive
6970 // rounds because they will permute elements within both vectors.
6971 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6972 EltStride == NumElems/2)
6975 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6984 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6985 // to create 256-bit vectors from two other 128-bit ones.
6986 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6988 MVT ResVT = Op.getSimpleValueType();
6990 assert((ResVT.is256BitVector() ||
6991 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6993 SDValue V1 = Op.getOperand(0);
6994 SDValue V2 = Op.getOperand(1);
6995 unsigned NumElems = ResVT.getVectorNumElements();
6996 if(ResVT.is256BitVector())
6997 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6999 if (Op.getNumOperands() == 4) {
7000 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7001 ResVT.getVectorNumElements()/2);
7002 SDValue V3 = Op.getOperand(2);
7003 SDValue V4 = Op.getOperand(3);
7004 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7005 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7007 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7010 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7011 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7012 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7013 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7014 Op.getNumOperands() == 4)));
7016 // AVX can use the vinsertf128 instruction to create 256-bit vectors
7017 // from two other 128-bit ones.
7019 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7020 return LowerAVXCONCAT_VECTORS(Op, DAG);
7024 //===----------------------------------------------------------------------===//
7025 // Vector shuffle lowering
7027 // This is an experimental code path for lowering vector shuffles on x86. It is
7028 // designed to handle arbitrary vector shuffles and blends, gracefully
7029 // degrading performance as necessary. It works hard to recognize idiomatic
7030 // shuffles and lower them to optimal instruction patterns without leaving
7031 // a framework that allows reasonably efficient handling of all vector shuffle
7033 //===----------------------------------------------------------------------===//
7035 /// \brief Tiny helper function to identify a no-op mask.
7037 /// This is a somewhat boring predicate function. It checks whether the mask
7038 /// array input, which is assumed to be a single-input shuffle mask of the kind
7039 /// used by the X86 shuffle instructions (not a fully general
7040 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7041 /// in-place shuffle are 'no-op's.
7042 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7043 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7044 if (Mask[i] != -1 && Mask[i] != i)
7049 /// \brief Helper function to classify a mask as a single-input mask.
7051 /// This isn't a generic single-input test because in the vector shuffle
7052 /// lowering we canonicalize single inputs to be the first input operand. This
7053 /// means we can more quickly test for a single input by only checking whether
7054 /// an input from the second operand exists. We also assume that the size of
7055 /// mask corresponds to the size of the input vectors which isn't true in the
7056 /// fully general case.
7057 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7059 if (M >= (int)Mask.size())
7064 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7065 // 2013 will allow us to use it as a non-type template parameter.
7068 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7070 /// See its documentation for details.
7071 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7072 if (Mask.size() != Args.size())
7074 for (int i = 0, e = Mask.size(); i < e; ++i) {
7075 assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7076 assert(*Args[i] < (int)Args.size() * 2 &&
7077 "Argument outside the range of possible shuffle inputs!");
7078 if (Mask[i] != -1 && Mask[i] != *Args[i])
7086 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7089 /// This is a fast way to test a shuffle mask against a fixed pattern:
7091 /// if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7093 /// It returns true if the mask is exactly as wide as the argument list, and
7094 /// each element of the mask is either -1 (signifying undef) or the value given
7095 /// in the argument.
7096 static const VariadicFunction1<
7097 bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7099 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7101 /// This helper function produces an 8-bit shuffle immediate corresponding to
7102 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7103 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7106 /// NB: We rely heavily on "undef" masks preserving the input lane.
7107 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7108 SelectionDAG &DAG) {
7109 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7110 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7111 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7112 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7113 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7116 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7117 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7118 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7119 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7120 return DAG.getConstant(Imm, MVT::i8);
7123 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7125 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7126 /// support for floating point shuffles but not integer shuffles. These
7127 /// instructions will incur a domain crossing penalty on some chips though so
7128 /// it is better to avoid lowering through this for integer vectors where
7130 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7131 const X86Subtarget *Subtarget,
7132 SelectionDAG &DAG) {
7134 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7135 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7136 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7137 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7138 ArrayRef<int> Mask = SVOp->getMask();
7139 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7141 if (isSingleInputShuffleMask(Mask)) {
7142 // Straight shuffle of a single input vector. Simulate this by using the
7143 // single input as both of the "inputs" to this instruction..
7144 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7145 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7146 DAG.getConstant(SHUFPDMask, MVT::i8));
7148 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7149 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7151 // Use dedicated unpack instructions for masks that match their pattern.
7152 if (isShuffleEquivalent(Mask, 0, 2))
7153 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7154 if (isShuffleEquivalent(Mask, 1, 3))
7155 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7157 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7158 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7159 DAG.getConstant(SHUFPDMask, MVT::i8));
7162 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7164 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7165 /// the integer unit to minimize domain crossing penalties. However, for blends
7166 /// it falls back to the floating point shuffle operation with appropriate bit
7168 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7169 const X86Subtarget *Subtarget,
7170 SelectionDAG &DAG) {
7172 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7173 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7174 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7175 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7176 ArrayRef<int> Mask = SVOp->getMask();
7177 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7179 if (isSingleInputShuffleMask(Mask)) {
7180 // Straight shuffle of a single input vector. For everything from SSE2
7181 // onward this has a single fast instruction with no scary immediates.
7182 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7183 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7184 int WidenedMask[4] = {
7185 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7186 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7188 ISD::BITCAST, DL, MVT::v2i64,
7189 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7190 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7193 // Use dedicated unpack instructions for masks that match their pattern.
7194 if (isShuffleEquivalent(Mask, 0, 2))
7195 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7196 if (isShuffleEquivalent(Mask, 1, 3))
7197 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7199 // We implement this with SHUFPD which is pretty lame because it will likely
7200 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7201 // However, all the alternatives are still more cycles and newer chips don't
7202 // have this problem. It would be really nice if x86 had better shuffles here.
7203 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7204 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7205 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7206 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7209 /// \brief Lower 4-lane 32-bit floating point shuffles.
7211 /// Uses instructions exclusively from the floating point unit to minimize
7212 /// domain crossing penalties, as these are sufficient to implement all v4f32
7214 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7215 const X86Subtarget *Subtarget,
7216 SelectionDAG &DAG) {
7218 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7219 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7220 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7221 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7222 ArrayRef<int> Mask = SVOp->getMask();
7223 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7225 SDValue LowV = V1, HighV = V2;
7226 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7229 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7231 if (NumV2Elements == 0)
7232 // Straight shuffle of a single input vector. We pass the input vector to
7233 // both operands to simulate this with a SHUFPS.
7234 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7235 getV4X86ShuffleImm8ForMask(Mask, DAG));
7237 // Use dedicated unpack instructions for masks that match their pattern.
7238 if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7239 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7240 if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7241 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7243 if (NumV2Elements == 1) {
7245 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7247 // Compute the index adjacent to V2Index and in the same half by toggling
7249 int V2AdjIndex = V2Index ^ 1;
7251 if (Mask[V2AdjIndex] == -1) {
7252 // Handles all the cases where we have a single V2 element and an undef.
7253 // This will only ever happen in the high lanes because we commute the
7254 // vector otherwise.
7256 std::swap(LowV, HighV);
7257 NewMask[V2Index] -= 4;
7259 // Handle the case where the V2 element ends up adjacent to a V1 element.
7260 // To make this work, blend them together as the first step.
7261 int V1Index = V2AdjIndex;
7262 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7263 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7264 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7266 // Now proceed to reconstruct the final blend as we have the necessary
7267 // high or low half formed.
7274 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7275 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7277 } else if (NumV2Elements == 2) {
7278 if (Mask[0] < 4 && Mask[1] < 4) {
7279 // Handle the easy case where we have V1 in the low lanes and V2 in the
7280 // high lanes. We never see this reversed because we sort the shuffle.
7284 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7285 // trying to place elements directly, just blend them and set up the final
7286 // shuffle to place them.
7288 // The first two blend mask elements are for V1, the second two are for
7290 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7291 Mask[2] < 4 ? Mask[2] : Mask[3],
7292 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7293 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7294 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7295 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7297 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7300 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7301 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7302 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7303 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7306 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7307 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7310 /// \brief Lower 4-lane i32 vector shuffles.
7312 /// We try to handle these with integer-domain shuffles where we can, but for
7313 /// blends we use the floating point domain blend instructions.
7314 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7315 const X86Subtarget *Subtarget,
7316 SelectionDAG &DAG) {
7318 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7319 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7320 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7321 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7322 ArrayRef<int> Mask = SVOp->getMask();
7323 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7325 if (isSingleInputShuffleMask(Mask))
7326 // Straight shuffle of a single input vector. For everything from SSE2
7327 // onward this has a single fast instruction with no scary immediates.
7328 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7329 getV4X86ShuffleImm8ForMask(Mask, DAG));
7331 // Use dedicated unpack instructions for masks that match their pattern.
7332 if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7333 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7334 if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7335 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7337 // We implement this with SHUFPS because it can blend from two vectors.
7338 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7339 // up the inputs, bypassing domain shift penalties that we would encur if we
7340 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7342 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7343 DAG.getVectorShuffle(
7345 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7346 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7349 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7350 /// shuffle lowering, and the most complex part.
7352 /// The lowering strategy is to try to form pairs of input lanes which are
7353 /// targeted at the same half of the final vector, and then use a dword shuffle
7354 /// to place them onto the right half, and finally unpack the paired lanes into
7355 /// their final position.
7357 /// The exact breakdown of how to form these dword pairs and align them on the
7358 /// correct sides is really tricky. See the comments within the function for
7359 /// more of the details.
7360 static SDValue lowerV8I16SingleInputVectorShuffle(
7361 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7362 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7363 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7364 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7365 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7367 SmallVector<int, 4> LoInputs;
7368 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7369 [](int M) { return M >= 0; });
7370 std::sort(LoInputs.begin(), LoInputs.end());
7371 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7372 SmallVector<int, 4> HiInputs;
7373 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7374 [](int M) { return M >= 0; });
7375 std::sort(HiInputs.begin(), HiInputs.end());
7376 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7378 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7379 int NumHToL = LoInputs.size() - NumLToL;
7381 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7382 int NumHToH = HiInputs.size() - NumLToH;
7383 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7384 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7385 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7386 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7388 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7389 // such inputs we can swap two of the dwords across the half mark and end up
7390 // with <=2 inputs to each half in each half. Once there, we can fall through
7391 // to the generic code below. For example:
7393 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7394 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7396 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7397 // and an existing 2-into-2 on the other half. In this case we may have to
7398 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7399 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7400 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7401 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7402 // half than the one we target for fixing) will be fixed when we re-enter this
7403 // path. We will also combine away any sequence of PSHUFD instructions that
7404 // result into a single instruction. Here is an example of the tricky case:
7406 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7407 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7409 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7411 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7412 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7414 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7415 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7417 // The result is fine to be handled by the generic logic.
7418 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7419 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7420 int AOffset, int BOffset) {
7421 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7422 "Must call this with A having 3 or 1 inputs from the A half.");
7423 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7424 "Must call this with B having 1 or 3 inputs from the B half.");
7425 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7426 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7428 // Compute the index of dword with only one word among the three inputs in
7429 // a half by taking the sum of the half with three inputs and subtracting
7430 // the sum of the actual three inputs. The difference is the remaining
7433 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7434 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7435 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7436 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7437 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7438 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7439 int TripleNonInputIdx =
7440 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7441 TripleDWord = TripleNonInputIdx / 2;
7443 // We use xor with one to compute the adjacent DWord to whichever one the
7445 OneInputDWord = (OneInput / 2) ^ 1;
7447 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7448 // and BToA inputs. If there is also such a problem with the BToB and AToB
7449 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7450 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7451 // is essential that we don't *create* a 3<-1 as then we might oscillate.
7452 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7453 // Compute how many inputs will be flipped by swapping these DWords. We
7455 // to balance this to ensure we don't form a 3-1 shuffle in the other
7457 int NumFlippedAToBInputs =
7458 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7459 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7460 int NumFlippedBToBInputs =
7461 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7462 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7463 if ((NumFlippedAToBInputs == 1 &&
7464 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7465 (NumFlippedBToBInputs == 1 &&
7466 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7467 // We choose whether to fix the A half or B half based on whether that
7468 // half has zero flipped inputs. At zero, we may not be able to fix it
7469 // with that half. We also bias towards fixing the B half because that
7470 // will more commonly be the high half, and we have to bias one way.
7471 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7472 ArrayRef<int> Inputs) {
7473 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7474 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7475 PinnedIdx ^ 1) != Inputs.end();
7476 // Determine whether the free index is in the flipped dword or the
7477 // unflipped dword based on where the pinned index is. We use this bit
7478 // in an xor to conditionally select the adjacent dword.
7479 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7480 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7481 FixFreeIdx) != Inputs.end();
7482 if (IsFixIdxInput == IsFixFreeIdxInput)
7484 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7485 FixFreeIdx) != Inputs.end();
7486 assert(IsFixIdxInput != IsFixFreeIdxInput &&
7487 "We need to be changing the number of flipped inputs!");
7488 int PSHUFHalfMask[] = {0, 1, 2, 3};
7489 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7490 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7492 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7495 if (M != -1 && M == FixIdx)
7497 else if (M != -1 && M == FixFreeIdx)
7500 if (NumFlippedBToBInputs != 0) {
7502 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7503 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7505 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7507 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7508 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7513 int PSHUFDMask[] = {0, 1, 2, 3};
7514 PSHUFDMask[ADWord] = BDWord;
7515 PSHUFDMask[BDWord] = ADWord;
7516 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7517 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7518 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7519 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7521 // Adjust the mask to match the new locations of A and B.
7523 if (M != -1 && M/2 == ADWord)
7524 M = 2 * BDWord + M % 2;
7525 else if (M != -1 && M/2 == BDWord)
7526 M = 2 * ADWord + M % 2;
7528 // Recurse back into this routine to re-compute state now that this isn't
7529 // a 3 and 1 problem.
7530 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7533 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7534 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7535 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7536 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7538 // At this point there are at most two inputs to the low and high halves from
7539 // each half. That means the inputs can always be grouped into dwords and
7540 // those dwords can then be moved to the correct half with a dword shuffle.
7541 // We use at most one low and one high word shuffle to collect these paired
7542 // inputs into dwords, and finally a dword shuffle to place them.
7543 int PSHUFLMask[4] = {-1, -1, -1, -1};
7544 int PSHUFHMask[4] = {-1, -1, -1, -1};
7545 int PSHUFDMask[4] = {-1, -1, -1, -1};
7547 // First fix the masks for all the inputs that are staying in their
7548 // original halves. This will then dictate the targets of the cross-half
7550 auto fixInPlaceInputs =
7551 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7552 MutableArrayRef<int> SourceHalfMask,
7553 MutableArrayRef<int> HalfMask, int HalfOffset) {
7554 if (InPlaceInputs.empty())
7556 if (InPlaceInputs.size() == 1) {
7557 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7558 InPlaceInputs[0] - HalfOffset;
7559 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7562 if (IncomingInputs.empty()) {
7563 // Just fix all of the in place inputs.
7564 for (int Input : InPlaceInputs) {
7565 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7566 PSHUFDMask[Input / 2] = Input / 2;
7571 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7572 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7573 InPlaceInputs[0] - HalfOffset;
7574 // Put the second input next to the first so that they are packed into
7575 // a dword. We find the adjacent index by toggling the low bit.
7576 int AdjIndex = InPlaceInputs[0] ^ 1;
7577 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7578 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7579 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7581 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7582 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7584 // Now gather the cross-half inputs and place them into a free dword of
7585 // their target half.
7586 // FIXME: This operation could almost certainly be simplified dramatically to
7587 // look more like the 3-1 fixing operation.
7588 auto moveInputsToRightHalf = [&PSHUFDMask](
7589 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7590 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7591 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7593 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7594 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7596 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7598 int LowWord = Word & ~1;
7599 int HighWord = Word | 1;
7600 return isWordClobbered(SourceHalfMask, LowWord) ||
7601 isWordClobbered(SourceHalfMask, HighWord);
7604 if (IncomingInputs.empty())
7607 if (ExistingInputs.empty()) {
7608 // Map any dwords with inputs from them into the right half.
7609 for (int Input : IncomingInputs) {
7610 // If the source half mask maps over the inputs, turn those into
7611 // swaps and use the swapped lane.
7612 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7613 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7614 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7615 Input - SourceOffset;
7616 // We have to swap the uses in our half mask in one sweep.
7617 for (int &M : HalfMask)
7618 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7620 else if (M == Input)
7621 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7623 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7624 Input - SourceOffset &&
7625 "Previous placement doesn't match!");
7627 // Note that this correctly re-maps both when we do a swap and when
7628 // we observe the other side of the swap above. We rely on that to
7629 // avoid swapping the members of the input list directly.
7630 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7633 // Map the input's dword into the correct half.
7634 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7635 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7637 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7639 "Previous placement doesn't match!");
7642 // And just directly shift any other-half mask elements to be same-half
7643 // as we will have mirrored the dword containing the element into the
7644 // same position within that half.
7645 for (int &M : HalfMask)
7646 if (M >= SourceOffset && M < SourceOffset + 4) {
7647 M = M - SourceOffset + DestOffset;
7648 assert(M >= 0 && "This should never wrap below zero!");
7653 // Ensure we have the input in a viable dword of its current half. This
7654 // is particularly tricky because the original position may be clobbered
7655 // by inputs being moved and *staying* in that half.
7656 if (IncomingInputs.size() == 1) {
7657 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7658 int InputFixed = std::find(std::begin(SourceHalfMask),
7659 std::end(SourceHalfMask), -1) -
7660 std::begin(SourceHalfMask) + SourceOffset;
7661 SourceHalfMask[InputFixed - SourceOffset] =
7662 IncomingInputs[0] - SourceOffset;
7663 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7665 IncomingInputs[0] = InputFixed;
7667 } else if (IncomingInputs.size() == 2) {
7668 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7669 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7670 // We have two non-adjacent or clobbered inputs we need to extract from
7671 // the source half. To do this, we need to map them into some adjacent
7672 // dword slot in the source mask.
7673 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7674 IncomingInputs[1] - SourceOffset};
7676 // If there is a free slot in the source half mask adjacent to one of
7677 // the inputs, place the other input in it. We use (Index XOR 1) to
7678 // compute an adjacent index.
7679 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7680 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7681 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7682 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7683 InputsFixed[1] = InputsFixed[0] ^ 1;
7684 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7685 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7686 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7687 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7688 InputsFixed[0] = InputsFixed[1] ^ 1;
7689 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7690 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7691 // The two inputs are in the same DWord but it is clobbered and the
7692 // adjacent DWord isn't used at all. Move both inputs to the free
7694 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7695 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
7696 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
7697 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
7699 // The only way we hit this point is if there is no clobbering
7700 // (because there are no off-half inputs to this half) and there is no
7701 // free slot adjacent to one of the inputs. In this case, we have to
7702 // swap an input with a non-input.
7703 for (int i = 0; i < 4; ++i)
7704 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
7705 "We can't handle any clobbers here!");
7706 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
7707 "Cannot have adjacent inputs here!");
7709 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7710 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
7712 // We also have to update the final source mask in this case because
7713 // it may need to undo the above swap.
7714 for (int &M : FinalSourceHalfMask)
7715 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
7716 M = InputsFixed[1] + SourceOffset;
7717 else if (M == InputsFixed[1] + SourceOffset)
7718 M = (InputsFixed[0] ^ 1) + SourceOffset;
7720 InputsFixed[1] = InputsFixed[0] ^ 1;
7723 // Point everything at the fixed inputs.
7724 for (int &M : HalfMask)
7725 if (M == IncomingInputs[0])
7726 M = InputsFixed[0] + SourceOffset;
7727 else if (M == IncomingInputs[1])
7728 M = InputsFixed[1] + SourceOffset;
7730 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
7731 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
7734 llvm_unreachable("Unhandled input size!");
7737 // Now hoist the DWord down to the right half.
7738 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7739 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7740 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7741 for (int &M : HalfMask)
7742 for (int Input : IncomingInputs)
7744 M = FreeDWord * 2 + Input % 2;
7746 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
7747 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7748 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
7749 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7751 // Now enact all the shuffles we've computed to move the inputs into their
7753 if (!isNoopShuffleMask(PSHUFLMask))
7754 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7755 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7756 if (!isNoopShuffleMask(PSHUFHMask))
7757 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7758 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7759 if (!isNoopShuffleMask(PSHUFDMask))
7760 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7761 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7762 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7763 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7765 // At this point, each half should contain all its inputs, and we can then
7766 // just shuffle them into their final position.
7767 assert(std::count_if(LoMask.begin(), LoMask.end(),
7768 [](int M) { return M >= 4; }) == 0 &&
7769 "Failed to lift all the high half inputs to the low mask!");
7770 assert(std::count_if(HiMask.begin(), HiMask.end(),
7771 [](int M) { return M >= 0 && M < 4; }) == 0 &&
7772 "Failed to lift all the low half inputs to the high mask!");
7774 // Do a half shuffle for the low mask.
7775 if (!isNoopShuffleMask(LoMask))
7776 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7777 getV4X86ShuffleImm8ForMask(LoMask, DAG));
7779 // Do a half shuffle with the high mask after shifting its values down.
7780 for (int &M : HiMask)
7783 if (!isNoopShuffleMask(HiMask))
7784 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7785 getV4X86ShuffleImm8ForMask(HiMask, DAG));
7790 /// \brief Detect whether the mask pattern should be lowered through
7793 /// This essentially tests whether viewing the mask as an interleaving of two
7794 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7795 /// lowering it through interleaving is a significantly better strategy.
7796 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7797 int NumEvenInputs[2] = {0, 0};
7798 int NumOddInputs[2] = {0, 0};
7799 int NumLoInputs[2] = {0, 0};
7800 int NumHiInputs[2] = {0, 0};
7801 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7805 int InputIdx = Mask[i] >= Size;
7808 ++NumLoInputs[InputIdx];
7810 ++NumHiInputs[InputIdx];
7813 ++NumEvenInputs[InputIdx];
7815 ++NumOddInputs[InputIdx];
7818 // The minimum number of cross-input results for both the interleaved and
7819 // split cases. If interleaving results in fewer cross-input results, return
7821 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7822 NumEvenInputs[0] + NumOddInputs[1]);
7823 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7824 NumLoInputs[0] + NumHiInputs[1]);
7825 return InterleavedCrosses < SplitCrosses;
7828 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7830 /// This strategy only works when the inputs from each vector fit into a single
7831 /// half of that vector, and generally there are not so many inputs as to leave
7832 /// the in-place shuffles required highly constrained (and thus expensive). It
7833 /// shifts all the inputs into a single side of both input vectors and then
7834 /// uses an unpack to interleave these inputs in a single vector. At that
7835 /// point, we will fall back on the generic single input shuffle lowering.
7836 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7838 MutableArrayRef<int> Mask,
7839 const X86Subtarget *Subtarget,
7840 SelectionDAG &DAG) {
7841 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7842 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7843 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7844 for (int i = 0; i < 8; ++i)
7845 if (Mask[i] >= 0 && Mask[i] < 4)
7846 LoV1Inputs.push_back(i);
7847 else if (Mask[i] >= 4 && Mask[i] < 8)
7848 HiV1Inputs.push_back(i);
7849 else if (Mask[i] >= 8 && Mask[i] < 12)
7850 LoV2Inputs.push_back(i);
7851 else if (Mask[i] >= 12)
7852 HiV2Inputs.push_back(i);
7854 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7855 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7858 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7859 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7860 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7862 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7863 HiV1Inputs.size() + HiV2Inputs.size();
7865 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7866 ArrayRef<int> HiInputs, bool MoveToLo,
7868 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7869 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7870 if (BadInputs.empty())
7873 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7874 int MoveOffset = MoveToLo ? 0 : 4;
7876 if (GoodInputs.empty()) {
7877 for (int BadInput : BadInputs) {
7878 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7879 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7882 if (GoodInputs.size() == 2) {
7883 // If the low inputs are spread across two dwords, pack them into
7885 MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
7886 MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
7887 Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
7888 Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
7890 // Otherwise pin the good inputs.
7891 for (int GoodInput : GoodInputs)
7892 MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7895 if (BadInputs.size() == 2) {
7896 // If we have two bad inputs then there may be either one or two good
7897 // inputs fixed in place. Find a fixed input, and then find the *other*
7898 // two adjacent indices by using modular arithmetic.
7900 std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
7901 [](int M) { return M >= 0; }) -
7902 std::begin(MoveMask);
7904 ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
7905 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7906 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7907 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7908 MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
7909 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7910 Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
7912 assert(BadInputs.size() == 1 && "All sizes handled");
7913 int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
7914 std::end(MoveMask), -1) -
7915 std::begin(MoveMask);
7916 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7917 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7921 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7924 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7926 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7929 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7930 // cross-half traffic in the final shuffle.
7932 // Munge the mask to be a single-input mask after the unpack merges the
7936 M = 2 * (M % 4) + (M / 8);
7938 return DAG.getVectorShuffle(
7939 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7940 DL, MVT::v8i16, V1, V2),
7941 DAG.getUNDEF(MVT::v8i16), Mask);
7944 /// \brief Generic lowering of 8-lane i16 shuffles.
7946 /// This handles both single-input shuffles and combined shuffle/blends with
7947 /// two inputs. The single input shuffles are immediately delegated to
7948 /// a dedicated lowering routine.
7950 /// The blends are lowered in one of three fundamental ways. If there are few
7951 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7952 /// of the input is significantly cheaper when lowered as an interleaving of
7953 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7954 /// halves of the inputs separately (making them have relatively few inputs)
7955 /// and then concatenate them.
7956 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7957 const X86Subtarget *Subtarget,
7958 SelectionDAG &DAG) {
7960 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7961 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7962 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7963 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7964 ArrayRef<int> OrigMask = SVOp->getMask();
7965 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7966 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7967 MutableArrayRef<int> Mask(MaskStorage);
7969 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7971 auto isV1 = [](int M) { return M >= 0 && M < 8; };
7972 auto isV2 = [](int M) { return M >= 8; };
7974 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7975 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7977 if (NumV2Inputs == 0)
7978 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7980 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7981 "to be V1-input shuffles.");
7983 if (NumV1Inputs + NumV2Inputs <= 4)
7984 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7986 // Check whether an interleaving lowering is likely to be more efficient.
7987 // This isn't perfect but it is a strong heuristic that tends to work well on
7988 // the kinds of shuffles that show up in practice.
7990 // FIXME: Handle 1x, 2x, and 4x interleaving.
7991 if (shouldLowerAsInterleaving(Mask)) {
7992 // FIXME: Figure out whether we should pack these into the low or high
7995 int EMask[8], OMask[8];
7996 for (int i = 0; i < 4; ++i) {
7997 EMask[i] = Mask[2*i];
7998 OMask[i] = Mask[2*i + 1];
8003 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
8004 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
8006 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
8009 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8010 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8012 for (int i = 0; i < 4; ++i) {
8013 LoBlendMask[i] = Mask[i];
8014 HiBlendMask[i] = Mask[i + 4];
8017 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8018 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8019 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
8020 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
8022 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8023 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
8026 /// \brief Check whether a compaction lowering can be done by dropping even
8027 /// elements and compute how many times even elements must be dropped.
8029 /// This handles shuffles which take every Nth element where N is a power of
8030 /// two. Example shuffle masks:
8032 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8033 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8034 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8035 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8036 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8037 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8039 /// Any of these lanes can of course be undef.
8041 /// This routine only supports N <= 3.
8042 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8045 /// \returns N above, or the number of times even elements must be dropped if
8046 /// there is such a number. Otherwise returns zero.
8047 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8048 // Figure out whether we're looping over two inputs or just one.
8049 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8051 // The modulus for the shuffle vector entries is based on whether this is
8052 // a single input or not.
8053 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8054 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8055 "We should only be called with masks with a power-of-2 size!");
8057 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8059 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8060 // and 2^3 simultaneously. This is because we may have ambiguity with
8061 // partially undef inputs.
8062 bool ViableForN[3] = {true, true, true};
8064 for (int i = 0, e = Mask.size(); i < e; ++i) {
8065 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8070 bool IsAnyViable = false;
8071 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8072 if (ViableForN[j]) {
8075 // The shuffle mask must be equal to (i * 2^N) % M.
8076 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8079 ViableForN[j] = false;
8081 // Early exit if we exhaust the possible powers of two.
8086 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8090 // Return 0 as there is no viable power of two.
8094 /// \brief Generic lowering of v16i8 shuffles.
8096 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8097 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8098 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8099 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8101 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8102 const X86Subtarget *Subtarget,
8103 SelectionDAG &DAG) {
8105 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8106 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8107 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8108 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8109 ArrayRef<int> OrigMask = SVOp->getMask();
8110 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8111 int MaskStorage[16] = {
8112 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8113 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
8114 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
8115 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
8116 MutableArrayRef<int> Mask(MaskStorage);
8117 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
8118 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
8120 // For single-input shuffles, there are some nicer lowering tricks we can use.
8121 if (isSingleInputShuffleMask(Mask)) {
8122 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8123 // Notably, this handles splat and partial-splat shuffles more efficiently.
8124 // However, it only makes sense if the pre-duplication shuffle simplifies
8125 // things significantly. Currently, this means we need to be able to
8126 // express the pre-duplication shuffle as an i16 shuffle.
8128 // FIXME: We should check for other patterns which can be widened into an
8129 // i16 shuffle as well.
8130 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8131 for (int i = 0; i < 16; i += 2) {
8132 if (Mask[i] != Mask[i + 1])
8137 auto tryToWidenViaDuplication = [&]() -> SDValue {
8138 if (!canWidenViaDuplication(Mask))
8140 SmallVector<int, 4> LoInputs;
8141 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8142 [](int M) { return M >= 0 && M < 8; });
8143 std::sort(LoInputs.begin(), LoInputs.end());
8144 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8146 SmallVector<int, 4> HiInputs;
8147 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8148 [](int M) { return M >= 8; });
8149 std::sort(HiInputs.begin(), HiInputs.end());
8150 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8153 bool TargetLo = LoInputs.size() >= HiInputs.size();
8154 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8155 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8157 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8158 SmallDenseMap<int, int, 8> LaneMap;
8159 for (int I : InPlaceInputs) {
8160 PreDupI16Shuffle[I/2] = I/2;
8163 int j = TargetLo ? 0 : 4, je = j + 4;
8164 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8165 // Check if j is already a shuffle of this input. This happens when
8166 // there are two adjacent bytes after we move the low one.
8167 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8168 // If we haven't yet mapped the input, search for a slot into which
8170 while (j < je && PreDupI16Shuffle[j] != -1)
8174 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8177 // Map this input with the i16 shuffle.
8178 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8181 // Update the lane map based on the mapping we ended up with.
8182 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8185 ISD::BITCAST, DL, MVT::v16i8,
8186 DAG.getVectorShuffle(MVT::v8i16, DL,
8187 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8188 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8190 // Unpack the bytes to form the i16s that will be shuffled into place.
8191 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8192 MVT::v16i8, V1, V1);
8194 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8195 for (int i = 0; i < 16; i += 2) {
8197 PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8198 assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8201 ISD::BITCAST, DL, MVT::v16i8,
8202 DAG.getVectorShuffle(MVT::v8i16, DL,
8203 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8204 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8206 if (SDValue V = tryToWidenViaDuplication())
8210 // Check whether an interleaving lowering is likely to be more efficient.
8211 // This isn't perfect but it is a strong heuristic that tends to work well on
8212 // the kinds of shuffles that show up in practice.
8214 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8215 if (shouldLowerAsInterleaving(Mask)) {
8216 // FIXME: Figure out whether we should pack these into the low or high
8219 int EMask[16], OMask[16];
8220 for (int i = 0; i < 8; ++i) {
8221 EMask[i] = Mask[2*i];
8222 OMask[i] = Mask[2*i + 1];
8227 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8228 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8230 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8233 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8234 // with PSHUFB. It is important to do this before we attempt to generate any
8235 // blends but after all of the single-input lowerings. If the single input
8236 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8237 // want to preserve that and we can DAG combine any longer sequences into
8238 // a PSHUFB in the end. But once we start blending from multiple inputs,
8239 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8240 // and there are *very* few patterns that would actually be faster than the
8241 // PSHUFB approach because of its ability to zero lanes.
8243 // FIXME: The only exceptions to the above are blends which are exact
8244 // interleavings with direct instructions supporting them. We currently don't
8245 // handle those well here.
8246 if (Subtarget->hasSSSE3()) {
8249 for (int i = 0; i < 16; ++i)
8250 if (Mask[i] == -1) {
8251 V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8253 V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8255 DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8257 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8258 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8259 if (isSingleInputShuffleMask(Mask))
8260 return V1; // Single inputs are easy.
8262 // Otherwise, blend the two.
8263 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8264 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8265 return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8268 // Check whether a compaction lowering can be done. This handles shuffles
8269 // which take every Nth element for some even N. See the helper function for
8272 // We special case these as they can be particularly efficiently handled with
8273 // the PACKUSB instruction on x86 and they show up in common patterns of
8274 // rearranging bytes to truncate wide elements.
8275 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8276 // NumEvenDrops is the power of two stride of the elements. Another way of
8277 // thinking about it is that we need to drop the even elements this many
8278 // times to get the original input.
8279 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8281 // First we need to zero all the dropped bytes.
8282 assert(NumEvenDrops <= 3 &&
8283 "No support for dropping even elements more than 3 times.");
8284 // We use the mask type to pick which bytes are preserved based on how many
8285 // elements are dropped.
8286 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8287 SDValue ByteClearMask =
8288 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8289 DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8290 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8292 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8294 // Now pack things back together.
8295 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8296 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8297 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8298 for (int i = 1; i < NumEvenDrops; ++i) {
8299 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8300 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8306 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8307 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8308 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8309 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8311 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8312 MutableArrayRef<int> V1HalfBlendMask,
8313 MutableArrayRef<int> V2HalfBlendMask) {
8314 for (int i = 0; i < 8; ++i)
8315 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8316 V1HalfBlendMask[i] = HalfMask[i];
8318 } else if (HalfMask[i] >= 16) {
8319 V2HalfBlendMask[i] = HalfMask[i] - 16;
8320 HalfMask[i] = i + 8;
8323 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8324 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8326 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8328 auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8329 MutableArrayRef<int> HiBlendMask) {
8331 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8332 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8334 if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8335 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8336 std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8337 [](int M) { return M >= 0 && M % 2 == 1; })) {
8338 // Use a mask to drop the high bytes.
8339 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8340 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8341 DAG.getConstant(0x00FF, MVT::v8i16));
8343 // This will be a single vector shuffle instead of a blend so nuke V2.
8344 V2 = DAG.getUNDEF(MVT::v8i16);
8346 // Squash the masks to point directly into V1.
8347 for (int &M : LoBlendMask)
8350 for (int &M : HiBlendMask)
8354 // Otherwise just unpack the low half of V into V1 and the high half into
8355 // V2 so that we can blend them as i16s.
8356 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8357 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8358 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8359 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8362 SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8363 SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8364 return std::make_pair(BlendedLo, BlendedHi);
8366 SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8367 std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8368 std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8370 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8371 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8373 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8376 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8378 /// This routine breaks down the specific type of 128-bit shuffle and
8379 /// dispatches to the lowering routines accordingly.
8380 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8381 MVT VT, const X86Subtarget *Subtarget,
8382 SelectionDAG &DAG) {
8383 switch (VT.SimpleTy) {
8385 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8387 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8389 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8391 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8393 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8395 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8398 llvm_unreachable("Unimplemented!");
8402 static bool isHalfCrossingShuffleMask(ArrayRef<int> Mask) {
8403 int Size = Mask.size();
8404 for (int M : Mask.slice(0, Size / 2))
8405 if (M >= 0 && (M % Size) >= Size / 2)
8407 for (int M : Mask.slice(Size / 2, Size / 2))
8408 if (M >= 0 && (M % Size) < Size / 2)
8413 /// \brief Generic routine to split a 256-bit vector shuffle into 128-bit
8416 /// There is a severely limited set of shuffles available in AVX1 for 256-bit
8417 /// vectors resulting in routinely needing to split the shuffle into two 128-bit
8418 /// shuffles. This can be done generically for any 256-bit vector shuffle and so
8419 /// we encode the logic here for specific shuffle lowering routines to bail to
8420 /// when they exhaust the features avaible to more directly handle the shuffle.
8421 static SDValue splitAndLower256BitVectorShuffle(SDValue Op, SDValue V1,
8423 const X86Subtarget *Subtarget,
8424 SelectionDAG &DAG) {
8426 MVT VT = Op.getSimpleValueType();
8427 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8428 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8429 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8430 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8431 ArrayRef<int> Mask = SVOp->getMask();
8433 ArrayRef<int> LoMask = Mask.slice(0, Mask.size()/2);
8434 ArrayRef<int> HiMask = Mask.slice(Mask.size()/2);
8436 int NumElements = VT.getVectorNumElements();
8437 int SplitNumElements = NumElements / 2;
8438 MVT ScalarVT = VT.getScalarType();
8439 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8441 SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8442 DAG.getIntPtrConstant(0));
8443 SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8444 DAG.getIntPtrConstant(SplitNumElements));
8445 SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8446 DAG.getIntPtrConstant(0));
8447 SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8448 DAG.getIntPtrConstant(SplitNumElements));
8450 // Now create two 4-way blends of these half-width vectors.
8451 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8452 SmallVector<int, 16> V1BlendMask, V2BlendMask, BlendMask;
8453 for (int i = 0; i < SplitNumElements; ++i) {
8454 int M = HalfMask[i];
8455 if (M >= NumElements) {
8456 V2BlendMask.push_back(M - NumElements);
8457 V1BlendMask.push_back(-1);
8458 BlendMask.push_back(SplitNumElements + i);
8459 } else if (M >= 0) {
8460 V2BlendMask.push_back(-1);
8461 V1BlendMask.push_back(M);
8462 BlendMask.push_back(i);
8464 V2BlendMask.push_back(-1);
8465 V1BlendMask.push_back(-1);
8466 BlendMask.push_back(-1);
8469 SDValue V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8470 SDValue V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8471 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8473 SDValue Lo = HalfBlend(LoMask);
8474 SDValue Hi = HalfBlend(HiMask);
8475 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8478 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
8480 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
8481 /// isn't available.
8482 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8483 const X86Subtarget *Subtarget,
8484 SelectionDAG &DAG) {
8486 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8487 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8488 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8489 ArrayRef<int> Mask = SVOp->getMask();
8490 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8492 // FIXME: If we have AVX2, we should delegate to generic code as crossing
8493 // shuffles aren't a problem and FP and int have the same patterns.
8495 // FIXME: We can handle these more cleverly than splitting for v4f64.
8496 if (isHalfCrossingShuffleMask(Mask))
8497 return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8499 if (isSingleInputShuffleMask(Mask)) {
8500 // Non-half-crossing single input shuffles can be lowerid with an
8501 // interleaved permutation.
8502 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
8503 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
8504 return DAG.getNode(X86ISD::VPERMILP, DL, MVT::v4f64, V1,
8505 DAG.getConstant(VPERMILPMask, MVT::i8));
8508 // X86 has dedicated unpack instructions that can handle specific blend
8509 // operations: UNPCKH and UNPCKL.
8510 if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
8511 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
8512 if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
8513 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
8514 // FIXME: It would be nice to find a way to get canonicalization to commute
8516 if (isShuffleEquivalent(Mask, 4, 0, 6, 2))
8517 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
8518 if (isShuffleEquivalent(Mask, 5, 1, 7, 3))
8519 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
8521 // Check if the blend happens to exactly fit that of SHUFPD.
8522 if (Mask[0] < 4 && (Mask[1] == -1 || Mask[1] >= 4) &&
8523 Mask[2] < 4 && (Mask[3] == -1 || Mask[3] >= 4)) {
8524 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
8525 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
8526 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
8527 DAG.getConstant(SHUFPDMask, MVT::i8));
8529 if ((Mask[0] == -1 || Mask[0] >= 4) && Mask[1] < 4 &&
8530 (Mask[2] == -1 || Mask[2] >= 4) && Mask[3] < 4) {
8531 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
8532 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
8533 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
8534 DAG.getConstant(SHUFPDMask, MVT::i8));
8537 // Shuffle the input elements into the desired positions in V1 and V2 and
8538 // blend them together.
8539 int V1Mask[] = {-1, -1, -1, -1};
8540 int V2Mask[] = {-1, -1, -1, -1};
8541 for (int i = 0; i < 4; ++i)
8542 if (Mask[i] >= 0 && Mask[i] < 4)
8543 V1Mask[i] = Mask[i];
8544 else if (Mask[i] >= 4)
8545 V2Mask[i] = Mask[i] - 4;
8547 V1 = DAG.getVectorShuffle(MVT::v4f64, DL, V1, DAG.getUNDEF(MVT::v4f64), V1Mask);
8548 V2 = DAG.getVectorShuffle(MVT::v4f64, DL, V2, DAG.getUNDEF(MVT::v4f64), V2Mask);
8550 unsigned BlendMask = 0;
8551 for (int i = 0; i < 4; ++i)
8553 BlendMask |= 1 << i;
8555 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v4f64, V1, V2,
8556 DAG.getConstant(BlendMask, MVT::i8));
8559 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
8561 /// Largely delegates to common code when we have AVX2 and to the floating-point
8562 /// code when we only have AVX.
8563 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8564 const X86Subtarget *Subtarget,
8565 SelectionDAG &DAG) {
8567 assert(Op.getSimpleValueType() == MVT::v4i64 && "Bad shuffle type!");
8568 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8569 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8570 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8571 ArrayRef<int> Mask = SVOp->getMask();
8572 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8574 // FIXME: If we have AVX2, we should delegate to generic code as crossing
8575 // shuffles aren't a problem and FP and int have the same patterns.
8577 if (isHalfCrossingShuffleMask(Mask))
8578 return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8580 // AVX1 doesn't provide any facilities for v4i64 shuffles, bitcast and
8581 // delegate to floating point code.
8582 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V1);
8583 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V2);
8584 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i64,
8585 lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG));
8588 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
8590 /// This routine either breaks down the specific type of a 256-bit x86 vector
8591 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
8592 /// together based on the available instructions.
8593 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8594 MVT VT, const X86Subtarget *Subtarget,
8595 SelectionDAG &DAG) {
8596 switch (VT.SimpleTy) {
8598 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8600 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8605 // Fall back to the basic pattern of extracting the high half and forming
8607 // FIXME: Add targeted lowering for each type that can document rationale
8608 // for delegating to this when necessary.
8609 return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8612 llvm_unreachable("Not a valid 256-bit x86 vector type!");
8616 /// \brief Tiny helper function to test whether a shuffle mask could be
8617 /// simplified by widening the elements being shuffled.
8618 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
8619 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8620 if (Mask[i] % 2 != 0 || Mask[i] + 1 != Mask[i+1])
8626 /// \brief Top-level lowering for x86 vector shuffles.
8628 /// This handles decomposition, canonicalization, and lowering of all x86
8629 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8630 /// above in helper routines. The canonicalization attempts to widen shuffles
8631 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8632 /// s.t. only one of the two inputs needs to be tested, etc.
8633 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8634 SelectionDAG &DAG) {
8635 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8636 ArrayRef<int> Mask = SVOp->getMask();
8637 SDValue V1 = Op.getOperand(0);
8638 SDValue V2 = Op.getOperand(1);
8639 MVT VT = Op.getSimpleValueType();
8640 int NumElements = VT.getVectorNumElements();
8643 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8645 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8646 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8647 if (V1IsUndef && V2IsUndef)
8648 return DAG.getUNDEF(VT);
8650 // When we create a shuffle node we put the UNDEF node to second operand,
8651 // but in some cases the first operand may be transformed to UNDEF.
8652 // In this case we should just commute the node.
8654 return DAG.getCommutedVectorShuffle(*SVOp);
8656 // Check for non-undef masks pointing at an undef vector and make the masks
8657 // undef as well. This makes it easier to match the shuffle based solely on
8661 if (M >= NumElements) {
8662 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8663 for (int &M : NewMask)
8664 if (M >= NumElements)
8666 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8669 // For integer vector shuffles, try to collapse them into a shuffle of fewer
8670 // lanes but wider integers. We cap this to not form integers larger than i64
8671 // but it might be interesting to form i128 integers to handle flipping the
8672 // low and high halves of AVX 256-bit vectors.
8673 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8674 canWidenShuffleElements(Mask)) {
8675 SmallVector<int, 8> NewMask;
8676 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8677 NewMask.push_back(Mask[i] / 2);
8679 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8680 VT.getVectorNumElements() / 2);
8681 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8682 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8683 return DAG.getNode(ISD::BITCAST, dl, VT,
8684 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8687 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8688 for (int M : SVOp->getMask())
8691 else if (M < NumElements)
8696 // Commute the shuffle as needed such that more elements come from V1 than
8697 // V2. This allows us to match the shuffle pattern strictly on how many
8698 // elements come from V1 without handling the symmetric cases.
8699 if (NumV2Elements > NumV1Elements)
8700 return DAG.getCommutedVectorShuffle(*SVOp);
8702 // When the number of V1 and V2 elements are the same, try to minimize the
8703 // number of uses of V2 in the low half of the vector.
8704 if (NumV1Elements == NumV2Elements) {
8705 int LowV1Elements = 0, LowV2Elements = 0;
8706 for (int M : SVOp->getMask().slice(0, NumElements / 2))
8707 if (M >= NumElements)
8711 if (LowV2Elements > LowV1Elements)
8712 return DAG.getCommutedVectorShuffle(*SVOp);
8715 // For each vector width, delegate to a specialized lowering routine.
8716 if (VT.getSizeInBits() == 128)
8717 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8719 if (VT.getSizeInBits() == 256)
8720 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8722 llvm_unreachable("Unimplemented!");
8726 //===----------------------------------------------------------------------===//
8727 // Legacy vector shuffle lowering
8729 // This code is the legacy code handling vector shuffles until the above
8730 // replaces its functionality and performance.
8731 //===----------------------------------------------------------------------===//
8733 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8734 bool hasInt256, unsigned *MaskOut = nullptr) {
8735 MVT EltVT = VT.getVectorElementType();
8737 // There is no blend with immediate in AVX-512.
8738 if (VT.is512BitVector())
8741 if (!hasSSE41 || EltVT == MVT::i8)
8743 if (!hasInt256 && VT == MVT::v16i16)
8746 unsigned MaskValue = 0;
8747 unsigned NumElems = VT.getVectorNumElements();
8748 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8749 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8750 unsigned NumElemsInLane = NumElems / NumLanes;
8752 // Blend for v16i16 should be symetric for the both lanes.
8753 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8755 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8756 int EltIdx = MaskVals[i];
8758 if ((EltIdx < 0 || EltIdx == (int)i) &&
8759 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8762 if (((unsigned)EltIdx == (i + NumElems)) &&
8763 (SndLaneEltIdx < 0 ||
8764 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8765 MaskValue |= (1 << i);
8771 *MaskOut = MaskValue;
8775 // Try to lower a shuffle node into a simple blend instruction.
8776 // This function assumes isBlendMask returns true for this
8777 // SuffleVectorSDNode
8778 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8780 const X86Subtarget *Subtarget,
8781 SelectionDAG &DAG) {
8782 MVT VT = SVOp->getSimpleValueType(0);
8783 MVT EltVT = VT.getVectorElementType();
8784 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8785 Subtarget->hasInt256() && "Trying to lower a "
8786 "VECTOR_SHUFFLE to a Blend but "
8787 "with the wrong mask"));
8788 SDValue V1 = SVOp->getOperand(0);
8789 SDValue V2 = SVOp->getOperand(1);
8791 unsigned NumElems = VT.getVectorNumElements();
8793 // Convert i32 vectors to floating point if it is not AVX2.
8794 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8796 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8797 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8799 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8800 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8803 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8804 DAG.getConstant(MaskValue, MVT::i32));
8805 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8808 /// In vector type \p VT, return true if the element at index \p InputIdx
8809 /// falls on a different 128-bit lane than \p OutputIdx.
8810 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8811 unsigned OutputIdx) {
8812 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8813 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8816 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
8817 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
8818 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
8819 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8821 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8822 SelectionDAG &DAG) {
8823 MVT VT = V1.getSimpleValueType();
8824 assert(VT.is128BitVector() || VT.is256BitVector());
8826 MVT EltVT = VT.getVectorElementType();
8827 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8828 unsigned NumElts = VT.getVectorNumElements();
8830 SmallVector<SDValue, 32> PshufbMask;
8831 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8832 int InputIdx = MaskVals[OutputIdx];
8833 unsigned InputByteIdx;
8835 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8836 InputByteIdx = 0x80;
8838 // Cross lane is not allowed.
8839 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8841 InputByteIdx = InputIdx * EltSizeInBytes;
8842 // Index is an byte offset within the 128-bit lane.
8843 InputByteIdx &= 0xf;
8846 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8847 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8848 if (InputByteIdx != 0x80)
8853 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8855 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8856 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8857 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8860 // v8i16 shuffles - Prefer shuffles in the following order:
8861 // 1. [all] pshuflw, pshufhw, optional move
8862 // 2. [ssse3] 1 x pshufb
8863 // 3. [ssse3] 2 x pshufb + 1 x por
8864 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8866 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8867 SelectionDAG &DAG) {
8868 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8869 SDValue V1 = SVOp->getOperand(0);
8870 SDValue V2 = SVOp->getOperand(1);
8872 SmallVector<int, 8> MaskVals;
8874 // Determine if more than 1 of the words in each of the low and high quadwords
8875 // of the result come from the same quadword of one of the two inputs. Undef
8876 // mask values count as coming from any quadword, for better codegen.
8878 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8879 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8880 unsigned LoQuad[] = { 0, 0, 0, 0 };
8881 unsigned HiQuad[] = { 0, 0, 0, 0 };
8882 // Indices of quads used.
8883 std::bitset<4> InputQuads;
8884 for (unsigned i = 0; i < 8; ++i) {
8885 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8886 int EltIdx = SVOp->getMaskElt(i);
8887 MaskVals.push_back(EltIdx);
8896 InputQuads.set(EltIdx / 4);
8899 int BestLoQuad = -1;
8900 unsigned MaxQuad = 1;
8901 for (unsigned i = 0; i < 4; ++i) {
8902 if (LoQuad[i] > MaxQuad) {
8904 MaxQuad = LoQuad[i];
8908 int BestHiQuad = -1;
8910 for (unsigned i = 0; i < 4; ++i) {
8911 if (HiQuad[i] > MaxQuad) {
8913 MaxQuad = HiQuad[i];
8917 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8918 // of the two input vectors, shuffle them into one input vector so only a
8919 // single pshufb instruction is necessary. If there are more than 2 input
8920 // quads, disable the next transformation since it does not help SSSE3.
8921 bool V1Used = InputQuads[0] || InputQuads[1];
8922 bool V2Used = InputQuads[2] || InputQuads[3];
8923 if (Subtarget->hasSSSE3()) {
8924 if (InputQuads.count() == 2 && V1Used && V2Used) {
8925 BestLoQuad = InputQuads[0] ? 0 : 1;
8926 BestHiQuad = InputQuads[2] ? 2 : 3;
8928 if (InputQuads.count() > 2) {
8934 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8935 // the shuffle mask. If a quad is scored as -1, that means that it contains
8936 // words from all 4 input quadwords.
8938 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8940 BestLoQuad < 0 ? 0 : BestLoQuad,
8941 BestHiQuad < 0 ? 1 : BestHiQuad
8943 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8944 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8945 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8946 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8948 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8949 // source words for the shuffle, to aid later transformations.
8950 bool AllWordsInNewV = true;
8951 bool InOrder[2] = { true, true };
8952 for (unsigned i = 0; i != 8; ++i) {
8953 int idx = MaskVals[i];
8955 InOrder[i/4] = false;
8956 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8958 AllWordsInNewV = false;
8962 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8963 if (AllWordsInNewV) {
8964 for (int i = 0; i != 8; ++i) {
8965 int idx = MaskVals[i];
8968 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8969 if ((idx != i) && idx < 4)
8971 if ((idx != i) && idx > 3)
8980 // If we've eliminated the use of V2, and the new mask is a pshuflw or
8981 // pshufhw, that's as cheap as it gets. Return the new shuffle.
8982 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8983 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8984 unsigned TargetMask = 0;
8985 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8986 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8987 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8988 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8989 getShufflePSHUFLWImmediate(SVOp);
8990 V1 = NewV.getOperand(0);
8991 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8995 // Promote splats to a larger type which usually leads to more efficient code.
8996 // FIXME: Is this true if pshufb is available?
8997 if (SVOp->isSplat())
8998 return PromoteSplat(SVOp, DAG);
9000 // If we have SSSE3, and all words of the result are from 1 input vector,
9001 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
9002 // is present, fall back to case 4.
9003 if (Subtarget->hasSSSE3()) {
9004 SmallVector<SDValue,16> pshufbMask;
9006 // If we have elements from both input vectors, set the high bit of the
9007 // shuffle mask element to zero out elements that come from V2 in the V1
9008 // mask, and elements that come from V1 in the V2 mask, so that the two
9009 // results can be OR'd together.
9010 bool TwoInputs = V1Used && V2Used;
9011 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
9013 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9015 // Calculate the shuffle mask for the second input, shuffle it, and
9016 // OR it with the first shuffled input.
9017 CommuteVectorShuffleMask(MaskVals, 8);
9018 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
9019 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9020 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9023 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
9024 // and update MaskVals with new element order.
9025 std::bitset<8> InOrder;
9026 if (BestLoQuad >= 0) {
9027 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
9028 for (int i = 0; i != 4; ++i) {
9029 int idx = MaskVals[i];
9032 } else if ((idx / 4) == BestLoQuad) {
9037 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9040 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9041 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9042 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
9044 getShufflePSHUFLWImmediate(SVOp), DAG);
9048 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
9049 // and update MaskVals with the new element order.
9050 if (BestHiQuad >= 0) {
9051 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
9052 for (unsigned i = 4; i != 8; ++i) {
9053 int idx = MaskVals[i];
9056 } else if ((idx / 4) == BestHiQuad) {
9057 MaskV[i] = (idx & 3) + 4;
9061 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9064 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9065 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9066 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
9068 getShufflePSHUFHWImmediate(SVOp), DAG);
9072 // In case BestHi & BestLo were both -1, which means each quadword has a word
9073 // from each of the four input quadwords, calculate the InOrder bitvector now
9074 // before falling through to the insert/extract cleanup.
9075 if (BestLoQuad == -1 && BestHiQuad == -1) {
9077 for (int i = 0; i != 8; ++i)
9078 if (MaskVals[i] < 0 || MaskVals[i] == i)
9082 // The other elements are put in the right place using pextrw and pinsrw.
9083 for (unsigned i = 0; i != 8; ++i) {
9086 int EltIdx = MaskVals[i];
9089 SDValue ExtOp = (EltIdx < 8) ?
9090 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
9091 DAG.getIntPtrConstant(EltIdx)) :
9092 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
9093 DAG.getIntPtrConstant(EltIdx - 8));
9094 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
9095 DAG.getIntPtrConstant(i));
9100 /// \brief v16i16 shuffles
9102 /// FIXME: We only support generation of a single pshufb currently. We can
9103 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
9104 /// well (e.g 2 x pshufb + 1 x por).
9106 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
9107 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9108 SDValue V1 = SVOp->getOperand(0);
9109 SDValue V2 = SVOp->getOperand(1);
9112 if (V2.getOpcode() != ISD::UNDEF)
9115 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9116 return getPSHUFB(MaskVals, V1, dl, DAG);
9119 // v16i8 shuffles - Prefer shuffles in the following order:
9120 // 1. [ssse3] 1 x pshufb
9121 // 2. [ssse3] 2 x pshufb + 1 x por
9122 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
9123 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
9124 const X86Subtarget* Subtarget,
9125 SelectionDAG &DAG) {
9126 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9127 SDValue V1 = SVOp->getOperand(0);
9128 SDValue V2 = SVOp->getOperand(1);
9130 ArrayRef<int> MaskVals = SVOp->getMask();
9132 // Promote splats to a larger type which usually leads to more efficient code.
9133 // FIXME: Is this true if pshufb is available?
9134 if (SVOp->isSplat())
9135 return PromoteSplat(SVOp, DAG);
9137 // If we have SSSE3, case 1 is generated when all result bytes come from
9138 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
9139 // present, fall back to case 3.
9141 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
9142 if (Subtarget->hasSSSE3()) {
9143 SmallVector<SDValue,16> pshufbMask;
9145 // If all result elements are from one input vector, then only translate
9146 // undef mask values to 0x80 (zero out result) in the pshufb mask.
9148 // Otherwise, we have elements from both input vectors, and must zero out
9149 // elements that come from V2 in the first mask, and V1 in the second mask
9150 // so that we can OR them together.
9151 for (unsigned i = 0; i != 16; ++i) {
9152 int EltIdx = MaskVals[i];
9153 if (EltIdx < 0 || EltIdx >= 16)
9155 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9157 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
9158 DAG.getNode(ISD::BUILD_VECTOR, dl,
9159 MVT::v16i8, pshufbMask));
9161 // As PSHUFB will zero elements with negative indices, it's safe to ignore
9162 // the 2nd operand if it's undefined or zero.
9163 if (V2.getOpcode() == ISD::UNDEF ||
9164 ISD::isBuildVectorAllZeros(V2.getNode()))
9167 // Calculate the shuffle mask for the second input, shuffle it, and
9168 // OR it with the first shuffled input.
9170 for (unsigned i = 0; i != 16; ++i) {
9171 int EltIdx = MaskVals[i];
9172 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
9173 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9175 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
9176 DAG.getNode(ISD::BUILD_VECTOR, dl,
9177 MVT::v16i8, pshufbMask));
9178 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9181 // No SSSE3 - Calculate in place words and then fix all out of place words
9182 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
9183 // the 16 different words that comprise the two doublequadword input vectors.
9184 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9185 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9187 for (int i = 0; i != 8; ++i) {
9188 int Elt0 = MaskVals[i*2];
9189 int Elt1 = MaskVals[i*2+1];
9191 // This word of the result is all undef, skip it.
9192 if (Elt0 < 0 && Elt1 < 0)
9195 // This word of the result is already in the correct place, skip it.
9196 if ((Elt0 == i*2) && (Elt1 == i*2+1))
9199 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
9200 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
9203 // If Elt0 and Elt1 are defined, are consecutive, and can be load
9204 // using a single extract together, load it and store it.
9205 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
9206 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9207 DAG.getIntPtrConstant(Elt1 / 2));
9208 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9209 DAG.getIntPtrConstant(i));
9213 // If Elt1 is defined, extract it from the appropriate source. If the
9214 // source byte is not also odd, shift the extracted word left 8 bits
9215 // otherwise clear the bottom 8 bits if we need to do an or.
9217 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9218 DAG.getIntPtrConstant(Elt1 / 2));
9219 if ((Elt1 & 1) == 0)
9220 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
9222 TLI.getShiftAmountTy(InsElt.getValueType())));
9224 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
9225 DAG.getConstant(0xFF00, MVT::i16));
9227 // If Elt0 is defined, extract it from the appropriate source. If the
9228 // source byte is not also even, shift the extracted word right 8 bits. If
9229 // Elt1 was also defined, OR the extracted values together before
9230 // inserting them in the result.
9232 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
9233 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
9234 if ((Elt0 & 1) != 0)
9235 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
9237 TLI.getShiftAmountTy(InsElt0.getValueType())));
9239 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
9240 DAG.getConstant(0x00FF, MVT::i16));
9241 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
9244 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9245 DAG.getIntPtrConstant(i));
9247 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
9250 // v32i8 shuffles - Translate to VPSHUFB if possible.
9252 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
9253 const X86Subtarget *Subtarget,
9254 SelectionDAG &DAG) {
9255 MVT VT = SVOp->getSimpleValueType(0);
9256 SDValue V1 = SVOp->getOperand(0);
9257 SDValue V2 = SVOp->getOperand(1);
9259 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9261 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9262 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
9263 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
9265 // VPSHUFB may be generated if
9266 // (1) one of input vector is undefined or zeroinitializer.
9267 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
9268 // And (2) the mask indexes don't cross the 128-bit lane.
9269 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
9270 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
9273 if (V1IsAllZero && !V2IsAllZero) {
9274 CommuteVectorShuffleMask(MaskVals, 32);
9277 return getPSHUFB(MaskVals, V1, dl, DAG);
9280 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
9281 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
9282 /// done when every pair / quad of shuffle mask elements point to elements in
9283 /// the right sequence. e.g.
9284 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
9286 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
9287 SelectionDAG &DAG) {
9288 MVT VT = SVOp->getSimpleValueType(0);
9290 unsigned NumElems = VT.getVectorNumElements();
9293 switch (VT.SimpleTy) {
9294 default: llvm_unreachable("Unexpected!");
9297 return SDValue(SVOp, 0);
9298 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
9299 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
9300 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
9301 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
9302 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
9303 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
9306 SmallVector<int, 8> MaskVec;
9307 for (unsigned i = 0; i != NumElems; i += Scale) {
9309 for (unsigned j = 0; j != Scale; ++j) {
9310 int EltIdx = SVOp->getMaskElt(i+j);
9314 StartIdx = (EltIdx / Scale);
9315 if (EltIdx != (int)(StartIdx*Scale + j))
9318 MaskVec.push_back(StartIdx);
9321 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
9322 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
9323 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
9326 /// getVZextMovL - Return a zero-extending vector move low node.
9328 static SDValue getVZextMovL(MVT VT, MVT OpVT,
9329 SDValue SrcOp, SelectionDAG &DAG,
9330 const X86Subtarget *Subtarget, SDLoc dl) {
9331 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
9332 LoadSDNode *LD = nullptr;
9333 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
9334 LD = dyn_cast<LoadSDNode>(SrcOp);
9336 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
9338 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
9339 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
9340 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9341 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
9342 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
9344 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
9345 return DAG.getNode(ISD::BITCAST, dl, VT,
9346 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9347 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9355 return DAG.getNode(ISD::BITCAST, dl, VT,
9356 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9357 DAG.getNode(ISD::BITCAST, dl,
9361 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
9362 /// which could not be matched by any known target speficic shuffle
9364 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9366 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
9367 if (NewOp.getNode())
9370 MVT VT = SVOp->getSimpleValueType(0);
9372 unsigned NumElems = VT.getVectorNumElements();
9373 unsigned NumLaneElems = NumElems / 2;
9376 MVT EltVT = VT.getVectorElementType();
9377 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
9380 SmallVector<int, 16> Mask;
9381 for (unsigned l = 0; l < 2; ++l) {
9382 // Build a shuffle mask for the output, discovering on the fly which
9383 // input vectors to use as shuffle operands (recorded in InputUsed).
9384 // If building a suitable shuffle vector proves too hard, then bail
9385 // out with UseBuildVector set.
9386 bool UseBuildVector = false;
9387 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9388 unsigned LaneStart = l * NumLaneElems;
9389 for (unsigned i = 0; i != NumLaneElems; ++i) {
9390 // The mask element. This indexes into the input.
9391 int Idx = SVOp->getMaskElt(i+LaneStart);
9393 // the mask element does not index into any input vector.
9398 // The input vector this mask element indexes into.
9399 int Input = Idx / NumLaneElems;
9401 // Turn the index into an offset from the start of the input vector.
9402 Idx -= Input * NumLaneElems;
9404 // Find or create a shuffle vector operand to hold this input.
9406 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9407 if (InputUsed[OpNo] == Input)
9408 // This input vector is already an operand.
9410 if (InputUsed[OpNo] < 0) {
9411 // Create a new operand for this input vector.
9412 InputUsed[OpNo] = Input;
9417 if (OpNo >= array_lengthof(InputUsed)) {
9418 // More than two input vectors used! Give up on trying to create a
9419 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
9420 UseBuildVector = true;
9424 // Add the mask index for the new shuffle vector.
9425 Mask.push_back(Idx + OpNo * NumLaneElems);
9428 if (UseBuildVector) {
9429 SmallVector<SDValue, 16> SVOps;
9430 for (unsigned i = 0; i != NumLaneElems; ++i) {
9431 // The mask element. This indexes into the input.
9432 int Idx = SVOp->getMaskElt(i+LaneStart);
9434 SVOps.push_back(DAG.getUNDEF(EltVT));
9438 // The input vector this mask element indexes into.
9439 int Input = Idx / NumElems;
9441 // Turn the index into an offset from the start of the input vector.
9442 Idx -= Input * NumElems;
9444 // Extract the vector element by hand.
9445 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9446 SVOp->getOperand(Input),
9447 DAG.getIntPtrConstant(Idx)));
9450 // Construct the output using a BUILD_VECTOR.
9451 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9452 } else if (InputUsed[0] < 0) {
9453 // No input vectors were used! The result is undefined.
9454 Output[l] = DAG.getUNDEF(NVT);
9456 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9457 (InputUsed[0] % 2) * NumLaneElems,
9459 // If only one input was used, use an undefined vector for the other.
9460 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9461 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9462 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9463 // At least one input vector was used. Create a new shuffle vector.
9464 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9470 // Concatenate the result back
9471 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9474 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9475 /// 4 elements, and match them with several different shuffle types.
9477 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9478 SDValue V1 = SVOp->getOperand(0);
9479 SDValue V2 = SVOp->getOperand(1);
9481 MVT VT = SVOp->getSimpleValueType(0);
9483 assert(VT.is128BitVector() && "Unsupported vector size");
9485 std::pair<int, int> Locs[4];
9486 int Mask1[] = { -1, -1, -1, -1 };
9487 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9491 for (unsigned i = 0; i != 4; ++i) {
9492 int Idx = PermMask[i];
9494 Locs[i] = std::make_pair(-1, -1);
9496 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9498 Locs[i] = std::make_pair(0, NumLo);
9502 Locs[i] = std::make_pair(1, NumHi);
9504 Mask1[2+NumHi] = Idx;
9510 if (NumLo <= 2 && NumHi <= 2) {
9511 // If no more than two elements come from either vector. This can be
9512 // implemented with two shuffles. First shuffle gather the elements.
9513 // The second shuffle, which takes the first shuffle as both of its
9514 // vector operands, put the elements into the right order.
9515 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9517 int Mask2[] = { -1, -1, -1, -1 };
9519 for (unsigned i = 0; i != 4; ++i)
9520 if (Locs[i].first != -1) {
9521 unsigned Idx = (i < 2) ? 0 : 4;
9522 Idx += Locs[i].first * 2 + Locs[i].second;
9526 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9529 if (NumLo == 3 || NumHi == 3) {
9530 // Otherwise, we must have three elements from one vector, call it X, and
9531 // one element from the other, call it Y. First, use a shufps to build an
9532 // intermediate vector with the one element from Y and the element from X
9533 // that will be in the same half in the final destination (the indexes don't
9534 // matter). Then, use a shufps to build the final vector, taking the half
9535 // containing the element from Y from the intermediate, and the other half
9538 // Normalize it so the 3 elements come from V1.
9539 CommuteVectorShuffleMask(PermMask, 4);
9543 // Find the element from V2.
9545 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9546 int Val = PermMask[HiIndex];
9553 Mask1[0] = PermMask[HiIndex];
9555 Mask1[2] = PermMask[HiIndex^1];
9557 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9560 Mask1[0] = PermMask[0];
9561 Mask1[1] = PermMask[1];
9562 Mask1[2] = HiIndex & 1 ? 6 : 4;
9563 Mask1[3] = HiIndex & 1 ? 4 : 6;
9564 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9567 Mask1[0] = HiIndex & 1 ? 2 : 0;
9568 Mask1[1] = HiIndex & 1 ? 0 : 2;
9569 Mask1[2] = PermMask[2];
9570 Mask1[3] = PermMask[3];
9575 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9578 // Break it into (shuffle shuffle_hi, shuffle_lo).
9579 int LoMask[] = { -1, -1, -1, -1 };
9580 int HiMask[] = { -1, -1, -1, -1 };
9582 int *MaskPtr = LoMask;
9583 unsigned MaskIdx = 0;
9586 for (unsigned i = 0; i != 4; ++i) {
9593 int Idx = PermMask[i];
9595 Locs[i] = std::make_pair(-1, -1);
9596 } else if (Idx < 4) {
9597 Locs[i] = std::make_pair(MaskIdx, LoIdx);
9598 MaskPtr[LoIdx] = Idx;
9601 Locs[i] = std::make_pair(MaskIdx, HiIdx);
9602 MaskPtr[HiIdx] = Idx;
9607 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9608 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9609 int MaskOps[] = { -1, -1, -1, -1 };
9610 for (unsigned i = 0; i != 4; ++i)
9611 if (Locs[i].first != -1)
9612 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9613 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9616 static bool MayFoldVectorLoad(SDValue V) {
9617 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9618 V = V.getOperand(0);
9620 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9621 V = V.getOperand(0);
9622 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9623 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9624 // BUILD_VECTOR (load), undef
9625 V = V.getOperand(0);
9627 return MayFoldLoad(V);
9631 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9632 MVT VT = Op.getSimpleValueType();
9634 // Canonizalize to v2f64.
9635 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9636 return DAG.getNode(ISD::BITCAST, dl, VT,
9637 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9642 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9644 SDValue V1 = Op.getOperand(0);
9645 SDValue V2 = Op.getOperand(1);
9646 MVT VT = Op.getSimpleValueType();
9648 assert(VT != MVT::v2i64 && "unsupported shuffle type");
9650 if (HasSSE2 && VT == MVT::v2f64)
9651 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9653 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9654 return DAG.getNode(ISD::BITCAST, dl, VT,
9655 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9656 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9657 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9661 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9662 SDValue V1 = Op.getOperand(0);
9663 SDValue V2 = Op.getOperand(1);
9664 MVT VT = Op.getSimpleValueType();
9666 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9667 "unsupported shuffle type");
9669 if (V2.getOpcode() == ISD::UNDEF)
9673 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9677 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9678 SDValue V1 = Op.getOperand(0);
9679 SDValue V2 = Op.getOperand(1);
9680 MVT VT = Op.getSimpleValueType();
9681 unsigned NumElems = VT.getVectorNumElements();
9683 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9684 // operand of these instructions is only memory, so check if there's a
9685 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9687 bool CanFoldLoad = false;
9689 // Trivial case, when V2 comes from a load.
9690 if (MayFoldVectorLoad(V2))
9693 // When V1 is a load, it can be folded later into a store in isel, example:
9694 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9696 // (MOVLPSmr addr:$src1, VR128:$src2)
9697 // So, recognize this potential and also use MOVLPS or MOVLPD
9698 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9701 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9703 if (HasSSE2 && NumElems == 2)
9704 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9707 // If we don't care about the second element, proceed to use movss.
9708 if (SVOp->getMaskElt(1) != -1)
9709 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9712 // movl and movlp will both match v2i64, but v2i64 is never matched by
9713 // movl earlier because we make it strict to avoid messing with the movlp load
9714 // folding logic (see the code above getMOVLP call). Match it here then,
9715 // this is horrible, but will stay like this until we move all shuffle
9716 // matching to x86 specific nodes. Note that for the 1st condition all
9717 // types are matched with movsd.
9719 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9720 // as to remove this logic from here, as much as possible
9721 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9722 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9723 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9726 assert(VT != MVT::v4i32 && "unsupported shuffle type");
9728 // Invert the operand order and use SHUFPS to match it.
9729 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9730 getShuffleSHUFImmediate(SVOp), DAG);
9733 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9734 SelectionDAG &DAG) {
9736 MVT VT = Load->getSimpleValueType(0);
9737 MVT EVT = VT.getVectorElementType();
9738 SDValue Addr = Load->getOperand(1);
9739 SDValue NewAddr = DAG.getNode(
9740 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9741 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9744 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9745 DAG.getMachineFunction().getMachineMemOperand(
9746 Load->getMemOperand(), 0, EVT.getStoreSize()));
9750 // It is only safe to call this function if isINSERTPSMask is true for
9751 // this shufflevector mask.
9752 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9753 SelectionDAG &DAG) {
9754 // Generate an insertps instruction when inserting an f32 from memory onto a
9755 // v4f32 or when copying a member from one v4f32 to another.
9756 // We also use it for transferring i32 from one register to another,
9757 // since it simply copies the same bits.
9758 // If we're transferring an i32 from memory to a specific element in a
9759 // register, we output a generic DAG that will match the PINSRD
9761 MVT VT = SVOp->getSimpleValueType(0);
9762 MVT EVT = VT.getVectorElementType();
9763 SDValue V1 = SVOp->getOperand(0);
9764 SDValue V2 = SVOp->getOperand(1);
9765 auto Mask = SVOp->getMask();
9766 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9767 "unsupported vector type for insertps/pinsrd");
9769 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9770 auto FromV2Predicate = [](const int &i) { return i >= 4; };
9771 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9779 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9782 // If we have 1 element from each vector, we have to check if we're
9783 // changing V1's element's place. If so, we're done. Otherwise, we
9784 // should assume we're changing V2's element's place and behave
9786 int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9787 assert(DestIndex <= INT32_MAX && "truncated destination index");
9788 if (FromV1 == FromV2 &&
9789 static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9793 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9796 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9797 "More than one element from V1 and from V2, or no elements from one "
9798 "of the vectors. This case should not have returned true from "
9803 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9806 // Get an index into the source vector in the range [0,4) (the mask is
9807 // in the range [0,8) because it can address V1 and V2)
9808 unsigned SrcIndex = Mask[DestIndex] % 4;
9809 if (MayFoldLoad(From)) {
9810 // Trivial case, when From comes from a load and is only used by the
9811 // shuffle. Make it use insertps from the vector that we need from that
9814 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9815 if (!NewLoad.getNode())
9818 if (EVT == MVT::f32) {
9819 // Create this as a scalar to vector to match the instruction pattern.
9820 SDValue LoadScalarToVector =
9821 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9822 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9823 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9825 } else { // EVT == MVT::i32
9826 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9827 // instruction, to match the PINSRD instruction, which loads an i32 to a
9828 // certain vector element.
9829 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9830 DAG.getConstant(DestIndex, MVT::i32));
9834 // Vector-element-to-vector
9835 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9836 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9839 // Reduce a vector shuffle to zext.
9840 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9841 SelectionDAG &DAG) {
9842 // PMOVZX is only available from SSE41.
9843 if (!Subtarget->hasSSE41())
9846 MVT VT = Op.getSimpleValueType();
9848 // Only AVX2 support 256-bit vector integer extending.
9849 if (!Subtarget->hasInt256() && VT.is256BitVector())
9852 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9854 SDValue V1 = Op.getOperand(0);
9855 SDValue V2 = Op.getOperand(1);
9856 unsigned NumElems = VT.getVectorNumElements();
9858 // Extending is an unary operation and the element type of the source vector
9859 // won't be equal to or larger than i64.
9860 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9861 VT.getVectorElementType() == MVT::i64)
9864 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9865 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9866 while ((1U << Shift) < NumElems) {
9867 if (SVOp->getMaskElt(1U << Shift) == 1)
9870 // The maximal ratio is 8, i.e. from i8 to i64.
9875 // Check the shuffle mask.
9876 unsigned Mask = (1U << Shift) - 1;
9877 for (unsigned i = 0; i != NumElems; ++i) {
9878 int EltIdx = SVOp->getMaskElt(i);
9879 if ((i & Mask) != 0 && EltIdx != -1)
9881 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9885 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9886 MVT NeVT = MVT::getIntegerVT(NBits);
9887 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9889 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9892 // Simplify the operand as it's prepared to be fed into shuffle.
9893 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9894 if (V1.getOpcode() == ISD::BITCAST &&
9895 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9896 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9897 V1.getOperand(0).getOperand(0)
9898 .getSimpleValueType().getSizeInBits() == SignificantBits) {
9899 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9900 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9901 ConstantSDNode *CIdx =
9902 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9903 // If it's foldable, i.e. normal load with single use, we will let code
9904 // selection to fold it. Otherwise, we will short the conversion sequence.
9905 if (CIdx && CIdx->getZExtValue() == 0 &&
9906 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9907 MVT FullVT = V.getSimpleValueType();
9908 MVT V1VT = V1.getSimpleValueType();
9909 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9910 // The "ext_vec_elt" node is wider than the result node.
9911 // In this case we should extract subvector from V.
9912 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9913 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9914 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9915 FullVT.getVectorNumElements()/Ratio);
9916 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9917 DAG.getIntPtrConstant(0));
9919 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9923 return DAG.getNode(ISD::BITCAST, DL, VT,
9924 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9927 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9928 SelectionDAG &DAG) {
9929 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9930 MVT VT = Op.getSimpleValueType();
9932 SDValue V1 = Op.getOperand(0);
9933 SDValue V2 = Op.getOperand(1);
9935 if (isZeroShuffle(SVOp))
9936 return getZeroVector(VT, Subtarget, DAG, dl);
9938 // Handle splat operations
9939 if (SVOp->isSplat()) {
9940 // Use vbroadcast whenever the splat comes from a foldable load
9941 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9942 if (Broadcast.getNode())
9946 // Check integer expanding shuffles.
9947 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9948 if (NewOp.getNode())
9951 // If the shuffle can be profitably rewritten as a narrower shuffle, then
9953 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9955 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9956 if (NewOp.getNode())
9957 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9958 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9959 // FIXME: Figure out a cleaner way to do this.
9960 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9961 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9962 if (NewOp.getNode()) {
9963 MVT NewVT = NewOp.getSimpleValueType();
9964 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9965 NewVT, true, false))
9966 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9969 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9970 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9971 if (NewOp.getNode()) {
9972 MVT NewVT = NewOp.getSimpleValueType();
9973 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9974 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9983 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9984 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9985 SDValue V1 = Op.getOperand(0);
9986 SDValue V2 = Op.getOperand(1);
9987 MVT VT = Op.getSimpleValueType();
9989 unsigned NumElems = VT.getVectorNumElements();
9990 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9991 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9992 bool V1IsSplat = false;
9993 bool V2IsSplat = false;
9994 bool HasSSE2 = Subtarget->hasSSE2();
9995 bool HasFp256 = Subtarget->hasFp256();
9996 bool HasInt256 = Subtarget->hasInt256();
9997 MachineFunction &MF = DAG.getMachineFunction();
9998 bool OptForSize = MF.getFunction()->getAttributes().
9999 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
10001 // Check if we should use the experimental vector shuffle lowering. If so,
10002 // delegate completely to that code path.
10003 if (ExperimentalVectorShuffleLowering)
10004 return lowerVectorShuffle(Op, Subtarget, DAG);
10006 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10008 if (V1IsUndef && V2IsUndef)
10009 return DAG.getUNDEF(VT);
10011 // When we create a shuffle node we put the UNDEF node to second operand,
10012 // but in some cases the first operand may be transformed to UNDEF.
10013 // In this case we should just commute the node.
10015 return DAG.getCommutedVectorShuffle(*SVOp);
10017 // Vector shuffle lowering takes 3 steps:
10019 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
10020 // narrowing and commutation of operands should be handled.
10021 // 2) Matching of shuffles with known shuffle masks to x86 target specific
10023 // 3) Rewriting of unmatched masks into new generic shuffle operations,
10024 // so the shuffle can be broken into other shuffles and the legalizer can
10025 // try the lowering again.
10027 // The general idea is that no vector_shuffle operation should be left to
10028 // be matched during isel, all of them must be converted to a target specific
10031 // Normalize the input vectors. Here splats, zeroed vectors, profitable
10032 // narrowing and commutation of operands should be handled. The actual code
10033 // doesn't include all of those, work in progress...
10034 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
10035 if (NewOp.getNode())
10038 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
10040 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
10041 // unpckh_undef). Only use pshufd if speed is more important than size.
10042 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10043 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10044 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10045 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10047 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
10048 V2IsUndef && MayFoldVectorLoad(V1))
10049 return getMOVDDup(Op, dl, V1, DAG);
10051 if (isMOVHLPS_v_undef_Mask(M, VT))
10052 return getMOVHighToLow(Op, dl, DAG);
10054 // Use to match splats
10055 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
10056 (VT == MVT::v2f64 || VT == MVT::v2i64))
10057 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10059 if (isPSHUFDMask(M, VT)) {
10060 // The actual implementation will match the mask in the if above and then
10061 // during isel it can match several different instructions, not only pshufd
10062 // as its name says, sad but true, emulate the behavior for now...
10063 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
10064 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
10066 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
10068 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
10069 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
10071 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
10072 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
10075 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
10079 if (isPALIGNRMask(M, VT, Subtarget))
10080 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
10081 getShufflePALIGNRImmediate(SVOp),
10084 if (isVALIGNMask(M, VT, Subtarget))
10085 return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
10086 getShuffleVALIGNImmediate(SVOp),
10089 // Check if this can be converted into a logical shift.
10090 bool isLeft = false;
10091 unsigned ShAmt = 0;
10093 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
10094 if (isShift && ShVal.hasOneUse()) {
10095 // If the shifted value has multiple uses, it may be cheaper to use
10096 // v_set0 + movlhps or movhlps, etc.
10097 MVT EltVT = VT.getVectorElementType();
10098 ShAmt *= EltVT.getSizeInBits();
10099 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10102 if (isMOVLMask(M, VT)) {
10103 if (ISD::isBuildVectorAllZeros(V1.getNode()))
10104 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
10105 if (!isMOVLPMask(M, VT)) {
10106 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
10107 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10109 if (VT == MVT::v4i32 || VT == MVT::v4f32)
10110 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10114 // FIXME: fold these into legal mask.
10115 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
10116 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
10118 if (isMOVHLPSMask(M, VT))
10119 return getMOVHighToLow(Op, dl, DAG);
10121 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
10122 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
10124 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
10125 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
10127 if (isMOVLPMask(M, VT))
10128 return getMOVLP(Op, dl, DAG, HasSSE2);
10130 if (ShouldXformToMOVHLPS(M, VT) ||
10131 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
10132 return DAG.getCommutedVectorShuffle(*SVOp);
10135 // No better options. Use a vshldq / vsrldq.
10136 MVT EltVT = VT.getVectorElementType();
10137 ShAmt *= EltVT.getSizeInBits();
10138 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10141 bool Commuted = false;
10142 // FIXME: This should also accept a bitcast of a splat? Be careful, not
10143 // 1,1,1,1 -> v8i16 though.
10144 BitVector UndefElements;
10145 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
10146 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10148 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
10149 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10152 // Canonicalize the splat or undef, if present, to be on the RHS.
10153 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
10154 CommuteVectorShuffleMask(M, NumElems);
10156 std::swap(V1IsSplat, V2IsSplat);
10160 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
10161 // Shuffling low element of v1 into undef, just return v1.
10164 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
10165 // the instruction selector will not match, so get a canonical MOVL with
10166 // swapped operands to undo the commute.
10167 return getMOVL(DAG, dl, VT, V2, V1);
10170 if (isUNPCKLMask(M, VT, HasInt256))
10171 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10173 if (isUNPCKHMask(M, VT, HasInt256))
10174 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10177 // Normalize mask so all entries that point to V2 points to its first
10178 // element then try to match unpck{h|l} again. If match, return a
10179 // new vector_shuffle with the corrected mask.p
10180 SmallVector<int, 8> NewMask(M.begin(), M.end());
10181 NormalizeMask(NewMask, NumElems);
10182 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
10183 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10184 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
10185 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10189 // Commute is back and try unpck* again.
10190 // FIXME: this seems wrong.
10191 CommuteVectorShuffleMask(M, NumElems);
10193 std::swap(V1IsSplat, V2IsSplat);
10195 if (isUNPCKLMask(M, VT, HasInt256))
10196 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10198 if (isUNPCKHMask(M, VT, HasInt256))
10199 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10202 // Normalize the node to match x86 shuffle ops if needed
10203 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
10204 return DAG.getCommutedVectorShuffle(*SVOp);
10206 // The checks below are all present in isShuffleMaskLegal, but they are
10207 // inlined here right now to enable us to directly emit target specific
10208 // nodes, and remove one by one until they don't return Op anymore.
10210 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
10211 SVOp->getSplatIndex() == 0 && V2IsUndef) {
10212 if (VT == MVT::v2f64 || VT == MVT::v2i64)
10213 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10216 if (isPSHUFHWMask(M, VT, HasInt256))
10217 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
10218 getShufflePSHUFHWImmediate(SVOp),
10221 if (isPSHUFLWMask(M, VT, HasInt256))
10222 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
10223 getShufflePSHUFLWImmediate(SVOp),
10226 unsigned MaskValue;
10227 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
10229 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
10231 if (isSHUFPMask(M, VT))
10232 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
10233 getShuffleSHUFImmediate(SVOp), DAG);
10235 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10236 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10237 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10238 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10240 //===--------------------------------------------------------------------===//
10241 // Generate target specific nodes for 128 or 256-bit shuffles only
10242 // supported in the AVX instruction set.
10245 // Handle VMOVDDUPY permutations
10246 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
10247 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
10249 // Handle VPERMILPS/D* permutations
10250 if (isVPERMILPMask(M, VT)) {
10251 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
10252 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
10253 getShuffleSHUFImmediate(SVOp), DAG);
10254 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
10255 getShuffleSHUFImmediate(SVOp), DAG);
10259 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
10260 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
10261 Idx*(NumElems/2), DAG, dl);
10263 // Handle VPERM2F128/VPERM2I128 permutations
10264 if (isVPERM2X128Mask(M, VT, HasFp256))
10265 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
10266 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
10268 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
10269 return getINSERTPS(SVOp, dl, DAG);
10272 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
10273 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
10275 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
10276 VT.is512BitVector()) {
10277 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
10278 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
10279 SmallVector<SDValue, 16> permclMask;
10280 for (unsigned i = 0; i != NumElems; ++i) {
10281 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
10284 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
10286 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
10287 return DAG.getNode(X86ISD::VPERMV, dl, VT,
10288 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
10289 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
10290 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
10293 //===--------------------------------------------------------------------===//
10294 // Since no target specific shuffle was selected for this generic one,
10295 // lower it into other known shuffles. FIXME: this isn't true yet, but
10296 // this is the plan.
10299 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
10300 if (VT == MVT::v8i16) {
10301 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
10302 if (NewOp.getNode())
10306 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
10307 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
10308 if (NewOp.getNode())
10312 if (VT == MVT::v16i8) {
10313 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
10314 if (NewOp.getNode())
10318 if (VT == MVT::v32i8) {
10319 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
10320 if (NewOp.getNode())
10324 // Handle all 128-bit wide vectors with 4 elements, and match them with
10325 // several different shuffle types.
10326 if (NumElems == 4 && VT.is128BitVector())
10327 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
10329 // Handle general 256-bit shuffles
10330 if (VT.is256BitVector())
10331 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
10336 // This function assumes its argument is a BUILD_VECTOR of constants or
10337 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10339 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10340 unsigned &MaskValue) {
10342 unsigned NumElems = BuildVector->getNumOperands();
10343 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10344 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10345 unsigned NumElemsInLane = NumElems / NumLanes;
10347 // Blend for v16i16 should be symetric for the both lanes.
10348 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10349 SDValue EltCond = BuildVector->getOperand(i);
10350 SDValue SndLaneEltCond =
10351 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10353 int Lane1Cond = -1, Lane2Cond = -1;
10354 if (isa<ConstantSDNode>(EltCond))
10355 Lane1Cond = !isZero(EltCond);
10356 if (isa<ConstantSDNode>(SndLaneEltCond))
10357 Lane2Cond = !isZero(SndLaneEltCond);
10359 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10360 // Lane1Cond != 0, means we want the first argument.
10361 // Lane1Cond == 0, means we want the second argument.
10362 // The encoding of this argument is 0 for the first argument, 1
10363 // for the second. Therefore, invert the condition.
10364 MaskValue |= !Lane1Cond << i;
10365 else if (Lane1Cond < 0)
10366 MaskValue |= !Lane2Cond << i;
10373 // Try to lower a vselect node into a simple blend instruction.
10374 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
10375 SelectionDAG &DAG) {
10376 SDValue Cond = Op.getOperand(0);
10377 SDValue LHS = Op.getOperand(1);
10378 SDValue RHS = Op.getOperand(2);
10380 MVT VT = Op.getSimpleValueType();
10381 MVT EltVT = VT.getVectorElementType();
10382 unsigned NumElems = VT.getVectorNumElements();
10384 // There is no blend with immediate in AVX-512.
10385 if (VT.is512BitVector())
10388 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10390 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10393 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10396 // Check the mask for BLEND and build the value.
10397 unsigned MaskValue = 0;
10398 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10401 // Convert i32 vectors to floating point if it is not AVX2.
10402 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10404 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10405 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10407 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10408 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10411 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10412 DAG.getConstant(MaskValue, MVT::i32));
10413 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10416 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10417 // A vselect where all conditions and data are constants can be optimized into
10418 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10419 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10420 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10421 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10424 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10425 if (BlendOp.getNode())
10428 // Some types for vselect were previously set to Expand, not Legal or
10429 // Custom. Return an empty SDValue so we fall-through to Expand, after
10430 // the Custom lowering phase.
10431 MVT VT = Op.getSimpleValueType();
10432 switch (VT.SimpleTy) {
10440 // We couldn't create a "Blend with immediate" node.
10441 // This node should still be legal, but we'll have to emit a blendv*
10446 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10447 MVT VT = Op.getSimpleValueType();
10450 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10453 if (VT.getSizeInBits() == 8) {
10454 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10455 Op.getOperand(0), Op.getOperand(1));
10456 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10457 DAG.getValueType(VT));
10458 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10461 if (VT.getSizeInBits() == 16) {
10462 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10463 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10465 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10466 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10467 DAG.getNode(ISD::BITCAST, dl,
10470 Op.getOperand(1)));
10471 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10472 Op.getOperand(0), Op.getOperand(1));
10473 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10474 DAG.getValueType(VT));
10475 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10478 if (VT == MVT::f32) {
10479 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10480 // the result back to FR32 register. It's only worth matching if the
10481 // result has a single use which is a store or a bitcast to i32. And in
10482 // the case of a store, it's not worth it if the index is a constant 0,
10483 // because a MOVSSmr can be used instead, which is smaller and faster.
10484 if (!Op.hasOneUse())
10486 SDNode *User = *Op.getNode()->use_begin();
10487 if ((User->getOpcode() != ISD::STORE ||
10488 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10489 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10490 (User->getOpcode() != ISD::BITCAST ||
10491 User->getValueType(0) != MVT::i32))
10493 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10494 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10497 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10500 if (VT == MVT::i32 || VT == MVT::i64) {
10501 // ExtractPS/pextrq works with constant index.
10502 if (isa<ConstantSDNode>(Op.getOperand(1)))
10508 /// Extract one bit from mask vector, like v16i1 or v8i1.
10509 /// AVX-512 feature.
10511 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10512 SDValue Vec = Op.getOperand(0);
10514 MVT VecVT = Vec.getSimpleValueType();
10515 SDValue Idx = Op.getOperand(1);
10516 MVT EltVT = Op.getSimpleValueType();
10518 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10520 // variable index can't be handled in mask registers,
10521 // extend vector to VR512
10522 if (!isa<ConstantSDNode>(Idx)) {
10523 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10524 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10525 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10526 ExtVT.getVectorElementType(), Ext, Idx);
10527 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10530 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10531 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10532 unsigned MaxSift = rc->getSize()*8 - 1;
10533 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10534 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10535 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10536 DAG.getConstant(MaxSift, MVT::i8));
10537 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10538 DAG.getIntPtrConstant(0));
10542 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10543 SelectionDAG &DAG) const {
10545 SDValue Vec = Op.getOperand(0);
10546 MVT VecVT = Vec.getSimpleValueType();
10547 SDValue Idx = Op.getOperand(1);
10549 if (Op.getSimpleValueType() == MVT::i1)
10550 return ExtractBitFromMaskVector(Op, DAG);
10552 if (!isa<ConstantSDNode>(Idx)) {
10553 if (VecVT.is512BitVector() ||
10554 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10555 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10558 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10559 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10560 MaskEltVT.getSizeInBits());
10562 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10563 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10564 getZeroVector(MaskVT, Subtarget, DAG, dl),
10565 Idx, DAG.getConstant(0, getPointerTy()));
10566 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10567 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10568 Perm, DAG.getConstant(0, getPointerTy()));
10573 // If this is a 256-bit vector result, first extract the 128-bit vector and
10574 // then extract the element from the 128-bit vector.
10575 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10577 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10578 // Get the 128-bit vector.
10579 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10580 MVT EltVT = VecVT.getVectorElementType();
10582 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10584 //if (IdxVal >= NumElems/2)
10585 // IdxVal -= NumElems/2;
10586 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10587 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10588 DAG.getConstant(IdxVal, MVT::i32));
10591 assert(VecVT.is128BitVector() && "Unexpected vector length");
10593 if (Subtarget->hasSSE41()) {
10594 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10599 MVT VT = Op.getSimpleValueType();
10600 // TODO: handle v16i8.
10601 if (VT.getSizeInBits() == 16) {
10602 SDValue Vec = Op.getOperand(0);
10603 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10605 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10606 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10607 DAG.getNode(ISD::BITCAST, dl,
10609 Op.getOperand(1)));
10610 // Transform it so it match pextrw which produces a 32-bit result.
10611 MVT EltVT = MVT::i32;
10612 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10613 Op.getOperand(0), Op.getOperand(1));
10614 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10615 DAG.getValueType(VT));
10616 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10619 if (VT.getSizeInBits() == 32) {
10620 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10624 // SHUFPS the element to the lowest double word, then movss.
10625 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10626 MVT VVT = Op.getOperand(0).getSimpleValueType();
10627 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10628 DAG.getUNDEF(VVT), Mask);
10629 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10630 DAG.getIntPtrConstant(0));
10633 if (VT.getSizeInBits() == 64) {
10634 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10635 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10636 // to match extract_elt for f64.
10637 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10641 // UNPCKHPD the element to the lowest double word, then movsd.
10642 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10643 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10644 int Mask[2] = { 1, -1 };
10645 MVT VVT = Op.getOperand(0).getSimpleValueType();
10646 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10647 DAG.getUNDEF(VVT), Mask);
10648 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10649 DAG.getIntPtrConstant(0));
10655 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10656 MVT VT = Op.getSimpleValueType();
10657 MVT EltVT = VT.getVectorElementType();
10660 SDValue N0 = Op.getOperand(0);
10661 SDValue N1 = Op.getOperand(1);
10662 SDValue N2 = Op.getOperand(2);
10664 if (!VT.is128BitVector())
10667 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
10668 isa<ConstantSDNode>(N2)) {
10670 if (VT == MVT::v8i16) {
10671 Opc = X86ISD::PINSRW;
10673 assert(VT == MVT::v16i8);
10674 Opc = X86ISD::PINSRB;
10677 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10679 if (N1.getValueType() != MVT::i32)
10680 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10681 if (N2.getValueType() != MVT::i32)
10682 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10683 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10686 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
10687 // Bits [7:6] of the constant are the source select. This will always be
10688 // zero here. The DAG Combiner may combine an extract_elt index into these
10689 // bits. For example (insert (extract, 3), 2) could be matched by putting
10690 // the '3' into bits [7:6] of X86ISD::INSERTPS.
10691 // Bits [5:4] of the constant are the destination select. This is the
10692 // value of the incoming immediate.
10693 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10694 // combine either bitwise AND or insert of float 0.0 to set these bits.
10695 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10696 // Create this as a scalar to vector..
10697 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10698 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10701 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10702 // PINSR* works with constant index.
10708 /// Insert one bit to mask vector, like v16i1 or v8i1.
10709 /// AVX-512 feature.
10711 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10713 SDValue Vec = Op.getOperand(0);
10714 SDValue Elt = Op.getOperand(1);
10715 SDValue Idx = Op.getOperand(2);
10716 MVT VecVT = Vec.getSimpleValueType();
10718 if (!isa<ConstantSDNode>(Idx)) {
10719 // Non constant index. Extend source and destination,
10720 // insert element and then truncate the result.
10721 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10722 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10723 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10724 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10725 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10726 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10729 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10730 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10731 if (Vec.getOpcode() == ISD::UNDEF)
10732 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10733 DAG.getConstant(IdxVal, MVT::i8));
10734 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10735 unsigned MaxSift = rc->getSize()*8 - 1;
10736 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10737 DAG.getConstant(MaxSift, MVT::i8));
10738 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10739 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10740 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10743 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10744 MVT VT = Op.getSimpleValueType();
10745 MVT EltVT = VT.getVectorElementType();
10747 if (EltVT == MVT::i1)
10748 return InsertBitToMaskVector(Op, DAG);
10751 SDValue N0 = Op.getOperand(0);
10752 SDValue N1 = Op.getOperand(1);
10753 SDValue N2 = Op.getOperand(2);
10755 // If this is a 256-bit vector result, first extract the 128-bit vector,
10756 // insert the element into the extracted half and then place it back.
10757 if (VT.is256BitVector() || VT.is512BitVector()) {
10758 if (!isa<ConstantSDNode>(N2))
10761 // Get the desired 128-bit vector half.
10762 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10763 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10765 // Insert the element into the desired half.
10766 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10767 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10769 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10770 DAG.getConstant(IdxIn128, MVT::i32));
10772 // Insert the changed part back to the 256-bit vector
10773 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10776 if (Subtarget->hasSSE41())
10777 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10779 if (EltVT == MVT::i8)
10782 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10783 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10784 // as its second argument.
10785 if (N1.getValueType() != MVT::i32)
10786 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10787 if (N2.getValueType() != MVT::i32)
10788 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10789 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10794 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10796 MVT OpVT = Op.getSimpleValueType();
10798 // If this is a 256-bit vector result, first insert into a 128-bit
10799 // vector and then insert into the 256-bit vector.
10800 if (!OpVT.is128BitVector()) {
10801 // Insert into a 128-bit vector.
10802 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10803 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10804 OpVT.getVectorNumElements() / SizeFactor);
10806 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10808 // Insert the 128-bit vector.
10809 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10812 if (OpVT == MVT::v1i64 &&
10813 Op.getOperand(0).getValueType() == MVT::i64)
10814 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10816 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10817 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10818 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10819 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10822 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10823 // a simple subregister reference or explicit instructions to grab
10824 // upper bits of a vector.
10825 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10826 SelectionDAG &DAG) {
10828 SDValue In = Op.getOperand(0);
10829 SDValue Idx = Op.getOperand(1);
10830 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10831 MVT ResVT = Op.getSimpleValueType();
10832 MVT InVT = In.getSimpleValueType();
10834 if (Subtarget->hasFp256()) {
10835 if (ResVT.is128BitVector() &&
10836 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10837 isa<ConstantSDNode>(Idx)) {
10838 return Extract128BitVector(In, IdxVal, DAG, dl);
10840 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10841 isa<ConstantSDNode>(Idx)) {
10842 return Extract256BitVector(In, IdxVal, DAG, dl);
10848 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10849 // simple superregister reference or explicit instructions to insert
10850 // the upper bits of a vector.
10851 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10852 SelectionDAG &DAG) {
10853 if (Subtarget->hasFp256()) {
10854 SDLoc dl(Op.getNode());
10855 SDValue Vec = Op.getNode()->getOperand(0);
10856 SDValue SubVec = Op.getNode()->getOperand(1);
10857 SDValue Idx = Op.getNode()->getOperand(2);
10859 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10860 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10861 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10862 isa<ConstantSDNode>(Idx)) {
10863 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10864 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10867 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10868 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10869 isa<ConstantSDNode>(Idx)) {
10870 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10871 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10877 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10878 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10879 // one of the above mentioned nodes. It has to be wrapped because otherwise
10880 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10881 // be used to form addressing mode. These wrapped nodes will be selected
10884 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10885 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10887 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10888 // global base reg.
10889 unsigned char OpFlag = 0;
10890 unsigned WrapperKind = X86ISD::Wrapper;
10891 CodeModel::Model M = DAG.getTarget().getCodeModel();
10893 if (Subtarget->isPICStyleRIPRel() &&
10894 (M == CodeModel::Small || M == CodeModel::Kernel))
10895 WrapperKind = X86ISD::WrapperRIP;
10896 else if (Subtarget->isPICStyleGOT())
10897 OpFlag = X86II::MO_GOTOFF;
10898 else if (Subtarget->isPICStyleStubPIC())
10899 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10901 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10902 CP->getAlignment(),
10903 CP->getOffset(), OpFlag);
10905 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10906 // With PIC, the address is actually $g + Offset.
10908 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10909 DAG.getNode(X86ISD::GlobalBaseReg,
10910 SDLoc(), getPointerTy()),
10917 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10918 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10920 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10921 // global base reg.
10922 unsigned char OpFlag = 0;
10923 unsigned WrapperKind = X86ISD::Wrapper;
10924 CodeModel::Model M = DAG.getTarget().getCodeModel();
10926 if (Subtarget->isPICStyleRIPRel() &&
10927 (M == CodeModel::Small || M == CodeModel::Kernel))
10928 WrapperKind = X86ISD::WrapperRIP;
10929 else if (Subtarget->isPICStyleGOT())
10930 OpFlag = X86II::MO_GOTOFF;
10931 else if (Subtarget->isPICStyleStubPIC())
10932 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10934 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10937 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10939 // With PIC, the address is actually $g + Offset.
10941 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10942 DAG.getNode(X86ISD::GlobalBaseReg,
10943 SDLoc(), getPointerTy()),
10950 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10951 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10953 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10954 // global base reg.
10955 unsigned char OpFlag = 0;
10956 unsigned WrapperKind = X86ISD::Wrapper;
10957 CodeModel::Model M = DAG.getTarget().getCodeModel();
10959 if (Subtarget->isPICStyleRIPRel() &&
10960 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10961 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10962 OpFlag = X86II::MO_GOTPCREL;
10963 WrapperKind = X86ISD::WrapperRIP;
10964 } else if (Subtarget->isPICStyleGOT()) {
10965 OpFlag = X86II::MO_GOT;
10966 } else if (Subtarget->isPICStyleStubPIC()) {
10967 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10968 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10969 OpFlag = X86II::MO_DARWIN_NONLAZY;
10972 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10975 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10977 // With PIC, the address is actually $g + Offset.
10978 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10979 !Subtarget->is64Bit()) {
10980 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10981 DAG.getNode(X86ISD::GlobalBaseReg,
10982 SDLoc(), getPointerTy()),
10986 // For symbols that require a load from a stub to get the address, emit the
10988 if (isGlobalStubReference(OpFlag))
10989 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10990 MachinePointerInfo::getGOT(), false, false, false, 0);
10996 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10997 // Create the TargetBlockAddressAddress node.
10998 unsigned char OpFlags =
10999 Subtarget->ClassifyBlockAddressReference();
11000 CodeModel::Model M = DAG.getTarget().getCodeModel();
11001 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11002 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11004 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11007 if (Subtarget->isPICStyleRIPRel() &&
11008 (M == CodeModel::Small || M == CodeModel::Kernel))
11009 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11011 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11013 // With PIC, the address is actually $g + Offset.
11014 if (isGlobalRelativeToPICBase(OpFlags)) {
11015 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11016 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11024 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11025 int64_t Offset, SelectionDAG &DAG) const {
11026 // Create the TargetGlobalAddress node, folding in the constant
11027 // offset if it is legal.
11028 unsigned char OpFlags =
11029 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11030 CodeModel::Model M = DAG.getTarget().getCodeModel();
11032 if (OpFlags == X86II::MO_NO_FLAG &&
11033 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11034 // A direct static reference to a global.
11035 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11038 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11041 if (Subtarget->isPICStyleRIPRel() &&
11042 (M == CodeModel::Small || M == CodeModel::Kernel))
11043 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11045 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11047 // With PIC, the address is actually $g + Offset.
11048 if (isGlobalRelativeToPICBase(OpFlags)) {
11049 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11050 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11054 // For globals that require a load from a stub to get the address, emit the
11056 if (isGlobalStubReference(OpFlags))
11057 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11058 MachinePointerInfo::getGOT(), false, false, false, 0);
11060 // If there was a non-zero offset that we didn't fold, create an explicit
11061 // addition for it.
11063 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11064 DAG.getConstant(Offset, getPointerTy()));
11070 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11071 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11072 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11073 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11077 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11078 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11079 unsigned char OperandFlags, bool LocalDynamic = false) {
11080 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11081 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11083 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11084 GA->getValueType(0),
11088 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11092 SDValue Ops[] = { Chain, TGA, *InFlag };
11093 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11095 SDValue Ops[] = { Chain, TGA };
11096 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11099 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11100 MFI->setAdjustsStack(true);
11102 SDValue Flag = Chain.getValue(1);
11103 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11106 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11108 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11111 SDLoc dl(GA); // ? function entry point might be better
11112 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11113 DAG.getNode(X86ISD::GlobalBaseReg,
11114 SDLoc(), PtrVT), InFlag);
11115 InFlag = Chain.getValue(1);
11117 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11120 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11122 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11124 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11125 X86::RAX, X86II::MO_TLSGD);
11128 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11134 // Get the start address of the TLS block for this module.
11135 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11136 .getInfo<X86MachineFunctionInfo>();
11137 MFI->incNumLocalDynamicTLSAccesses();
11141 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11142 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11145 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11146 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11147 InFlag = Chain.getValue(1);
11148 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11149 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11152 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11156 unsigned char OperandFlags = X86II::MO_DTPOFF;
11157 unsigned WrapperKind = X86ISD::Wrapper;
11158 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11159 GA->getValueType(0),
11160 GA->getOffset(), OperandFlags);
11161 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11163 // Add x@dtpoff with the base.
11164 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11167 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11168 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11169 const EVT PtrVT, TLSModel::Model model,
11170 bool is64Bit, bool isPIC) {
11173 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11174 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11175 is64Bit ? 257 : 256));
11177 SDValue ThreadPointer =
11178 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11179 MachinePointerInfo(Ptr), false, false, false, 0);
11181 unsigned char OperandFlags = 0;
11182 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11184 unsigned WrapperKind = X86ISD::Wrapper;
11185 if (model == TLSModel::LocalExec) {
11186 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11187 } else if (model == TLSModel::InitialExec) {
11189 OperandFlags = X86II::MO_GOTTPOFF;
11190 WrapperKind = X86ISD::WrapperRIP;
11192 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11195 llvm_unreachable("Unexpected model");
11198 // emit "addl x@ntpoff,%eax" (local exec)
11199 // or "addl x@indntpoff,%eax" (initial exec)
11200 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11202 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11203 GA->getOffset(), OperandFlags);
11204 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11206 if (model == TLSModel::InitialExec) {
11207 if (isPIC && !is64Bit) {
11208 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11209 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11213 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11214 MachinePointerInfo::getGOT(), false, false, false, 0);
11217 // The address of the thread local variable is the add of the thread
11218 // pointer with the offset of the variable.
11219 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11223 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11225 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11226 const GlobalValue *GV = GA->getGlobal();
11228 if (Subtarget->isTargetELF()) {
11229 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11232 case TLSModel::GeneralDynamic:
11233 if (Subtarget->is64Bit())
11234 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11235 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11236 case TLSModel::LocalDynamic:
11237 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11238 Subtarget->is64Bit());
11239 case TLSModel::InitialExec:
11240 case TLSModel::LocalExec:
11241 return LowerToTLSExecModel(
11242 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11243 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11245 llvm_unreachable("Unknown TLS model.");
11248 if (Subtarget->isTargetDarwin()) {
11249 // Darwin only has one model of TLS. Lower to that.
11250 unsigned char OpFlag = 0;
11251 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11252 X86ISD::WrapperRIP : X86ISD::Wrapper;
11254 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11255 // global base reg.
11256 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11257 !Subtarget->is64Bit();
11259 OpFlag = X86II::MO_TLVP_PIC_BASE;
11261 OpFlag = X86II::MO_TLVP;
11263 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11264 GA->getValueType(0),
11265 GA->getOffset(), OpFlag);
11266 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11268 // With PIC32, the address is actually $g + Offset.
11270 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11271 DAG.getNode(X86ISD::GlobalBaseReg,
11272 SDLoc(), getPointerTy()),
11275 // Lowering the machine isd will make sure everything is in the right
11277 SDValue Chain = DAG.getEntryNode();
11278 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11279 SDValue Args[] = { Chain, Offset };
11280 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11282 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11283 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11284 MFI->setAdjustsStack(true);
11286 // And our return value (tls address) is in the standard call return value
11288 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11289 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11290 Chain.getValue(1));
11293 if (Subtarget->isTargetKnownWindowsMSVC() ||
11294 Subtarget->isTargetWindowsGNU()) {
11295 // Just use the implicit TLS architecture
11296 // Need to generate someting similar to:
11297 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11299 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11300 // mov rcx, qword [rdx+rcx*8]
11301 // mov eax, .tls$:tlsvar
11302 // [rax+rcx] contains the address
11303 // Windows 64bit: gs:0x58
11304 // Windows 32bit: fs:__tls_array
11307 SDValue Chain = DAG.getEntryNode();
11309 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11310 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11311 // use its literal value of 0x2C.
11312 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11313 ? Type::getInt8PtrTy(*DAG.getContext(),
11315 : Type::getInt32PtrTy(*DAG.getContext(),
11319 Subtarget->is64Bit()
11320 ? DAG.getIntPtrConstant(0x58)
11321 : (Subtarget->isTargetWindowsGNU()
11322 ? DAG.getIntPtrConstant(0x2C)
11323 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11325 SDValue ThreadPointer =
11326 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11327 MachinePointerInfo(Ptr), false, false, false, 0);
11329 // Load the _tls_index variable
11330 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11331 if (Subtarget->is64Bit())
11332 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11333 IDX, MachinePointerInfo(), MVT::i32,
11334 false, false, false, 0);
11336 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11337 false, false, false, 0);
11339 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11341 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11343 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11344 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11345 false, false, false, 0);
11347 // Get the offset of start of .tls section
11348 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11349 GA->getValueType(0),
11350 GA->getOffset(), X86II::MO_SECREL);
11351 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11353 // The address of the thread local variable is the add of the thread
11354 // pointer with the offset of the variable.
11355 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11358 llvm_unreachable("TLS not implemented for this target.");
11361 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11362 /// and take a 2 x i32 value to shift plus a shift amount.
11363 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11364 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11365 MVT VT = Op.getSimpleValueType();
11366 unsigned VTBits = VT.getSizeInBits();
11368 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11369 SDValue ShOpLo = Op.getOperand(0);
11370 SDValue ShOpHi = Op.getOperand(1);
11371 SDValue ShAmt = Op.getOperand(2);
11372 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11373 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11375 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11376 DAG.getConstant(VTBits - 1, MVT::i8));
11377 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11378 DAG.getConstant(VTBits - 1, MVT::i8))
11379 : DAG.getConstant(0, VT);
11381 SDValue Tmp2, Tmp3;
11382 if (Op.getOpcode() == ISD::SHL_PARTS) {
11383 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11384 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11386 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11387 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11390 // If the shift amount is larger or equal than the width of a part we can't
11391 // rely on the results of shld/shrd. Insert a test and select the appropriate
11392 // values for large shift amounts.
11393 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11394 DAG.getConstant(VTBits, MVT::i8));
11395 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11396 AndNode, DAG.getConstant(0, MVT::i8));
11399 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11400 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11401 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11403 if (Op.getOpcode() == ISD::SHL_PARTS) {
11404 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11405 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11407 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11408 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11411 SDValue Ops[2] = { Lo, Hi };
11412 return DAG.getMergeValues(Ops, dl);
11415 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11416 SelectionDAG &DAG) const {
11417 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11419 if (SrcVT.isVector())
11422 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11423 "Unknown SINT_TO_FP to lower!");
11425 // These are really Legal; return the operand so the caller accepts it as
11427 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11429 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11430 Subtarget->is64Bit()) {
11435 unsigned Size = SrcVT.getSizeInBits()/8;
11436 MachineFunction &MF = DAG.getMachineFunction();
11437 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11438 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11439 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11441 MachinePointerInfo::getFixedStack(SSFI),
11443 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11446 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11448 SelectionDAG &DAG) const {
11452 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11454 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11456 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11458 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11460 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11461 MachineMemOperand *MMO;
11463 int SSFI = FI->getIndex();
11465 DAG.getMachineFunction()
11466 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11467 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11469 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11470 StackSlot = StackSlot.getOperand(1);
11472 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11473 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11475 Tys, Ops, SrcVT, MMO);
11478 Chain = Result.getValue(1);
11479 SDValue InFlag = Result.getValue(2);
11481 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11482 // shouldn't be necessary except that RFP cannot be live across
11483 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11484 MachineFunction &MF = DAG.getMachineFunction();
11485 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11486 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11487 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11488 Tys = DAG.getVTList(MVT::Other);
11490 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11492 MachineMemOperand *MMO =
11493 DAG.getMachineFunction()
11494 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11495 MachineMemOperand::MOStore, SSFISize, SSFISize);
11497 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11498 Ops, Op.getValueType(), MMO);
11499 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11500 MachinePointerInfo::getFixedStack(SSFI),
11501 false, false, false, 0);
11507 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11508 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11509 SelectionDAG &DAG) const {
11510 // This algorithm is not obvious. Here it is what we're trying to output:
11513 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11514 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11516 haddpd %xmm0, %xmm0
11518 pshufd $0x4e, %xmm0, %xmm1
11524 LLVMContext *Context = DAG.getContext();
11526 // Build some magic constants.
11527 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11528 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11529 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11531 SmallVector<Constant*,2> CV1;
11533 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11534 APInt(64, 0x4330000000000000ULL))));
11536 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11537 APInt(64, 0x4530000000000000ULL))));
11538 Constant *C1 = ConstantVector::get(CV1);
11539 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11541 // Load the 64-bit value into an XMM register.
11542 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11544 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11545 MachinePointerInfo::getConstantPool(),
11546 false, false, false, 16);
11547 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11548 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11551 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11552 MachinePointerInfo::getConstantPool(),
11553 false, false, false, 16);
11554 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11555 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11558 if (Subtarget->hasSSE3()) {
11559 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11560 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11562 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11563 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11565 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11566 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11570 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11571 DAG.getIntPtrConstant(0));
11574 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11575 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11576 SelectionDAG &DAG) const {
11578 // FP constant to bias correct the final result.
11579 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11582 // Load the 32-bit value into an XMM register.
11583 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11586 // Zero out the upper parts of the register.
11587 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11589 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11590 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11591 DAG.getIntPtrConstant(0));
11593 // Or the load with the bias.
11594 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11595 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11596 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11597 MVT::v2f64, Load)),
11598 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11599 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11600 MVT::v2f64, Bias)));
11601 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11602 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11603 DAG.getIntPtrConstant(0));
11605 // Subtract the bias.
11606 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11608 // Handle final rounding.
11609 EVT DestVT = Op.getValueType();
11611 if (DestVT.bitsLT(MVT::f64))
11612 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11613 DAG.getIntPtrConstant(0));
11614 if (DestVT.bitsGT(MVT::f64))
11615 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11617 // Handle final rounding.
11621 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11622 SelectionDAG &DAG) const {
11623 SDValue N0 = Op.getOperand(0);
11624 MVT SVT = N0.getSimpleValueType();
11627 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11628 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11629 "Custom UINT_TO_FP is not supported!");
11631 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11632 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11633 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11636 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11637 SelectionDAG &DAG) const {
11638 SDValue N0 = Op.getOperand(0);
11641 if (Op.getValueType().isVector())
11642 return lowerUINT_TO_FP_vec(Op, DAG);
11644 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11645 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11646 // the optimization here.
11647 if (DAG.SignBitIsZero(N0))
11648 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11650 MVT SrcVT = N0.getSimpleValueType();
11651 MVT DstVT = Op.getSimpleValueType();
11652 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11653 return LowerUINT_TO_FP_i64(Op, DAG);
11654 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11655 return LowerUINT_TO_FP_i32(Op, DAG);
11656 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11659 // Make a 64-bit buffer, and use it to build an FILD.
11660 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11661 if (SrcVT == MVT::i32) {
11662 SDValue WordOff = DAG.getConstant(4, getPointerTy());
11663 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11664 getPointerTy(), StackSlot, WordOff);
11665 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11666 StackSlot, MachinePointerInfo(),
11668 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11669 OffsetSlot, MachinePointerInfo(),
11671 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11675 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11676 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11677 StackSlot, MachinePointerInfo(),
11679 // For i64 source, we need to add the appropriate power of 2 if the input
11680 // was negative. This is the same as the optimization in
11681 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11682 // we must be careful to do the computation in x87 extended precision, not
11683 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11684 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11685 MachineMemOperand *MMO =
11686 DAG.getMachineFunction()
11687 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11688 MachineMemOperand::MOLoad, 8, 8);
11690 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11691 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11692 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11695 APInt FF(32, 0x5F800000ULL);
11697 // Check whether the sign bit is set.
11698 SDValue SignSet = DAG.getSetCC(dl,
11699 getSetCCResultType(*DAG.getContext(), MVT::i64),
11700 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11703 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11704 SDValue FudgePtr = DAG.getConstantPool(
11705 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11708 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11709 SDValue Zero = DAG.getIntPtrConstant(0);
11710 SDValue Four = DAG.getIntPtrConstant(4);
11711 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11713 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11715 // Load the value out, extending it from f32 to f80.
11716 // FIXME: Avoid the extend by constructing the right constant pool?
11717 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11718 FudgePtr, MachinePointerInfo::getConstantPool(),
11719 MVT::f32, false, false, false, 4);
11720 // Extend everything to 80 bits to force it to be done on x87.
11721 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11722 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11725 std::pair<SDValue,SDValue>
11726 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11727 bool IsSigned, bool IsReplace) const {
11730 EVT DstTy = Op.getValueType();
11732 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11733 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11737 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11738 DstTy.getSimpleVT() >= MVT::i16 &&
11739 "Unknown FP_TO_INT to lower!");
11741 // These are really Legal.
11742 if (DstTy == MVT::i32 &&
11743 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11744 return std::make_pair(SDValue(), SDValue());
11745 if (Subtarget->is64Bit() &&
11746 DstTy == MVT::i64 &&
11747 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11748 return std::make_pair(SDValue(), SDValue());
11750 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11751 // stack slot, or into the FTOL runtime function.
11752 MachineFunction &MF = DAG.getMachineFunction();
11753 unsigned MemSize = DstTy.getSizeInBits()/8;
11754 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11755 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11758 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11759 Opc = X86ISD::WIN_FTOL;
11761 switch (DstTy.getSimpleVT().SimpleTy) {
11762 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11763 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11764 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11765 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11768 SDValue Chain = DAG.getEntryNode();
11769 SDValue Value = Op.getOperand(0);
11770 EVT TheVT = Op.getOperand(0).getValueType();
11771 // FIXME This causes a redundant load/store if the SSE-class value is already
11772 // in memory, such as if it is on the callstack.
11773 if (isScalarFPTypeInSSEReg(TheVT)) {
11774 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11775 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11776 MachinePointerInfo::getFixedStack(SSFI),
11778 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11780 Chain, StackSlot, DAG.getValueType(TheVT)
11783 MachineMemOperand *MMO =
11784 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11785 MachineMemOperand::MOLoad, MemSize, MemSize);
11786 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11787 Chain = Value.getValue(1);
11788 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11789 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11792 MachineMemOperand *MMO =
11793 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11794 MachineMemOperand::MOStore, MemSize, MemSize);
11796 if (Opc != X86ISD::WIN_FTOL) {
11797 // Build the FP_TO_INT*_IN_MEM
11798 SDValue Ops[] = { Chain, Value, StackSlot };
11799 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11801 return std::make_pair(FIST, StackSlot);
11803 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11804 DAG.getVTList(MVT::Other, MVT::Glue),
11806 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11807 MVT::i32, ftol.getValue(1));
11808 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11809 MVT::i32, eax.getValue(2));
11810 SDValue Ops[] = { eax, edx };
11811 SDValue pair = IsReplace
11812 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11813 : DAG.getMergeValues(Ops, DL);
11814 return std::make_pair(pair, SDValue());
11818 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11819 const X86Subtarget *Subtarget) {
11820 MVT VT = Op->getSimpleValueType(0);
11821 SDValue In = Op->getOperand(0);
11822 MVT InVT = In.getSimpleValueType();
11825 // Optimize vectors in AVX mode:
11828 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11829 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11830 // Concat upper and lower parts.
11833 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11834 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11835 // Concat upper and lower parts.
11838 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11839 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11840 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11843 if (Subtarget->hasInt256())
11844 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11846 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11847 SDValue Undef = DAG.getUNDEF(InVT);
11848 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11849 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11850 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11852 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11853 VT.getVectorNumElements()/2);
11855 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11856 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11858 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11861 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11862 SelectionDAG &DAG) {
11863 MVT VT = Op->getSimpleValueType(0);
11864 SDValue In = Op->getOperand(0);
11865 MVT InVT = In.getSimpleValueType();
11867 unsigned int NumElts = VT.getVectorNumElements();
11868 if (NumElts != 8 && NumElts != 16)
11871 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11872 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11874 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11875 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11876 // Now we have only mask extension
11877 assert(InVT.getVectorElementType() == MVT::i1);
11878 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11879 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11880 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11881 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11882 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11883 MachinePointerInfo::getConstantPool(),
11884 false, false, false, Alignment);
11886 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11887 if (VT.is512BitVector())
11889 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11892 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11893 SelectionDAG &DAG) {
11894 if (Subtarget->hasFp256()) {
11895 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11903 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11904 SelectionDAG &DAG) {
11906 MVT VT = Op.getSimpleValueType();
11907 SDValue In = Op.getOperand(0);
11908 MVT SVT = In.getSimpleValueType();
11910 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11911 return LowerZERO_EXTEND_AVX512(Op, DAG);
11913 if (Subtarget->hasFp256()) {
11914 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11919 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11920 VT.getVectorNumElements() != SVT.getVectorNumElements());
11924 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11926 MVT VT = Op.getSimpleValueType();
11927 SDValue In = Op.getOperand(0);
11928 MVT InVT = In.getSimpleValueType();
11930 if (VT == MVT::i1) {
11931 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11932 "Invalid scalar TRUNCATE operation");
11933 if (InVT.getSizeInBits() >= 32)
11935 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11936 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11938 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11939 "Invalid TRUNCATE operation");
11941 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11942 if (VT.getVectorElementType().getSizeInBits() >=8)
11943 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11945 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11946 unsigned NumElts = InVT.getVectorNumElements();
11947 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11948 if (InVT.getSizeInBits() < 512) {
11949 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11950 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11954 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11955 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11956 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11957 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11958 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11959 MachinePointerInfo::getConstantPool(),
11960 false, false, false, Alignment);
11961 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11962 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11963 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11966 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11967 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11968 if (Subtarget->hasInt256()) {
11969 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11970 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11971 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11973 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11974 DAG.getIntPtrConstant(0));
11977 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11978 DAG.getIntPtrConstant(0));
11979 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11980 DAG.getIntPtrConstant(2));
11981 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11982 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11983 static const int ShufMask[] = {0, 2, 4, 6};
11984 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11987 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11988 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11989 if (Subtarget->hasInt256()) {
11990 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11992 SmallVector<SDValue,32> pshufbMask;
11993 for (unsigned i = 0; i < 2; ++i) {
11994 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11995 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11996 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11997 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11998 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11999 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
12000 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
12001 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
12002 for (unsigned j = 0; j < 8; ++j)
12003 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
12005 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12006 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12007 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12009 static const int ShufMask[] = {0, 2, -1, -1};
12010 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12012 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12013 DAG.getIntPtrConstant(0));
12014 return DAG.getNode(ISD::BITCAST, DL, VT, In);
12017 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12018 DAG.getIntPtrConstant(0));
12020 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12021 DAG.getIntPtrConstant(4));
12023 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12024 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12026 // The PSHUFB mask:
12027 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12028 -1, -1, -1, -1, -1, -1, -1, -1};
12030 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12031 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12032 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12034 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12035 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12037 // The MOVLHPS Mask:
12038 static const int ShufMask2[] = {0, 1, 4, 5};
12039 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12040 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12043 // Handle truncation of V256 to V128 using shuffles.
12044 if (!VT.is128BitVector() || !InVT.is256BitVector())
12047 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12049 unsigned NumElems = VT.getVectorNumElements();
12050 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12052 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12053 // Prepare truncation shuffle mask
12054 for (unsigned i = 0; i != NumElems; ++i)
12055 MaskVec[i] = i * 2;
12056 SDValue V = DAG.getVectorShuffle(NVT, DL,
12057 DAG.getNode(ISD::BITCAST, DL, NVT, In),
12058 DAG.getUNDEF(NVT), &MaskVec[0]);
12059 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12060 DAG.getIntPtrConstant(0));
12063 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12064 SelectionDAG &DAG) const {
12065 assert(!Op.getSimpleValueType().isVector());
12067 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12068 /*IsSigned=*/ true, /*IsReplace=*/ false);
12069 SDValue FIST = Vals.first, StackSlot = Vals.second;
12070 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12071 if (!FIST.getNode()) return Op;
12073 if (StackSlot.getNode())
12074 // Load the result.
12075 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12076 FIST, StackSlot, MachinePointerInfo(),
12077 false, false, false, 0);
12079 // The node is the result.
12083 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12084 SelectionDAG &DAG) const {
12085 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12086 /*IsSigned=*/ false, /*IsReplace=*/ false);
12087 SDValue FIST = Vals.first, StackSlot = Vals.second;
12088 assert(FIST.getNode() && "Unexpected failure");
12090 if (StackSlot.getNode())
12091 // Load the result.
12092 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12093 FIST, StackSlot, MachinePointerInfo(),
12094 false, false, false, 0);
12096 // The node is the result.
12100 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12102 MVT VT = Op.getSimpleValueType();
12103 SDValue In = Op.getOperand(0);
12104 MVT SVT = In.getSimpleValueType();
12106 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12108 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12109 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12110 In, DAG.getUNDEF(SVT)));
12113 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
12114 LLVMContext *Context = DAG.getContext();
12116 MVT VT = Op.getSimpleValueType();
12118 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12119 if (VT.isVector()) {
12120 EltVT = VT.getVectorElementType();
12121 NumElts = VT.getVectorNumElements();
12124 if (EltVT == MVT::f64)
12125 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12126 APInt(64, ~(1ULL << 63))));
12128 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12129 APInt(32, ~(1U << 31))));
12130 C = ConstantVector::getSplat(NumElts, C);
12131 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12132 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12133 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12134 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12135 MachinePointerInfo::getConstantPool(),
12136 false, false, false, Alignment);
12137 if (VT.isVector()) {
12138 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12139 return DAG.getNode(ISD::BITCAST, dl, VT,
12140 DAG.getNode(ISD::AND, dl, ANDVT,
12141 DAG.getNode(ISD::BITCAST, dl, ANDVT,
12143 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
12145 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
12148 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
12149 LLVMContext *Context = DAG.getContext();
12151 MVT VT = Op.getSimpleValueType();
12153 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12154 if (VT.isVector()) {
12155 EltVT = VT.getVectorElementType();
12156 NumElts = VT.getVectorNumElements();
12159 if (EltVT == MVT::f64)
12160 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12161 APInt(64, 1ULL << 63)));
12163 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12164 APInt(32, 1U << 31)));
12165 C = ConstantVector::getSplat(NumElts, C);
12166 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12167 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12168 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12169 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12170 MachinePointerInfo::getConstantPool(),
12171 false, false, false, Alignment);
12172 if (VT.isVector()) {
12173 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
12174 return DAG.getNode(ISD::BITCAST, dl, VT,
12175 DAG.getNode(ISD::XOR, dl, XORVT,
12176 DAG.getNode(ISD::BITCAST, dl, XORVT,
12178 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
12181 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
12184 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12185 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12186 LLVMContext *Context = DAG.getContext();
12187 SDValue Op0 = Op.getOperand(0);
12188 SDValue Op1 = Op.getOperand(1);
12190 MVT VT = Op.getSimpleValueType();
12191 MVT SrcVT = Op1.getSimpleValueType();
12193 // If second operand is smaller, extend it first.
12194 if (SrcVT.bitsLT(VT)) {
12195 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12198 // And if it is bigger, shrink it first.
12199 if (SrcVT.bitsGT(VT)) {
12200 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12204 // At this point the operands and the result should have the same
12205 // type, and that won't be f80 since that is not custom lowered.
12207 // First get the sign bit of second operand.
12208 SmallVector<Constant*,4> CV;
12209 if (SrcVT == MVT::f64) {
12210 const fltSemantics &Sem = APFloat::IEEEdouble;
12211 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
12212 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12214 const fltSemantics &Sem = APFloat::IEEEsingle;
12215 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
12216 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12217 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12218 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12220 Constant *C = ConstantVector::get(CV);
12221 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12222 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12223 MachinePointerInfo::getConstantPool(),
12224 false, false, false, 16);
12225 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12227 // Shift sign bit right or left if the two operands have different types.
12228 if (SrcVT.bitsGT(VT)) {
12229 // Op0 is MVT::f32, Op1 is MVT::f64.
12230 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
12231 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
12232 DAG.getConstant(32, MVT::i32));
12233 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
12234 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
12235 DAG.getIntPtrConstant(0));
12238 // Clear first operand sign bit.
12240 if (VT == MVT::f64) {
12241 const fltSemantics &Sem = APFloat::IEEEdouble;
12242 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12243 APInt(64, ~(1ULL << 63)))));
12244 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12246 const fltSemantics &Sem = APFloat::IEEEsingle;
12247 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12248 APInt(32, ~(1U << 31)))));
12249 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12250 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12251 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12253 C = ConstantVector::get(CV);
12254 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12255 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12256 MachinePointerInfo::getConstantPool(),
12257 false, false, false, 16);
12258 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
12260 // Or the value with the sign bit.
12261 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12264 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12265 SDValue N0 = Op.getOperand(0);
12267 MVT VT = Op.getSimpleValueType();
12269 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12270 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12271 DAG.getConstant(1, VT));
12272 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12275 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
12277 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12278 SelectionDAG &DAG) {
12279 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12281 if (!Subtarget->hasSSE41())
12284 if (!Op->hasOneUse())
12287 SDNode *N = Op.getNode();
12290 SmallVector<SDValue, 8> Opnds;
12291 DenseMap<SDValue, unsigned> VecInMap;
12292 SmallVector<SDValue, 8> VecIns;
12293 EVT VT = MVT::Other;
12295 // Recognize a special case where a vector is casted into wide integer to
12297 Opnds.push_back(N->getOperand(0));
12298 Opnds.push_back(N->getOperand(1));
12300 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12301 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12302 // BFS traverse all OR'd operands.
12303 if (I->getOpcode() == ISD::OR) {
12304 Opnds.push_back(I->getOperand(0));
12305 Opnds.push_back(I->getOperand(1));
12306 // Re-evaluate the number of nodes to be traversed.
12307 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12311 // Quit if a non-EXTRACT_VECTOR_ELT
12312 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12315 // Quit if without a constant index.
12316 SDValue Idx = I->getOperand(1);
12317 if (!isa<ConstantSDNode>(Idx))
12320 SDValue ExtractedFromVec = I->getOperand(0);
12321 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12322 if (M == VecInMap.end()) {
12323 VT = ExtractedFromVec.getValueType();
12324 // Quit if not 128/256-bit vector.
12325 if (!VT.is128BitVector() && !VT.is256BitVector())
12327 // Quit if not the same type.
12328 if (VecInMap.begin() != VecInMap.end() &&
12329 VT != VecInMap.begin()->first.getValueType())
12331 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12332 VecIns.push_back(ExtractedFromVec);
12334 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12337 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12338 "Not extracted from 128-/256-bit vector.");
12340 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12342 for (DenseMap<SDValue, unsigned>::const_iterator
12343 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12344 // Quit if not all elements are used.
12345 if (I->second != FullMask)
12349 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12351 // Cast all vectors into TestVT for PTEST.
12352 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12353 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12355 // If more than one full vectors are evaluated, OR them first before PTEST.
12356 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12357 // Each iteration will OR 2 nodes and append the result until there is only
12358 // 1 node left, i.e. the final OR'd value of all vectors.
12359 SDValue LHS = VecIns[Slot];
12360 SDValue RHS = VecIns[Slot + 1];
12361 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12364 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12365 VecIns.back(), VecIns.back());
12368 /// \brief return true if \c Op has a use that doesn't just read flags.
12369 static bool hasNonFlagsUse(SDValue Op) {
12370 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12372 SDNode *User = *UI;
12373 unsigned UOpNo = UI.getOperandNo();
12374 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12375 // Look pass truncate.
12376 UOpNo = User->use_begin().getOperandNo();
12377 User = *User->use_begin();
12380 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12381 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12387 /// Emit nodes that will be selected as "test Op0,Op0", or something
12389 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12390 SelectionDAG &DAG) const {
12391 if (Op.getValueType() == MVT::i1)
12392 // KORTEST instruction should be selected
12393 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12394 DAG.getConstant(0, Op.getValueType()));
12396 // CF and OF aren't always set the way we want. Determine which
12397 // of these we need.
12398 bool NeedCF = false;
12399 bool NeedOF = false;
12402 case X86::COND_A: case X86::COND_AE:
12403 case X86::COND_B: case X86::COND_BE:
12406 case X86::COND_G: case X86::COND_GE:
12407 case X86::COND_L: case X86::COND_LE:
12408 case X86::COND_O: case X86::COND_NO: {
12409 // Check if we really need to set the
12410 // Overflow flag. If NoSignedWrap is present
12411 // that is not actually needed.
12412 switch (Op->getOpcode()) {
12417 const BinaryWithFlagsSDNode *BinNode =
12418 cast<BinaryWithFlagsSDNode>(Op.getNode());
12419 if (BinNode->hasNoSignedWrap())
12429 // See if we can use the EFLAGS value from the operand instead of
12430 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12431 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12432 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12433 // Emit a CMP with 0, which is the TEST pattern.
12434 //if (Op.getValueType() == MVT::i1)
12435 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12436 // DAG.getConstant(0, MVT::i1));
12437 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12438 DAG.getConstant(0, Op.getValueType()));
12440 unsigned Opcode = 0;
12441 unsigned NumOperands = 0;
12443 // Truncate operations may prevent the merge of the SETCC instruction
12444 // and the arithmetic instruction before it. Attempt to truncate the operands
12445 // of the arithmetic instruction and use a reduced bit-width instruction.
12446 bool NeedTruncation = false;
12447 SDValue ArithOp = Op;
12448 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12449 SDValue Arith = Op->getOperand(0);
12450 // Both the trunc and the arithmetic op need to have one user each.
12451 if (Arith->hasOneUse())
12452 switch (Arith.getOpcode()) {
12459 NeedTruncation = true;
12465 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12466 // which may be the result of a CAST. We use the variable 'Op', which is the
12467 // non-casted variable when we check for possible users.
12468 switch (ArithOp.getOpcode()) {
12470 // Due to an isel shortcoming, be conservative if this add is likely to be
12471 // selected as part of a load-modify-store instruction. When the root node
12472 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12473 // uses of other nodes in the match, such as the ADD in this case. This
12474 // leads to the ADD being left around and reselected, with the result being
12475 // two adds in the output. Alas, even if none our users are stores, that
12476 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12477 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12478 // climbing the DAG back to the root, and it doesn't seem to be worth the
12480 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12481 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12482 if (UI->getOpcode() != ISD::CopyToReg &&
12483 UI->getOpcode() != ISD::SETCC &&
12484 UI->getOpcode() != ISD::STORE)
12487 if (ConstantSDNode *C =
12488 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12489 // An add of one will be selected as an INC.
12490 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12491 Opcode = X86ISD::INC;
12496 // An add of negative one (subtract of one) will be selected as a DEC.
12497 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12498 Opcode = X86ISD::DEC;
12504 // Otherwise use a regular EFLAGS-setting add.
12505 Opcode = X86ISD::ADD;
12510 // If we have a constant logical shift that's only used in a comparison
12511 // against zero turn it into an equivalent AND. This allows turning it into
12512 // a TEST instruction later.
12513 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12514 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12515 EVT VT = Op.getValueType();
12516 unsigned BitWidth = VT.getSizeInBits();
12517 unsigned ShAmt = Op->getConstantOperandVal(1);
12518 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12520 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12521 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12522 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12523 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12525 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12526 DAG.getConstant(Mask, VT));
12527 DAG.ReplaceAllUsesWith(Op, New);
12533 // If the primary and result isn't used, don't bother using X86ISD::AND,
12534 // because a TEST instruction will be better.
12535 if (!hasNonFlagsUse(Op))
12541 // Due to the ISEL shortcoming noted above, be conservative if this op is
12542 // likely to be selected as part of a load-modify-store instruction.
12543 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12544 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12545 if (UI->getOpcode() == ISD::STORE)
12548 // Otherwise use a regular EFLAGS-setting instruction.
12549 switch (ArithOp.getOpcode()) {
12550 default: llvm_unreachable("unexpected operator!");
12551 case ISD::SUB: Opcode = X86ISD::SUB; break;
12552 case ISD::XOR: Opcode = X86ISD::XOR; break;
12553 case ISD::AND: Opcode = X86ISD::AND; break;
12555 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12556 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12557 if (EFLAGS.getNode())
12560 Opcode = X86ISD::OR;
12574 return SDValue(Op.getNode(), 1);
12580 // If we found that truncation is beneficial, perform the truncation and
12582 if (NeedTruncation) {
12583 EVT VT = Op.getValueType();
12584 SDValue WideVal = Op->getOperand(0);
12585 EVT WideVT = WideVal.getValueType();
12586 unsigned ConvertedOp = 0;
12587 // Use a target machine opcode to prevent further DAGCombine
12588 // optimizations that may separate the arithmetic operations
12589 // from the setcc node.
12590 switch (WideVal.getOpcode()) {
12592 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12593 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12594 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12595 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12596 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12600 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12601 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12602 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12603 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12604 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12610 // Emit a CMP with 0, which is the TEST pattern.
12611 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12612 DAG.getConstant(0, Op.getValueType()));
12614 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12615 SmallVector<SDValue, 4> Ops;
12616 for (unsigned i = 0; i != NumOperands; ++i)
12617 Ops.push_back(Op.getOperand(i));
12619 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12620 DAG.ReplaceAllUsesWith(Op, New);
12621 return SDValue(New.getNode(), 1);
12624 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12626 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12627 SDLoc dl, SelectionDAG &DAG) const {
12628 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12629 if (C->getAPIntValue() == 0)
12630 return EmitTest(Op0, X86CC, dl, DAG);
12632 if (Op0.getValueType() == MVT::i1)
12633 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12636 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12637 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12638 // Do the comparison at i32 if it's smaller, besides the Atom case.
12639 // This avoids subregister aliasing issues. Keep the smaller reference
12640 // if we're optimizing for size, however, as that'll allow better folding
12641 // of memory operations.
12642 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12643 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12644 AttributeSet::FunctionIndex, Attribute::MinSize) &&
12645 !Subtarget->isAtom()) {
12646 unsigned ExtendOp =
12647 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12648 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12649 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12651 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12652 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12653 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12655 return SDValue(Sub.getNode(), 1);
12657 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12660 /// Convert a comparison if required by the subtarget.
12661 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12662 SelectionDAG &DAG) const {
12663 // If the subtarget does not support the FUCOMI instruction, floating-point
12664 // comparisons have to be converted.
12665 if (Subtarget->hasCMov() ||
12666 Cmp.getOpcode() != X86ISD::CMP ||
12667 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12668 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12671 // The instruction selector will select an FUCOM instruction instead of
12672 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12673 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12674 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12676 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12677 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12678 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12679 DAG.getConstant(8, MVT::i8));
12680 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12681 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12684 static bool isAllOnes(SDValue V) {
12685 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12686 return C && C->isAllOnesValue();
12689 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12690 /// if it's possible.
12691 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12692 SDLoc dl, SelectionDAG &DAG) const {
12693 SDValue Op0 = And.getOperand(0);
12694 SDValue Op1 = And.getOperand(1);
12695 if (Op0.getOpcode() == ISD::TRUNCATE)
12696 Op0 = Op0.getOperand(0);
12697 if (Op1.getOpcode() == ISD::TRUNCATE)
12698 Op1 = Op1.getOperand(0);
12701 if (Op1.getOpcode() == ISD::SHL)
12702 std::swap(Op0, Op1);
12703 if (Op0.getOpcode() == ISD::SHL) {
12704 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12705 if (And00C->getZExtValue() == 1) {
12706 // If we looked past a truncate, check that it's only truncating away
12708 unsigned BitWidth = Op0.getValueSizeInBits();
12709 unsigned AndBitWidth = And.getValueSizeInBits();
12710 if (BitWidth > AndBitWidth) {
12712 DAG.computeKnownBits(Op0, Zeros, Ones);
12713 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12717 RHS = Op0.getOperand(1);
12719 } else if (Op1.getOpcode() == ISD::Constant) {
12720 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12721 uint64_t AndRHSVal = AndRHS->getZExtValue();
12722 SDValue AndLHS = Op0;
12724 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12725 LHS = AndLHS.getOperand(0);
12726 RHS = AndLHS.getOperand(1);
12729 // Use BT if the immediate can't be encoded in a TEST instruction.
12730 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12732 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12736 if (LHS.getNode()) {
12737 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12738 // instruction. Since the shift amount is in-range-or-undefined, we know
12739 // that doing a bittest on the i32 value is ok. We extend to i32 because
12740 // the encoding for the i16 version is larger than the i32 version.
12741 // Also promote i16 to i32 for performance / code size reason.
12742 if (LHS.getValueType() == MVT::i8 ||
12743 LHS.getValueType() == MVT::i16)
12744 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12746 // If the operand types disagree, extend the shift amount to match. Since
12747 // BT ignores high bits (like shifts) we can use anyextend.
12748 if (LHS.getValueType() != RHS.getValueType())
12749 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12751 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12752 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12753 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12754 DAG.getConstant(Cond, MVT::i8), BT);
12760 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12762 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12767 // SSE Condition code mapping:
12776 switch (SetCCOpcode) {
12777 default: llvm_unreachable("Unexpected SETCC condition");
12779 case ISD::SETEQ: SSECC = 0; break;
12781 case ISD::SETGT: Swap = true; // Fallthrough
12783 case ISD::SETOLT: SSECC = 1; break;
12785 case ISD::SETGE: Swap = true; // Fallthrough
12787 case ISD::SETOLE: SSECC = 2; break;
12788 case ISD::SETUO: SSECC = 3; break;
12790 case ISD::SETNE: SSECC = 4; break;
12791 case ISD::SETULE: Swap = true; // Fallthrough
12792 case ISD::SETUGE: SSECC = 5; break;
12793 case ISD::SETULT: Swap = true; // Fallthrough
12794 case ISD::SETUGT: SSECC = 6; break;
12795 case ISD::SETO: SSECC = 7; break;
12797 case ISD::SETONE: SSECC = 8; break;
12800 std::swap(Op0, Op1);
12805 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12806 // ones, and then concatenate the result back.
12807 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12808 MVT VT = Op.getSimpleValueType();
12810 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12811 "Unsupported value type for operation");
12813 unsigned NumElems = VT.getVectorNumElements();
12815 SDValue CC = Op.getOperand(2);
12817 // Extract the LHS vectors
12818 SDValue LHS = Op.getOperand(0);
12819 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12820 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12822 // Extract the RHS vectors
12823 SDValue RHS = Op.getOperand(1);
12824 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12825 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12827 // Issue the operation on the smaller types and concatenate the result back
12828 MVT EltVT = VT.getVectorElementType();
12829 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12830 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12831 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12832 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12835 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12836 const X86Subtarget *Subtarget) {
12837 SDValue Op0 = Op.getOperand(0);
12838 SDValue Op1 = Op.getOperand(1);
12839 SDValue CC = Op.getOperand(2);
12840 MVT VT = Op.getSimpleValueType();
12843 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12844 Op.getValueType().getScalarType() == MVT::i1 &&
12845 "Cannot set masked compare for this operation");
12847 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12849 bool Unsigned = false;
12852 switch (SetCCOpcode) {
12853 default: llvm_unreachable("Unexpected SETCC condition");
12854 case ISD::SETNE: SSECC = 4; break;
12855 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12856 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12857 case ISD::SETLT: Swap = true; //fall-through
12858 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12859 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12860 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12861 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12862 case ISD::SETULE: Unsigned = true; //fall-through
12863 case ISD::SETLE: SSECC = 2; break;
12867 std::swap(Op0, Op1);
12869 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12870 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12871 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12872 DAG.getConstant(SSECC, MVT::i8));
12875 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12876 /// operand \p Op1. If non-trivial (for example because it's not constant)
12877 /// return an empty value.
12878 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12880 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12884 MVT VT = Op1.getSimpleValueType();
12885 MVT EVT = VT.getVectorElementType();
12886 unsigned n = VT.getVectorNumElements();
12887 SmallVector<SDValue, 8> ULTOp1;
12889 for (unsigned i = 0; i < n; ++i) {
12890 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12891 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12894 // Avoid underflow.
12895 APInt Val = Elt->getAPIntValue();
12899 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12902 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12905 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12906 SelectionDAG &DAG) {
12907 SDValue Op0 = Op.getOperand(0);
12908 SDValue Op1 = Op.getOperand(1);
12909 SDValue CC = Op.getOperand(2);
12910 MVT VT = Op.getSimpleValueType();
12911 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12912 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12917 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12918 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12921 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12922 unsigned Opc = X86ISD::CMPP;
12923 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12924 assert(VT.getVectorNumElements() <= 16);
12925 Opc = X86ISD::CMPM;
12927 // In the two special cases we can't handle, emit two comparisons.
12930 unsigned CombineOpc;
12931 if (SetCCOpcode == ISD::SETUEQ) {
12932 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12934 assert(SetCCOpcode == ISD::SETONE);
12935 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12938 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12939 DAG.getConstant(CC0, MVT::i8));
12940 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12941 DAG.getConstant(CC1, MVT::i8));
12942 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12944 // Handle all other FP comparisons here.
12945 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12946 DAG.getConstant(SSECC, MVT::i8));
12949 // Break 256-bit integer vector compare into smaller ones.
12950 if (VT.is256BitVector() && !Subtarget->hasInt256())
12951 return Lower256IntVSETCC(Op, DAG);
12953 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12954 EVT OpVT = Op1.getValueType();
12955 if (Subtarget->hasAVX512()) {
12956 if (Op1.getValueType().is512BitVector() ||
12957 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12958 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12960 // In AVX-512 architecture setcc returns mask with i1 elements,
12961 // But there is no compare instruction for i8 and i16 elements.
12962 // We are not talking about 512-bit operands in this case, these
12963 // types are illegal.
12965 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12966 OpVT.getVectorElementType().getSizeInBits() >= 8))
12967 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12968 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12971 // We are handling one of the integer comparisons here. Since SSE only has
12972 // GT and EQ comparisons for integer, swapping operands and multiple
12973 // operations may be required for some comparisons.
12975 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12976 bool Subus = false;
12978 switch (SetCCOpcode) {
12979 default: llvm_unreachable("Unexpected SETCC condition");
12980 case ISD::SETNE: Invert = true;
12981 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12982 case ISD::SETLT: Swap = true;
12983 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12984 case ISD::SETGE: Swap = true;
12985 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12986 Invert = true; break;
12987 case ISD::SETULT: Swap = true;
12988 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12989 FlipSigns = true; break;
12990 case ISD::SETUGE: Swap = true;
12991 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12992 FlipSigns = true; Invert = true; break;
12995 // Special case: Use min/max operations for SETULE/SETUGE
12996 MVT VET = VT.getVectorElementType();
12998 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12999 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13002 switch (SetCCOpcode) {
13004 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13005 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13008 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13011 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13012 if (!MinMax && hasSubus) {
13013 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13015 // t = psubus Op0, Op1
13016 // pcmpeq t, <0..0>
13017 switch (SetCCOpcode) {
13019 case ISD::SETULT: {
13020 // If the comparison is against a constant we can turn this into a
13021 // setule. With psubus, setule does not require a swap. This is
13022 // beneficial because the constant in the register is no longer
13023 // destructed as the destination so it can be hoisted out of a loop.
13024 // Only do this pre-AVX since vpcmp* is no longer destructive.
13025 if (Subtarget->hasAVX())
13027 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13028 if (ULEOp1.getNode()) {
13030 Subus = true; Invert = false; Swap = false;
13034 // Psubus is better than flip-sign because it requires no inversion.
13035 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13036 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13040 Opc = X86ISD::SUBUS;
13046 std::swap(Op0, Op1);
13048 // Check that the operation in question is available (most are plain SSE2,
13049 // but PCMPGTQ and PCMPEQQ have different requirements).
13050 if (VT == MVT::v2i64) {
13051 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13052 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13054 // First cast everything to the right type.
13055 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13056 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13058 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13059 // bits of the inputs before performing those operations. The lower
13060 // compare is always unsigned.
13063 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13065 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13066 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13067 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13068 Sign, Zero, Sign, Zero);
13070 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13071 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13073 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13074 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13075 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13077 // Create masks for only the low parts/high parts of the 64 bit integers.
13078 static const int MaskHi[] = { 1, 1, 3, 3 };
13079 static const int MaskLo[] = { 0, 0, 2, 2 };
13080 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13081 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13082 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13084 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13085 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13088 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13090 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13093 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13094 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13095 // pcmpeqd + pshufd + pand.
13096 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13098 // First cast everything to the right type.
13099 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13100 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13103 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13105 // Make sure the lower and upper halves are both all-ones.
13106 static const int Mask[] = { 1, 0, 3, 2 };
13107 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13108 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13111 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13113 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13117 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13118 // bits of the inputs before performing those operations.
13120 EVT EltVT = VT.getVectorElementType();
13121 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13122 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13123 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13126 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13128 // If the logical-not of the result is required, perform that now.
13130 Result = DAG.getNOT(dl, Result, VT);
13133 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13136 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13137 getZeroVector(VT, Subtarget, DAG, dl));
13142 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13144 MVT VT = Op.getSimpleValueType();
13146 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13148 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13149 && "SetCC type must be 8-bit or 1-bit integer");
13150 SDValue Op0 = Op.getOperand(0);
13151 SDValue Op1 = Op.getOperand(1);
13153 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13155 // Optimize to BT if possible.
13156 // Lower (X & (1 << N)) == 0 to BT(X, N).
13157 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13158 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13159 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13160 Op1.getOpcode() == ISD::Constant &&
13161 cast<ConstantSDNode>(Op1)->isNullValue() &&
13162 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13163 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13164 if (NewSetCC.getNode())
13168 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13170 if (Op1.getOpcode() == ISD::Constant &&
13171 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13172 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13173 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13175 // If the input is a setcc, then reuse the input setcc or use a new one with
13176 // the inverted condition.
13177 if (Op0.getOpcode() == X86ISD::SETCC) {
13178 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13179 bool Invert = (CC == ISD::SETNE) ^
13180 cast<ConstantSDNode>(Op1)->isNullValue();
13184 CCode = X86::GetOppositeBranchCondition(CCode);
13185 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13186 DAG.getConstant(CCode, MVT::i8),
13187 Op0.getOperand(1));
13189 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13193 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13194 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13195 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13197 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13198 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13201 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13202 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13203 if (X86CC == X86::COND_INVALID)
13206 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13207 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13208 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13209 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13211 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13215 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13216 static bool isX86LogicalCmp(SDValue Op) {
13217 unsigned Opc = Op.getNode()->getOpcode();
13218 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13219 Opc == X86ISD::SAHF)
13221 if (Op.getResNo() == 1 &&
13222 (Opc == X86ISD::ADD ||
13223 Opc == X86ISD::SUB ||
13224 Opc == X86ISD::ADC ||
13225 Opc == X86ISD::SBB ||
13226 Opc == X86ISD::SMUL ||
13227 Opc == X86ISD::UMUL ||
13228 Opc == X86ISD::INC ||
13229 Opc == X86ISD::DEC ||
13230 Opc == X86ISD::OR ||
13231 Opc == X86ISD::XOR ||
13232 Opc == X86ISD::AND))
13235 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13241 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13242 if (V.getOpcode() != ISD::TRUNCATE)
13245 SDValue VOp0 = V.getOperand(0);
13246 unsigned InBits = VOp0.getValueSizeInBits();
13247 unsigned Bits = V.getValueSizeInBits();
13248 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13251 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13252 bool addTest = true;
13253 SDValue Cond = Op.getOperand(0);
13254 SDValue Op1 = Op.getOperand(1);
13255 SDValue Op2 = Op.getOperand(2);
13257 EVT VT = Op1.getValueType();
13260 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13261 // are available. Otherwise fp cmovs get lowered into a less efficient branch
13262 // sequence later on.
13263 if (Cond.getOpcode() == ISD::SETCC &&
13264 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13265 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13266 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13267 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13268 int SSECC = translateX86FSETCC(
13269 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13272 if (Subtarget->hasAVX512()) {
13273 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13274 DAG.getConstant(SSECC, MVT::i8));
13275 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13277 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13278 DAG.getConstant(SSECC, MVT::i8));
13279 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13280 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13281 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13285 if (Cond.getOpcode() == ISD::SETCC) {
13286 SDValue NewCond = LowerSETCC(Cond, DAG);
13287 if (NewCond.getNode())
13291 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13292 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13293 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13294 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13295 if (Cond.getOpcode() == X86ISD::SETCC &&
13296 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13297 isZero(Cond.getOperand(1).getOperand(1))) {
13298 SDValue Cmp = Cond.getOperand(1);
13300 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13302 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13303 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13304 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13306 SDValue CmpOp0 = Cmp.getOperand(0);
13307 // Apply further optimizations for special cases
13308 // (select (x != 0), -1, 0) -> neg & sbb
13309 // (select (x == 0), 0, -1) -> neg & sbb
13310 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13311 if (YC->isNullValue() &&
13312 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13313 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13314 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13315 DAG.getConstant(0, CmpOp0.getValueType()),
13317 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13318 DAG.getConstant(X86::COND_B, MVT::i8),
13319 SDValue(Neg.getNode(), 1));
13323 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13324 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13325 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13327 SDValue Res = // Res = 0 or -1.
13328 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13329 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13331 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13332 Res = DAG.getNOT(DL, Res, Res.getValueType());
13334 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13335 if (!N2C || !N2C->isNullValue())
13336 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13341 // Look past (and (setcc_carry (cmp ...)), 1).
13342 if (Cond.getOpcode() == ISD::AND &&
13343 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13344 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13345 if (C && C->getAPIntValue() == 1)
13346 Cond = Cond.getOperand(0);
13349 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13350 // setting operand in place of the X86ISD::SETCC.
13351 unsigned CondOpcode = Cond.getOpcode();
13352 if (CondOpcode == X86ISD::SETCC ||
13353 CondOpcode == X86ISD::SETCC_CARRY) {
13354 CC = Cond.getOperand(0);
13356 SDValue Cmp = Cond.getOperand(1);
13357 unsigned Opc = Cmp.getOpcode();
13358 MVT VT = Op.getSimpleValueType();
13360 bool IllegalFPCMov = false;
13361 if (VT.isFloatingPoint() && !VT.isVector() &&
13362 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13363 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13365 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13366 Opc == X86ISD::BT) { // FIXME
13370 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13371 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13372 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13373 Cond.getOperand(0).getValueType() != MVT::i8)) {
13374 SDValue LHS = Cond.getOperand(0);
13375 SDValue RHS = Cond.getOperand(1);
13376 unsigned X86Opcode;
13379 switch (CondOpcode) {
13380 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13381 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13382 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13383 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13384 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13385 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13386 default: llvm_unreachable("unexpected overflowing operator");
13388 if (CondOpcode == ISD::UMULO)
13389 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13392 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13394 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13396 if (CondOpcode == ISD::UMULO)
13397 Cond = X86Op.getValue(2);
13399 Cond = X86Op.getValue(1);
13401 CC = DAG.getConstant(X86Cond, MVT::i8);
13406 // Look pass the truncate if the high bits are known zero.
13407 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13408 Cond = Cond.getOperand(0);
13410 // We know the result of AND is compared against zero. Try to match
13412 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13413 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13414 if (NewSetCC.getNode()) {
13415 CC = NewSetCC.getOperand(0);
13416 Cond = NewSetCC.getOperand(1);
13423 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13424 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13427 // a < b ? -1 : 0 -> RES = ~setcc_carry
13428 // a < b ? 0 : -1 -> RES = setcc_carry
13429 // a >= b ? -1 : 0 -> RES = setcc_carry
13430 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13431 if (Cond.getOpcode() == X86ISD::SUB) {
13432 Cond = ConvertCmpIfNecessary(Cond, DAG);
13433 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13435 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13436 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13437 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13438 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13439 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13440 return DAG.getNOT(DL, Res, Res.getValueType());
13445 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13446 // widen the cmov and push the truncate through. This avoids introducing a new
13447 // branch during isel and doesn't add any extensions.
13448 if (Op.getValueType() == MVT::i8 &&
13449 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13450 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13451 if (T1.getValueType() == T2.getValueType() &&
13452 // Blacklist CopyFromReg to avoid partial register stalls.
13453 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13454 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13455 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13456 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13460 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13461 // condition is true.
13462 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13463 SDValue Ops[] = { Op2, Op1, CC, Cond };
13464 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13467 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13468 MVT VT = Op->getSimpleValueType(0);
13469 SDValue In = Op->getOperand(0);
13470 MVT InVT = In.getSimpleValueType();
13473 unsigned int NumElts = VT.getVectorNumElements();
13474 if (NumElts != 8 && NumElts != 16)
13477 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13478 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13480 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13481 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13483 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13484 Constant *C = ConstantInt::get(*DAG.getContext(),
13485 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13487 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13488 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13489 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13490 MachinePointerInfo::getConstantPool(),
13491 false, false, false, Alignment);
13492 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13493 if (VT.is512BitVector())
13495 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13498 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13499 SelectionDAG &DAG) {
13500 MVT VT = Op->getSimpleValueType(0);
13501 SDValue In = Op->getOperand(0);
13502 MVT InVT = In.getSimpleValueType();
13505 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13506 return LowerSIGN_EXTEND_AVX512(Op, DAG);
13508 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13509 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13510 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13513 if (Subtarget->hasInt256())
13514 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13516 // Optimize vectors in AVX mode
13517 // Sign extend v8i16 to v8i32 and
13520 // Divide input vector into two parts
13521 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13522 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13523 // concat the vectors to original VT
13525 unsigned NumElems = InVT.getVectorNumElements();
13526 SDValue Undef = DAG.getUNDEF(InVT);
13528 SmallVector<int,8> ShufMask1(NumElems, -1);
13529 for (unsigned i = 0; i != NumElems/2; ++i)
13532 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13534 SmallVector<int,8> ShufMask2(NumElems, -1);
13535 for (unsigned i = 0; i != NumElems/2; ++i)
13536 ShufMask2[i] = i + NumElems/2;
13538 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13540 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13541 VT.getVectorNumElements()/2);
13543 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13544 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13546 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13549 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13550 // may emit an illegal shuffle but the expansion is still better than scalar
13551 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13552 // we'll emit a shuffle and a arithmetic shift.
13553 // TODO: It is possible to support ZExt by zeroing the undef values during
13554 // the shuffle phase or after the shuffle.
13555 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13556 SelectionDAG &DAG) {
13557 MVT RegVT = Op.getSimpleValueType();
13558 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13559 assert(RegVT.isInteger() &&
13560 "We only custom lower integer vector sext loads.");
13562 // Nothing useful we can do without SSE2 shuffles.
13563 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13565 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13567 EVT MemVT = Ld->getMemoryVT();
13568 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13569 unsigned RegSz = RegVT.getSizeInBits();
13571 ISD::LoadExtType Ext = Ld->getExtensionType();
13573 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13574 && "Only anyext and sext are currently implemented.");
13575 assert(MemVT != RegVT && "Cannot extend to the same type");
13576 assert(MemVT.isVector() && "Must load a vector from memory");
13578 unsigned NumElems = RegVT.getVectorNumElements();
13579 unsigned MemSz = MemVT.getSizeInBits();
13580 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13582 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13583 // The only way in which we have a legal 256-bit vector result but not the
13584 // integer 256-bit operations needed to directly lower a sextload is if we
13585 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13586 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13587 // correctly legalized. We do this late to allow the canonical form of
13588 // sextload to persist throughout the rest of the DAG combiner -- it wants
13589 // to fold together any extensions it can, and so will fuse a sign_extend
13590 // of an sextload into a sextload targeting a wider value.
13592 if (MemSz == 128) {
13593 // Just switch this to a normal load.
13594 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13595 "it must be a legal 128-bit vector "
13597 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13598 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13599 Ld->isInvariant(), Ld->getAlignment());
13601 assert(MemSz < 128 &&
13602 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13603 // Do an sext load to a 128-bit vector type. We want to use the same
13604 // number of elements, but elements half as wide. This will end up being
13605 // recursively lowered by this routine, but will succeed as we definitely
13606 // have all the necessary features if we're using AVX1.
13608 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13609 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13611 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13612 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13613 Ld->isNonTemporal(), Ld->isInvariant(),
13614 Ld->getAlignment());
13617 // Replace chain users with the new chain.
13618 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13619 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13621 // Finally, do a normal sign-extend to the desired register.
13622 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13625 // All sizes must be a power of two.
13626 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13627 "Non-power-of-two elements are not custom lowered!");
13629 // Attempt to load the original value using scalar loads.
13630 // Find the largest scalar type that divides the total loaded size.
13631 MVT SclrLoadTy = MVT::i8;
13632 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13633 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13634 MVT Tp = (MVT::SimpleValueType)tp;
13635 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13640 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13641 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13643 SclrLoadTy = MVT::f64;
13645 // Calculate the number of scalar loads that we need to perform
13646 // in order to load our vector from memory.
13647 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13649 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13650 "Can only lower sext loads with a single scalar load!");
13652 unsigned loadRegZize = RegSz;
13653 if (Ext == ISD::SEXTLOAD && RegSz == 256)
13656 // Represent our vector as a sequence of elements which are the
13657 // largest scalar that we can load.
13658 EVT LoadUnitVecVT = EVT::getVectorVT(
13659 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13661 // Represent the data using the same element type that is stored in
13662 // memory. In practice, we ''widen'' MemVT.
13664 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13665 loadRegZize / MemVT.getScalarType().getSizeInBits());
13667 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13668 "Invalid vector type");
13670 // We can't shuffle using an illegal type.
13671 assert(TLI.isTypeLegal(WideVecVT) &&
13672 "We only lower types that form legal widened vector types");
13674 SmallVector<SDValue, 8> Chains;
13675 SDValue Ptr = Ld->getBasePtr();
13676 SDValue Increment =
13677 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13678 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13680 for (unsigned i = 0; i < NumLoads; ++i) {
13681 // Perform a single load.
13682 SDValue ScalarLoad =
13683 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13684 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13685 Ld->getAlignment());
13686 Chains.push_back(ScalarLoad.getValue(1));
13687 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13688 // another round of DAGCombining.
13690 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13692 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13693 ScalarLoad, DAG.getIntPtrConstant(i));
13695 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13698 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13700 // Bitcast the loaded value to a vector of the original element type, in
13701 // the size of the target vector type.
13702 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13703 unsigned SizeRatio = RegSz / MemSz;
13705 if (Ext == ISD::SEXTLOAD) {
13706 // If we have SSE4.1, we can directly emit a VSEXT node.
13707 if (Subtarget->hasSSE41()) {
13708 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13709 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13713 // Otherwise we'll shuffle the small elements in the high bits of the
13714 // larger type and perform an arithmetic shift. If the shift is not legal
13715 // it's better to scalarize.
13716 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13717 "We can't implement a sext load without an arithmetic right shift!");
13719 // Redistribute the loaded elements into the different locations.
13720 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13721 for (unsigned i = 0; i != NumElems; ++i)
13722 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13724 SDValue Shuff = DAG.getVectorShuffle(
13725 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13727 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13729 // Build the arithmetic shift.
13730 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13731 MemVT.getVectorElementType().getSizeInBits();
13733 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13735 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13739 // Redistribute the loaded elements into the different locations.
13740 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13741 for (unsigned i = 0; i != NumElems; ++i)
13742 ShuffleVec[i * SizeRatio] = i;
13744 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13745 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13747 // Bitcast to the requested type.
13748 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13749 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13753 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13754 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13755 // from the AND / OR.
13756 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13757 Opc = Op.getOpcode();
13758 if (Opc != ISD::OR && Opc != ISD::AND)
13760 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13761 Op.getOperand(0).hasOneUse() &&
13762 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13763 Op.getOperand(1).hasOneUse());
13766 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13767 // 1 and that the SETCC node has a single use.
13768 static bool isXor1OfSetCC(SDValue Op) {
13769 if (Op.getOpcode() != ISD::XOR)
13771 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13772 if (N1C && N1C->getAPIntValue() == 1) {
13773 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13774 Op.getOperand(0).hasOneUse();
13779 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13780 bool addTest = true;
13781 SDValue Chain = Op.getOperand(0);
13782 SDValue Cond = Op.getOperand(1);
13783 SDValue Dest = Op.getOperand(2);
13786 bool Inverted = false;
13788 if (Cond.getOpcode() == ISD::SETCC) {
13789 // Check for setcc([su]{add,sub,mul}o == 0).
13790 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13791 isa<ConstantSDNode>(Cond.getOperand(1)) &&
13792 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13793 Cond.getOperand(0).getResNo() == 1 &&
13794 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13795 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13796 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13797 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13798 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13799 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13801 Cond = Cond.getOperand(0);
13803 SDValue NewCond = LowerSETCC(Cond, DAG);
13804 if (NewCond.getNode())
13809 // FIXME: LowerXALUO doesn't handle these!!
13810 else if (Cond.getOpcode() == X86ISD::ADD ||
13811 Cond.getOpcode() == X86ISD::SUB ||
13812 Cond.getOpcode() == X86ISD::SMUL ||
13813 Cond.getOpcode() == X86ISD::UMUL)
13814 Cond = LowerXALUO(Cond, DAG);
13817 // Look pass (and (setcc_carry (cmp ...)), 1).
13818 if (Cond.getOpcode() == ISD::AND &&
13819 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13820 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13821 if (C && C->getAPIntValue() == 1)
13822 Cond = Cond.getOperand(0);
13825 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13826 // setting operand in place of the X86ISD::SETCC.
13827 unsigned CondOpcode = Cond.getOpcode();
13828 if (CondOpcode == X86ISD::SETCC ||
13829 CondOpcode == X86ISD::SETCC_CARRY) {
13830 CC = Cond.getOperand(0);
13832 SDValue Cmp = Cond.getOperand(1);
13833 unsigned Opc = Cmp.getOpcode();
13834 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13835 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13839 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13843 // These can only come from an arithmetic instruction with overflow,
13844 // e.g. SADDO, UADDO.
13845 Cond = Cond.getNode()->getOperand(1);
13851 CondOpcode = Cond.getOpcode();
13852 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13853 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13854 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13855 Cond.getOperand(0).getValueType() != MVT::i8)) {
13856 SDValue LHS = Cond.getOperand(0);
13857 SDValue RHS = Cond.getOperand(1);
13858 unsigned X86Opcode;
13861 // Keep this in sync with LowerXALUO, otherwise we might create redundant
13862 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13864 switch (CondOpcode) {
13865 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13867 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13869 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13872 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13873 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13875 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13877 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13880 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13881 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13882 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13883 default: llvm_unreachable("unexpected overflowing operator");
13886 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13887 if (CondOpcode == ISD::UMULO)
13888 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13891 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13893 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13895 if (CondOpcode == ISD::UMULO)
13896 Cond = X86Op.getValue(2);
13898 Cond = X86Op.getValue(1);
13900 CC = DAG.getConstant(X86Cond, MVT::i8);
13904 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13905 SDValue Cmp = Cond.getOperand(0).getOperand(1);
13906 if (CondOpc == ISD::OR) {
13907 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13908 // two branches instead of an explicit OR instruction with a
13910 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13911 isX86LogicalCmp(Cmp)) {
13912 CC = Cond.getOperand(0).getOperand(0);
13913 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13914 Chain, Dest, CC, Cmp);
13915 CC = Cond.getOperand(1).getOperand(0);
13919 } else { // ISD::AND
13920 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13921 // two branches instead of an explicit AND instruction with a
13922 // separate test. However, we only do this if this block doesn't
13923 // have a fall-through edge, because this requires an explicit
13924 // jmp when the condition is false.
13925 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13926 isX86LogicalCmp(Cmp) &&
13927 Op.getNode()->hasOneUse()) {
13928 X86::CondCode CCode =
13929 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13930 CCode = X86::GetOppositeBranchCondition(CCode);
13931 CC = DAG.getConstant(CCode, MVT::i8);
13932 SDNode *User = *Op.getNode()->use_begin();
13933 // Look for an unconditional branch following this conditional branch.
13934 // We need this because we need to reverse the successors in order
13935 // to implement FCMP_OEQ.
13936 if (User->getOpcode() == ISD::BR) {
13937 SDValue FalseBB = User->getOperand(1);
13939 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13940 assert(NewBR == User);
13944 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13945 Chain, Dest, CC, Cmp);
13946 X86::CondCode CCode =
13947 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13948 CCode = X86::GetOppositeBranchCondition(CCode);
13949 CC = DAG.getConstant(CCode, MVT::i8);
13955 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13956 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13957 // It should be transformed during dag combiner except when the condition
13958 // is set by a arithmetics with overflow node.
13959 X86::CondCode CCode =
13960 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13961 CCode = X86::GetOppositeBranchCondition(CCode);
13962 CC = DAG.getConstant(CCode, MVT::i8);
13963 Cond = Cond.getOperand(0).getOperand(1);
13965 } else if (Cond.getOpcode() == ISD::SETCC &&
13966 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13967 // For FCMP_OEQ, we can emit
13968 // two branches instead of an explicit AND instruction with a
13969 // separate test. However, we only do this if this block doesn't
13970 // have a fall-through edge, because this requires an explicit
13971 // jmp when the condition is false.
13972 if (Op.getNode()->hasOneUse()) {
13973 SDNode *User = *Op.getNode()->use_begin();
13974 // Look for an unconditional branch following this conditional branch.
13975 // We need this because we need to reverse the successors in order
13976 // to implement FCMP_OEQ.
13977 if (User->getOpcode() == ISD::BR) {
13978 SDValue FalseBB = User->getOperand(1);
13980 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13981 assert(NewBR == User);
13985 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13986 Cond.getOperand(0), Cond.getOperand(1));
13987 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13988 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13989 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13990 Chain, Dest, CC, Cmp);
13991 CC = DAG.getConstant(X86::COND_P, MVT::i8);
13996 } else if (Cond.getOpcode() == ISD::SETCC &&
13997 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13998 // For FCMP_UNE, we can emit
13999 // two branches instead of an explicit AND instruction with a
14000 // separate test. However, we only do this if this block doesn't
14001 // have a fall-through edge, because this requires an explicit
14002 // jmp when the condition is false.
14003 if (Op.getNode()->hasOneUse()) {
14004 SDNode *User = *Op.getNode()->use_begin();
14005 // Look for an unconditional branch following this conditional branch.
14006 // We need this because we need to reverse the successors in order
14007 // to implement FCMP_UNE.
14008 if (User->getOpcode() == ISD::BR) {
14009 SDValue FalseBB = User->getOperand(1);
14011 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14012 assert(NewBR == User);
14015 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14016 Cond.getOperand(0), Cond.getOperand(1));
14017 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14018 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14019 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14020 Chain, Dest, CC, Cmp);
14021 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14031 // Look pass the truncate if the high bits are known zero.
14032 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14033 Cond = Cond.getOperand(0);
14035 // We know the result of AND is compared against zero. Try to match
14037 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14038 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14039 if (NewSetCC.getNode()) {
14040 CC = NewSetCC.getOperand(0);
14041 Cond = NewSetCC.getOperand(1);
14048 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14049 CC = DAG.getConstant(X86Cond, MVT::i8);
14050 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14052 Cond = ConvertCmpIfNecessary(Cond, DAG);
14053 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14054 Chain, Dest, CC, Cond);
14057 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14058 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14059 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14060 // that the guard pages used by the OS virtual memory manager are allocated in
14061 // correct sequence.
14063 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14064 SelectionDAG &DAG) const {
14065 MachineFunction &MF = DAG.getMachineFunction();
14066 bool SplitStack = MF.shouldSplitStack();
14067 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
14072 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14073 SDNode* Node = Op.getNode();
14075 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14076 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14077 " not tell us which reg is the stack pointer!");
14078 EVT VT = Node->getValueType(0);
14079 SDValue Tmp1 = SDValue(Node, 0);
14080 SDValue Tmp2 = SDValue(Node, 1);
14081 SDValue Tmp3 = Node->getOperand(2);
14082 SDValue Chain = Tmp1.getOperand(0);
14084 // Chain the dynamic stack allocation so that it doesn't modify the stack
14085 // pointer when other instructions are using the stack.
14086 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14089 SDValue Size = Tmp2.getOperand(1);
14090 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14091 Chain = SP.getValue(1);
14092 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14093 const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
14094 unsigned StackAlign = TFI.getStackAlignment();
14095 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14096 if (Align > StackAlign)
14097 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14098 DAG.getConstant(-(uint64_t)Align, VT));
14099 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14101 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14102 DAG.getIntPtrConstant(0, true), SDValue(),
14105 SDValue Ops[2] = { Tmp1, Tmp2 };
14106 return DAG.getMergeValues(Ops, dl);
14110 SDValue Chain = Op.getOperand(0);
14111 SDValue Size = Op.getOperand(1);
14112 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14113 EVT VT = Op.getNode()->getValueType(0);
14115 bool Is64Bit = Subtarget->is64Bit();
14116 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
14119 MachineRegisterInfo &MRI = MF.getRegInfo();
14122 // The 64 bit implementation of segmented stacks needs to clobber both r10
14123 // r11. This makes it impossible to use it along with nested parameters.
14124 const Function *F = MF.getFunction();
14126 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14128 if (I->hasNestAttr())
14129 report_fatal_error("Cannot use segmented stacks with functions that "
14130 "have nested arguments.");
14133 const TargetRegisterClass *AddrRegClass =
14134 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
14135 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14136 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14137 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14138 DAG.getRegister(Vreg, SPTy));
14139 SDValue Ops1[2] = { Value, Chain };
14140 return DAG.getMergeValues(Ops1, dl);
14143 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
14145 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14146 Flag = Chain.getValue(1);
14147 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14149 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14151 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
14152 DAG.getSubtarget().getRegisterInfo());
14153 unsigned SPReg = RegInfo->getStackRegister();
14154 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14155 Chain = SP.getValue(1);
14158 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14159 DAG.getConstant(-(uint64_t)Align, VT));
14160 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14163 SDValue Ops1[2] = { SP, Chain };
14164 return DAG.getMergeValues(Ops1, dl);
14168 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14169 MachineFunction &MF = DAG.getMachineFunction();
14170 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14172 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14175 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14176 // vastart just stores the address of the VarArgsFrameIndex slot into the
14177 // memory location argument.
14178 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14180 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14181 MachinePointerInfo(SV), false, false, 0);
14185 // gp_offset (0 - 6 * 8)
14186 // fp_offset (48 - 48 + 8 * 16)
14187 // overflow_arg_area (point to parameters coming in memory).
14189 SmallVector<SDValue, 8> MemOps;
14190 SDValue FIN = Op.getOperand(1);
14192 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14193 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14195 FIN, MachinePointerInfo(SV), false, false, 0);
14196 MemOps.push_back(Store);
14199 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14200 FIN, DAG.getIntPtrConstant(4));
14201 Store = DAG.getStore(Op.getOperand(0), DL,
14202 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14204 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14205 MemOps.push_back(Store);
14207 // Store ptr to overflow_arg_area
14208 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14209 FIN, DAG.getIntPtrConstant(4));
14210 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14212 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14213 MachinePointerInfo(SV, 8),
14215 MemOps.push_back(Store);
14217 // Store ptr to reg_save_area.
14218 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14219 FIN, DAG.getIntPtrConstant(8));
14220 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14222 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14223 MachinePointerInfo(SV, 16), false, false, 0);
14224 MemOps.push_back(Store);
14225 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14228 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14229 assert(Subtarget->is64Bit() &&
14230 "LowerVAARG only handles 64-bit va_arg!");
14231 assert((Subtarget->isTargetLinux() ||
14232 Subtarget->isTargetDarwin()) &&
14233 "Unhandled target in LowerVAARG");
14234 assert(Op.getNode()->getNumOperands() == 4);
14235 SDValue Chain = Op.getOperand(0);
14236 SDValue SrcPtr = Op.getOperand(1);
14237 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14238 unsigned Align = Op.getConstantOperandVal(3);
14241 EVT ArgVT = Op.getNode()->getValueType(0);
14242 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14243 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14246 // Decide which area this value should be read from.
14247 // TODO: Implement the AMD64 ABI in its entirety. This simple
14248 // selection mechanism works only for the basic types.
14249 if (ArgVT == MVT::f80) {
14250 llvm_unreachable("va_arg for f80 not yet implemented");
14251 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14252 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14253 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14254 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14256 llvm_unreachable("Unhandled argument type in LowerVAARG");
14259 if (ArgMode == 2) {
14260 // Sanity Check: Make sure using fp_offset makes sense.
14261 assert(!DAG.getTarget().Options.UseSoftFloat &&
14262 !(DAG.getMachineFunction()
14263 .getFunction()->getAttributes()
14264 .hasAttribute(AttributeSet::FunctionIndex,
14265 Attribute::NoImplicitFloat)) &&
14266 Subtarget->hasSSE1());
14269 // Insert VAARG_64 node into the DAG
14270 // VAARG_64 returns two values: Variable Argument Address, Chain
14271 SmallVector<SDValue, 11> InstOps;
14272 InstOps.push_back(Chain);
14273 InstOps.push_back(SrcPtr);
14274 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
14275 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
14276 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
14277 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14278 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14279 VTs, InstOps, MVT::i64,
14280 MachinePointerInfo(SV),
14282 /*Volatile=*/false,
14284 /*WriteMem=*/true);
14285 Chain = VAARG.getValue(1);
14287 // Load the next argument and return it
14288 return DAG.getLoad(ArgVT, dl,
14291 MachinePointerInfo(),
14292 false, false, false, 0);
14295 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14296 SelectionDAG &DAG) {
14297 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14298 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14299 SDValue Chain = Op.getOperand(0);
14300 SDValue DstPtr = Op.getOperand(1);
14301 SDValue SrcPtr = Op.getOperand(2);
14302 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14303 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14306 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14307 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14309 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14312 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14313 // amount is a constant. Takes immediate version of shift as input.
14314 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14315 SDValue SrcOp, uint64_t ShiftAmt,
14316 SelectionDAG &DAG) {
14317 MVT ElementType = VT.getVectorElementType();
14319 // Fold this packed shift into its first operand if ShiftAmt is 0.
14323 // Check for ShiftAmt >= element width
14324 if (ShiftAmt >= ElementType.getSizeInBits()) {
14325 if (Opc == X86ISD::VSRAI)
14326 ShiftAmt = ElementType.getSizeInBits() - 1;
14328 return DAG.getConstant(0, VT);
14331 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14332 && "Unknown target vector shift-by-constant node");
14334 // Fold this packed vector shift into a build vector if SrcOp is a
14335 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14336 if (VT == SrcOp.getSimpleValueType() &&
14337 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14338 SmallVector<SDValue, 8> Elts;
14339 unsigned NumElts = SrcOp->getNumOperands();
14340 ConstantSDNode *ND;
14343 default: llvm_unreachable(nullptr);
14344 case X86ISD::VSHLI:
14345 for (unsigned i=0; i!=NumElts; ++i) {
14346 SDValue CurrentOp = SrcOp->getOperand(i);
14347 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14348 Elts.push_back(CurrentOp);
14351 ND = cast<ConstantSDNode>(CurrentOp);
14352 const APInt &C = ND->getAPIntValue();
14353 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14356 case X86ISD::VSRLI:
14357 for (unsigned i=0; i!=NumElts; ++i) {
14358 SDValue CurrentOp = SrcOp->getOperand(i);
14359 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14360 Elts.push_back(CurrentOp);
14363 ND = cast<ConstantSDNode>(CurrentOp);
14364 const APInt &C = ND->getAPIntValue();
14365 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14368 case X86ISD::VSRAI:
14369 for (unsigned i=0; i!=NumElts; ++i) {
14370 SDValue CurrentOp = SrcOp->getOperand(i);
14371 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14372 Elts.push_back(CurrentOp);
14375 ND = cast<ConstantSDNode>(CurrentOp);
14376 const APInt &C = ND->getAPIntValue();
14377 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14382 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14385 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14388 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14389 // may or may not be a constant. Takes immediate version of shift as input.
14390 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14391 SDValue SrcOp, SDValue ShAmt,
14392 SelectionDAG &DAG) {
14393 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14395 // Catch shift-by-constant.
14396 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14397 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14398 CShAmt->getZExtValue(), DAG);
14400 // Change opcode to non-immediate version
14402 default: llvm_unreachable("Unknown target vector shift node");
14403 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14404 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14405 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14408 // Need to build a vector containing shift amount
14409 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14412 ShOps[1] = DAG.getConstant(0, MVT::i32);
14413 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14414 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14416 // The return type has to be a 128-bit type with the same element
14417 // type as the input type.
14418 MVT EltVT = VT.getVectorElementType();
14419 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14421 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14422 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14425 /// \brief Return (vselect \p Mask, \p Op, \p PreservedSrc) along with the
14426 /// necessary casting for \p Mask when lowering masking intrinsics.
14427 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14428 SDValue PreservedSrc, SelectionDAG &DAG) {
14429 EVT VT = Op.getValueType();
14430 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14431 MVT::i1, VT.getVectorNumElements());
14434 assert(MaskVT.isSimple() && "invalid mask type");
14435 return DAG.getNode(ISD::VSELECT, dl, VT,
14436 DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask),
14440 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
14442 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14443 case Intrinsic::x86_fma_vfmadd_ps:
14444 case Intrinsic::x86_fma_vfmadd_pd:
14445 case Intrinsic::x86_fma_vfmadd_ps_256:
14446 case Intrinsic::x86_fma_vfmadd_pd_256:
14447 case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14448 case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14449 return X86ISD::FMADD;
14450 case Intrinsic::x86_fma_vfmsub_ps:
14451 case Intrinsic::x86_fma_vfmsub_pd:
14452 case Intrinsic::x86_fma_vfmsub_ps_256:
14453 case Intrinsic::x86_fma_vfmsub_pd_256:
14454 case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14455 case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14456 return X86ISD::FMSUB;
14457 case Intrinsic::x86_fma_vfnmadd_ps:
14458 case Intrinsic::x86_fma_vfnmadd_pd:
14459 case Intrinsic::x86_fma_vfnmadd_ps_256:
14460 case Intrinsic::x86_fma_vfnmadd_pd_256:
14461 case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14462 case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14463 return X86ISD::FNMADD;
14464 case Intrinsic::x86_fma_vfnmsub_ps:
14465 case Intrinsic::x86_fma_vfnmsub_pd:
14466 case Intrinsic::x86_fma_vfnmsub_ps_256:
14467 case Intrinsic::x86_fma_vfnmsub_pd_256:
14468 case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14469 case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14470 return X86ISD::FNMSUB;
14471 case Intrinsic::x86_fma_vfmaddsub_ps:
14472 case Intrinsic::x86_fma_vfmaddsub_pd:
14473 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14474 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14475 case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14476 case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14477 return X86ISD::FMADDSUB;
14478 case Intrinsic::x86_fma_vfmsubadd_ps:
14479 case Intrinsic::x86_fma_vfmsubadd_pd:
14480 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14481 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14482 case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14483 case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
14484 return X86ISD::FMSUBADD;
14488 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14490 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14492 default: return SDValue(); // Don't custom lower most intrinsics.
14493 // Comparison intrinsics.
14494 case Intrinsic::x86_sse_comieq_ss:
14495 case Intrinsic::x86_sse_comilt_ss:
14496 case Intrinsic::x86_sse_comile_ss:
14497 case Intrinsic::x86_sse_comigt_ss:
14498 case Intrinsic::x86_sse_comige_ss:
14499 case Intrinsic::x86_sse_comineq_ss:
14500 case Intrinsic::x86_sse_ucomieq_ss:
14501 case Intrinsic::x86_sse_ucomilt_ss:
14502 case Intrinsic::x86_sse_ucomile_ss:
14503 case Intrinsic::x86_sse_ucomigt_ss:
14504 case Intrinsic::x86_sse_ucomige_ss:
14505 case Intrinsic::x86_sse_ucomineq_ss:
14506 case Intrinsic::x86_sse2_comieq_sd:
14507 case Intrinsic::x86_sse2_comilt_sd:
14508 case Intrinsic::x86_sse2_comile_sd:
14509 case Intrinsic::x86_sse2_comigt_sd:
14510 case Intrinsic::x86_sse2_comige_sd:
14511 case Intrinsic::x86_sse2_comineq_sd:
14512 case Intrinsic::x86_sse2_ucomieq_sd:
14513 case Intrinsic::x86_sse2_ucomilt_sd:
14514 case Intrinsic::x86_sse2_ucomile_sd:
14515 case Intrinsic::x86_sse2_ucomigt_sd:
14516 case Intrinsic::x86_sse2_ucomige_sd:
14517 case Intrinsic::x86_sse2_ucomineq_sd: {
14521 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14522 case Intrinsic::x86_sse_comieq_ss:
14523 case Intrinsic::x86_sse2_comieq_sd:
14524 Opc = X86ISD::COMI;
14527 case Intrinsic::x86_sse_comilt_ss:
14528 case Intrinsic::x86_sse2_comilt_sd:
14529 Opc = X86ISD::COMI;
14532 case Intrinsic::x86_sse_comile_ss:
14533 case Intrinsic::x86_sse2_comile_sd:
14534 Opc = X86ISD::COMI;
14537 case Intrinsic::x86_sse_comigt_ss:
14538 case Intrinsic::x86_sse2_comigt_sd:
14539 Opc = X86ISD::COMI;
14542 case Intrinsic::x86_sse_comige_ss:
14543 case Intrinsic::x86_sse2_comige_sd:
14544 Opc = X86ISD::COMI;
14547 case Intrinsic::x86_sse_comineq_ss:
14548 case Intrinsic::x86_sse2_comineq_sd:
14549 Opc = X86ISD::COMI;
14552 case Intrinsic::x86_sse_ucomieq_ss:
14553 case Intrinsic::x86_sse2_ucomieq_sd:
14554 Opc = X86ISD::UCOMI;
14557 case Intrinsic::x86_sse_ucomilt_ss:
14558 case Intrinsic::x86_sse2_ucomilt_sd:
14559 Opc = X86ISD::UCOMI;
14562 case Intrinsic::x86_sse_ucomile_ss:
14563 case Intrinsic::x86_sse2_ucomile_sd:
14564 Opc = X86ISD::UCOMI;
14567 case Intrinsic::x86_sse_ucomigt_ss:
14568 case Intrinsic::x86_sse2_ucomigt_sd:
14569 Opc = X86ISD::UCOMI;
14572 case Intrinsic::x86_sse_ucomige_ss:
14573 case Intrinsic::x86_sse2_ucomige_sd:
14574 Opc = X86ISD::UCOMI;
14577 case Intrinsic::x86_sse_ucomineq_ss:
14578 case Intrinsic::x86_sse2_ucomineq_sd:
14579 Opc = X86ISD::UCOMI;
14584 SDValue LHS = Op.getOperand(1);
14585 SDValue RHS = Op.getOperand(2);
14586 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14587 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14588 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
14589 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14590 DAG.getConstant(X86CC, MVT::i8), Cond);
14591 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14594 // Arithmetic intrinsics.
14595 case Intrinsic::x86_sse2_pmulu_dq:
14596 case Intrinsic::x86_avx2_pmulu_dq:
14597 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14598 Op.getOperand(1), Op.getOperand(2));
14600 case Intrinsic::x86_sse41_pmuldq:
14601 case Intrinsic::x86_avx2_pmul_dq:
14602 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14603 Op.getOperand(1), Op.getOperand(2));
14605 case Intrinsic::x86_sse2_pmulhu_w:
14606 case Intrinsic::x86_avx2_pmulhu_w:
14607 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14608 Op.getOperand(1), Op.getOperand(2));
14610 case Intrinsic::x86_sse2_pmulh_w:
14611 case Intrinsic::x86_avx2_pmulh_w:
14612 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14613 Op.getOperand(1), Op.getOperand(2));
14615 // SSE2/AVX2 sub with unsigned saturation intrinsics
14616 case Intrinsic::x86_sse2_psubus_b:
14617 case Intrinsic::x86_sse2_psubus_w:
14618 case Intrinsic::x86_avx2_psubus_b:
14619 case Intrinsic::x86_avx2_psubus_w:
14620 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
14621 Op.getOperand(1), Op.getOperand(2));
14623 // SSE3/AVX horizontal add/sub intrinsics
14624 case Intrinsic::x86_sse3_hadd_ps:
14625 case Intrinsic::x86_sse3_hadd_pd:
14626 case Intrinsic::x86_avx_hadd_ps_256:
14627 case Intrinsic::x86_avx_hadd_pd_256:
14628 case Intrinsic::x86_sse3_hsub_ps:
14629 case Intrinsic::x86_sse3_hsub_pd:
14630 case Intrinsic::x86_avx_hsub_ps_256:
14631 case Intrinsic::x86_avx_hsub_pd_256:
14632 case Intrinsic::x86_ssse3_phadd_w_128:
14633 case Intrinsic::x86_ssse3_phadd_d_128:
14634 case Intrinsic::x86_avx2_phadd_w:
14635 case Intrinsic::x86_avx2_phadd_d:
14636 case Intrinsic::x86_ssse3_phsub_w_128:
14637 case Intrinsic::x86_ssse3_phsub_d_128:
14638 case Intrinsic::x86_avx2_phsub_w:
14639 case Intrinsic::x86_avx2_phsub_d: {
14642 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14643 case Intrinsic::x86_sse3_hadd_ps:
14644 case Intrinsic::x86_sse3_hadd_pd:
14645 case Intrinsic::x86_avx_hadd_ps_256:
14646 case Intrinsic::x86_avx_hadd_pd_256:
14647 Opcode = X86ISD::FHADD;
14649 case Intrinsic::x86_sse3_hsub_ps:
14650 case Intrinsic::x86_sse3_hsub_pd:
14651 case Intrinsic::x86_avx_hsub_ps_256:
14652 case Intrinsic::x86_avx_hsub_pd_256:
14653 Opcode = X86ISD::FHSUB;
14655 case Intrinsic::x86_ssse3_phadd_w_128:
14656 case Intrinsic::x86_ssse3_phadd_d_128:
14657 case Intrinsic::x86_avx2_phadd_w:
14658 case Intrinsic::x86_avx2_phadd_d:
14659 Opcode = X86ISD::HADD;
14661 case Intrinsic::x86_ssse3_phsub_w_128:
14662 case Intrinsic::x86_ssse3_phsub_d_128:
14663 case Intrinsic::x86_avx2_phsub_w:
14664 case Intrinsic::x86_avx2_phsub_d:
14665 Opcode = X86ISD::HSUB;
14668 return DAG.getNode(Opcode, dl, Op.getValueType(),
14669 Op.getOperand(1), Op.getOperand(2));
14672 // SSE2/SSE41/AVX2 integer max/min intrinsics.
14673 case Intrinsic::x86_sse2_pmaxu_b:
14674 case Intrinsic::x86_sse41_pmaxuw:
14675 case Intrinsic::x86_sse41_pmaxud:
14676 case Intrinsic::x86_avx2_pmaxu_b:
14677 case Intrinsic::x86_avx2_pmaxu_w:
14678 case Intrinsic::x86_avx2_pmaxu_d:
14679 case Intrinsic::x86_sse2_pminu_b:
14680 case Intrinsic::x86_sse41_pminuw:
14681 case Intrinsic::x86_sse41_pminud:
14682 case Intrinsic::x86_avx2_pminu_b:
14683 case Intrinsic::x86_avx2_pminu_w:
14684 case Intrinsic::x86_avx2_pminu_d:
14685 case Intrinsic::x86_sse41_pmaxsb:
14686 case Intrinsic::x86_sse2_pmaxs_w:
14687 case Intrinsic::x86_sse41_pmaxsd:
14688 case Intrinsic::x86_avx2_pmaxs_b:
14689 case Intrinsic::x86_avx2_pmaxs_w:
14690 case Intrinsic::x86_avx2_pmaxs_d:
14691 case Intrinsic::x86_sse41_pminsb:
14692 case Intrinsic::x86_sse2_pmins_w:
14693 case Intrinsic::x86_sse41_pminsd:
14694 case Intrinsic::x86_avx2_pmins_b:
14695 case Intrinsic::x86_avx2_pmins_w:
14696 case Intrinsic::x86_avx2_pmins_d: {
14699 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14700 case Intrinsic::x86_sse2_pmaxu_b:
14701 case Intrinsic::x86_sse41_pmaxuw:
14702 case Intrinsic::x86_sse41_pmaxud:
14703 case Intrinsic::x86_avx2_pmaxu_b:
14704 case Intrinsic::x86_avx2_pmaxu_w:
14705 case Intrinsic::x86_avx2_pmaxu_d:
14706 Opcode = X86ISD::UMAX;
14708 case Intrinsic::x86_sse2_pminu_b:
14709 case Intrinsic::x86_sse41_pminuw:
14710 case Intrinsic::x86_sse41_pminud:
14711 case Intrinsic::x86_avx2_pminu_b:
14712 case Intrinsic::x86_avx2_pminu_w:
14713 case Intrinsic::x86_avx2_pminu_d:
14714 Opcode = X86ISD::UMIN;
14716 case Intrinsic::x86_sse41_pmaxsb:
14717 case Intrinsic::x86_sse2_pmaxs_w:
14718 case Intrinsic::x86_sse41_pmaxsd:
14719 case Intrinsic::x86_avx2_pmaxs_b:
14720 case Intrinsic::x86_avx2_pmaxs_w:
14721 case Intrinsic::x86_avx2_pmaxs_d:
14722 Opcode = X86ISD::SMAX;
14724 case Intrinsic::x86_sse41_pminsb:
14725 case Intrinsic::x86_sse2_pmins_w:
14726 case Intrinsic::x86_sse41_pminsd:
14727 case Intrinsic::x86_avx2_pmins_b:
14728 case Intrinsic::x86_avx2_pmins_w:
14729 case Intrinsic::x86_avx2_pmins_d:
14730 Opcode = X86ISD::SMIN;
14733 return DAG.getNode(Opcode, dl, Op.getValueType(),
14734 Op.getOperand(1), Op.getOperand(2));
14737 // SSE/SSE2/AVX floating point max/min intrinsics.
14738 case Intrinsic::x86_sse_max_ps:
14739 case Intrinsic::x86_sse2_max_pd:
14740 case Intrinsic::x86_avx_max_ps_256:
14741 case Intrinsic::x86_avx_max_pd_256:
14742 case Intrinsic::x86_sse_min_ps:
14743 case Intrinsic::x86_sse2_min_pd:
14744 case Intrinsic::x86_avx_min_ps_256:
14745 case Intrinsic::x86_avx_min_pd_256: {
14748 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14749 case Intrinsic::x86_sse_max_ps:
14750 case Intrinsic::x86_sse2_max_pd:
14751 case Intrinsic::x86_avx_max_ps_256:
14752 case Intrinsic::x86_avx_max_pd_256:
14753 Opcode = X86ISD::FMAX;
14755 case Intrinsic::x86_sse_min_ps:
14756 case Intrinsic::x86_sse2_min_pd:
14757 case Intrinsic::x86_avx_min_ps_256:
14758 case Intrinsic::x86_avx_min_pd_256:
14759 Opcode = X86ISD::FMIN;
14762 return DAG.getNode(Opcode, dl, Op.getValueType(),
14763 Op.getOperand(1), Op.getOperand(2));
14766 // AVX2 variable shift intrinsics
14767 case Intrinsic::x86_avx2_psllv_d:
14768 case Intrinsic::x86_avx2_psllv_q:
14769 case Intrinsic::x86_avx2_psllv_d_256:
14770 case Intrinsic::x86_avx2_psllv_q_256:
14771 case Intrinsic::x86_avx2_psrlv_d:
14772 case Intrinsic::x86_avx2_psrlv_q:
14773 case Intrinsic::x86_avx2_psrlv_d_256:
14774 case Intrinsic::x86_avx2_psrlv_q_256:
14775 case Intrinsic::x86_avx2_psrav_d:
14776 case Intrinsic::x86_avx2_psrav_d_256: {
14779 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14780 case Intrinsic::x86_avx2_psllv_d:
14781 case Intrinsic::x86_avx2_psllv_q:
14782 case Intrinsic::x86_avx2_psllv_d_256:
14783 case Intrinsic::x86_avx2_psllv_q_256:
14786 case Intrinsic::x86_avx2_psrlv_d:
14787 case Intrinsic::x86_avx2_psrlv_q:
14788 case Intrinsic::x86_avx2_psrlv_d_256:
14789 case Intrinsic::x86_avx2_psrlv_q_256:
14792 case Intrinsic::x86_avx2_psrav_d:
14793 case Intrinsic::x86_avx2_psrav_d_256:
14797 return DAG.getNode(Opcode, dl, Op.getValueType(),
14798 Op.getOperand(1), Op.getOperand(2));
14801 case Intrinsic::x86_sse2_packssdw_128:
14802 case Intrinsic::x86_sse2_packsswb_128:
14803 case Intrinsic::x86_avx2_packssdw:
14804 case Intrinsic::x86_avx2_packsswb:
14805 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14806 Op.getOperand(1), Op.getOperand(2));
14808 case Intrinsic::x86_sse2_packuswb_128:
14809 case Intrinsic::x86_sse41_packusdw:
14810 case Intrinsic::x86_avx2_packuswb:
14811 case Intrinsic::x86_avx2_packusdw:
14812 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14813 Op.getOperand(1), Op.getOperand(2));
14815 case Intrinsic::x86_ssse3_pshuf_b_128:
14816 case Intrinsic::x86_avx2_pshuf_b:
14817 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14818 Op.getOperand(1), Op.getOperand(2));
14820 case Intrinsic::x86_sse2_pshuf_d:
14821 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14822 Op.getOperand(1), Op.getOperand(2));
14824 case Intrinsic::x86_sse2_pshufl_w:
14825 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14826 Op.getOperand(1), Op.getOperand(2));
14828 case Intrinsic::x86_sse2_pshufh_w:
14829 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14830 Op.getOperand(1), Op.getOperand(2));
14832 case Intrinsic::x86_ssse3_psign_b_128:
14833 case Intrinsic::x86_ssse3_psign_w_128:
14834 case Intrinsic::x86_ssse3_psign_d_128:
14835 case Intrinsic::x86_avx2_psign_b:
14836 case Intrinsic::x86_avx2_psign_w:
14837 case Intrinsic::x86_avx2_psign_d:
14838 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14839 Op.getOperand(1), Op.getOperand(2));
14841 case Intrinsic::x86_sse41_insertps:
14842 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14843 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14845 case Intrinsic::x86_avx_vperm2f128_ps_256:
14846 case Intrinsic::x86_avx_vperm2f128_pd_256:
14847 case Intrinsic::x86_avx_vperm2f128_si_256:
14848 case Intrinsic::x86_avx2_vperm2i128:
14849 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14850 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14852 case Intrinsic::x86_avx2_permd:
14853 case Intrinsic::x86_avx2_permps:
14854 // Operands intentionally swapped. Mask is last operand to intrinsic,
14855 // but second operand for node/instruction.
14856 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14857 Op.getOperand(2), Op.getOperand(1));
14859 case Intrinsic::x86_sse_sqrt_ps:
14860 case Intrinsic::x86_sse2_sqrt_pd:
14861 case Intrinsic::x86_avx_sqrt_ps_256:
14862 case Intrinsic::x86_avx_sqrt_pd_256:
14863 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14865 case Intrinsic::x86_avx512_mask_valign_q_512:
14866 case Intrinsic::x86_avx512_mask_valign_d_512:
14867 // Vector source operands are swapped.
14868 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14869 Op.getValueType(), Op.getOperand(2),
14872 Op.getOperand(5), Op.getOperand(4), DAG);
14874 // ptest and testp intrinsics. The intrinsic these come from are designed to
14875 // return an integer value, not just an instruction so lower it to the ptest
14876 // or testp pattern and a setcc for the result.
14877 case Intrinsic::x86_sse41_ptestz:
14878 case Intrinsic::x86_sse41_ptestc:
14879 case Intrinsic::x86_sse41_ptestnzc:
14880 case Intrinsic::x86_avx_ptestz_256:
14881 case Intrinsic::x86_avx_ptestc_256:
14882 case Intrinsic::x86_avx_ptestnzc_256:
14883 case Intrinsic::x86_avx_vtestz_ps:
14884 case Intrinsic::x86_avx_vtestc_ps:
14885 case Intrinsic::x86_avx_vtestnzc_ps:
14886 case Intrinsic::x86_avx_vtestz_pd:
14887 case Intrinsic::x86_avx_vtestc_pd:
14888 case Intrinsic::x86_avx_vtestnzc_pd:
14889 case Intrinsic::x86_avx_vtestz_ps_256:
14890 case Intrinsic::x86_avx_vtestc_ps_256:
14891 case Intrinsic::x86_avx_vtestnzc_ps_256:
14892 case Intrinsic::x86_avx_vtestz_pd_256:
14893 case Intrinsic::x86_avx_vtestc_pd_256:
14894 case Intrinsic::x86_avx_vtestnzc_pd_256: {
14895 bool IsTestPacked = false;
14898 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14899 case Intrinsic::x86_avx_vtestz_ps:
14900 case Intrinsic::x86_avx_vtestz_pd:
14901 case Intrinsic::x86_avx_vtestz_ps_256:
14902 case Intrinsic::x86_avx_vtestz_pd_256:
14903 IsTestPacked = true; // Fallthrough
14904 case Intrinsic::x86_sse41_ptestz:
14905 case Intrinsic::x86_avx_ptestz_256:
14907 X86CC = X86::COND_E;
14909 case Intrinsic::x86_avx_vtestc_ps:
14910 case Intrinsic::x86_avx_vtestc_pd:
14911 case Intrinsic::x86_avx_vtestc_ps_256:
14912 case Intrinsic::x86_avx_vtestc_pd_256:
14913 IsTestPacked = true; // Fallthrough
14914 case Intrinsic::x86_sse41_ptestc:
14915 case Intrinsic::x86_avx_ptestc_256:
14917 X86CC = X86::COND_B;
14919 case Intrinsic::x86_avx_vtestnzc_ps:
14920 case Intrinsic::x86_avx_vtestnzc_pd:
14921 case Intrinsic::x86_avx_vtestnzc_ps_256:
14922 case Intrinsic::x86_avx_vtestnzc_pd_256:
14923 IsTestPacked = true; // Fallthrough
14924 case Intrinsic::x86_sse41_ptestnzc:
14925 case Intrinsic::x86_avx_ptestnzc_256:
14927 X86CC = X86::COND_A;
14931 SDValue LHS = Op.getOperand(1);
14932 SDValue RHS = Op.getOperand(2);
14933 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14934 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14935 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14936 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14937 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14939 case Intrinsic::x86_avx512_kortestz_w:
14940 case Intrinsic::x86_avx512_kortestc_w: {
14941 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14942 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14943 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14944 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14945 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14946 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14947 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14950 // SSE/AVX shift intrinsics
14951 case Intrinsic::x86_sse2_psll_w:
14952 case Intrinsic::x86_sse2_psll_d:
14953 case Intrinsic::x86_sse2_psll_q:
14954 case Intrinsic::x86_avx2_psll_w:
14955 case Intrinsic::x86_avx2_psll_d:
14956 case Intrinsic::x86_avx2_psll_q:
14957 case Intrinsic::x86_sse2_psrl_w:
14958 case Intrinsic::x86_sse2_psrl_d:
14959 case Intrinsic::x86_sse2_psrl_q:
14960 case Intrinsic::x86_avx2_psrl_w:
14961 case Intrinsic::x86_avx2_psrl_d:
14962 case Intrinsic::x86_avx2_psrl_q:
14963 case Intrinsic::x86_sse2_psra_w:
14964 case Intrinsic::x86_sse2_psra_d:
14965 case Intrinsic::x86_avx2_psra_w:
14966 case Intrinsic::x86_avx2_psra_d: {
14969 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14970 case Intrinsic::x86_sse2_psll_w:
14971 case Intrinsic::x86_sse2_psll_d:
14972 case Intrinsic::x86_sse2_psll_q:
14973 case Intrinsic::x86_avx2_psll_w:
14974 case Intrinsic::x86_avx2_psll_d:
14975 case Intrinsic::x86_avx2_psll_q:
14976 Opcode = X86ISD::VSHL;
14978 case Intrinsic::x86_sse2_psrl_w:
14979 case Intrinsic::x86_sse2_psrl_d:
14980 case Intrinsic::x86_sse2_psrl_q:
14981 case Intrinsic::x86_avx2_psrl_w:
14982 case Intrinsic::x86_avx2_psrl_d:
14983 case Intrinsic::x86_avx2_psrl_q:
14984 Opcode = X86ISD::VSRL;
14986 case Intrinsic::x86_sse2_psra_w:
14987 case Intrinsic::x86_sse2_psra_d:
14988 case Intrinsic::x86_avx2_psra_w:
14989 case Intrinsic::x86_avx2_psra_d:
14990 Opcode = X86ISD::VSRA;
14993 return DAG.getNode(Opcode, dl, Op.getValueType(),
14994 Op.getOperand(1), Op.getOperand(2));
14997 // SSE/AVX immediate shift intrinsics
14998 case Intrinsic::x86_sse2_pslli_w:
14999 case Intrinsic::x86_sse2_pslli_d:
15000 case Intrinsic::x86_sse2_pslli_q:
15001 case Intrinsic::x86_avx2_pslli_w:
15002 case Intrinsic::x86_avx2_pslli_d:
15003 case Intrinsic::x86_avx2_pslli_q:
15004 case Intrinsic::x86_sse2_psrli_w:
15005 case Intrinsic::x86_sse2_psrli_d:
15006 case Intrinsic::x86_sse2_psrli_q:
15007 case Intrinsic::x86_avx2_psrli_w:
15008 case Intrinsic::x86_avx2_psrli_d:
15009 case Intrinsic::x86_avx2_psrli_q:
15010 case Intrinsic::x86_sse2_psrai_w:
15011 case Intrinsic::x86_sse2_psrai_d:
15012 case Intrinsic::x86_avx2_psrai_w:
15013 case Intrinsic::x86_avx2_psrai_d: {
15016 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15017 case Intrinsic::x86_sse2_pslli_w:
15018 case Intrinsic::x86_sse2_pslli_d:
15019 case Intrinsic::x86_sse2_pslli_q:
15020 case Intrinsic::x86_avx2_pslli_w:
15021 case Intrinsic::x86_avx2_pslli_d:
15022 case Intrinsic::x86_avx2_pslli_q:
15023 Opcode = X86ISD::VSHLI;
15025 case Intrinsic::x86_sse2_psrli_w:
15026 case Intrinsic::x86_sse2_psrli_d:
15027 case Intrinsic::x86_sse2_psrli_q:
15028 case Intrinsic::x86_avx2_psrli_w:
15029 case Intrinsic::x86_avx2_psrli_d:
15030 case Intrinsic::x86_avx2_psrli_q:
15031 Opcode = X86ISD::VSRLI;
15033 case Intrinsic::x86_sse2_psrai_w:
15034 case Intrinsic::x86_sse2_psrai_d:
15035 case Intrinsic::x86_avx2_psrai_w:
15036 case Intrinsic::x86_avx2_psrai_d:
15037 Opcode = X86ISD::VSRAI;
15040 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
15041 Op.getOperand(1), Op.getOperand(2), DAG);
15044 case Intrinsic::x86_sse42_pcmpistria128:
15045 case Intrinsic::x86_sse42_pcmpestria128:
15046 case Intrinsic::x86_sse42_pcmpistric128:
15047 case Intrinsic::x86_sse42_pcmpestric128:
15048 case Intrinsic::x86_sse42_pcmpistrio128:
15049 case Intrinsic::x86_sse42_pcmpestrio128:
15050 case Intrinsic::x86_sse42_pcmpistris128:
15051 case Intrinsic::x86_sse42_pcmpestris128:
15052 case Intrinsic::x86_sse42_pcmpistriz128:
15053 case Intrinsic::x86_sse42_pcmpestriz128: {
15057 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
15058 case Intrinsic::x86_sse42_pcmpistria128:
15059 Opcode = X86ISD::PCMPISTRI;
15060 X86CC = X86::COND_A;
15062 case Intrinsic::x86_sse42_pcmpestria128:
15063 Opcode = X86ISD::PCMPESTRI;
15064 X86CC = X86::COND_A;
15066 case Intrinsic::x86_sse42_pcmpistric128:
15067 Opcode = X86ISD::PCMPISTRI;
15068 X86CC = X86::COND_B;
15070 case Intrinsic::x86_sse42_pcmpestric128:
15071 Opcode = X86ISD::PCMPESTRI;
15072 X86CC = X86::COND_B;
15074 case Intrinsic::x86_sse42_pcmpistrio128:
15075 Opcode = X86ISD::PCMPISTRI;
15076 X86CC = X86::COND_O;
15078 case Intrinsic::x86_sse42_pcmpestrio128:
15079 Opcode = X86ISD::PCMPESTRI;
15080 X86CC = X86::COND_O;
15082 case Intrinsic::x86_sse42_pcmpistris128:
15083 Opcode = X86ISD::PCMPISTRI;
15084 X86CC = X86::COND_S;
15086 case Intrinsic::x86_sse42_pcmpestris128:
15087 Opcode = X86ISD::PCMPESTRI;
15088 X86CC = X86::COND_S;
15090 case Intrinsic::x86_sse42_pcmpistriz128:
15091 Opcode = X86ISD::PCMPISTRI;
15092 X86CC = X86::COND_E;
15094 case Intrinsic::x86_sse42_pcmpestriz128:
15095 Opcode = X86ISD::PCMPESTRI;
15096 X86CC = X86::COND_E;
15099 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15100 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15101 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15102 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15103 DAG.getConstant(X86CC, MVT::i8),
15104 SDValue(PCMP.getNode(), 1));
15105 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15108 case Intrinsic::x86_sse42_pcmpistri128:
15109 case Intrinsic::x86_sse42_pcmpestri128: {
15111 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15112 Opcode = X86ISD::PCMPISTRI;
15114 Opcode = X86ISD::PCMPESTRI;
15116 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15117 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15118 return DAG.getNode(Opcode, dl, VTs, NewOps);
15121 case Intrinsic::x86_fma_mask_vfmadd_ps_512:
15122 case Intrinsic::x86_fma_mask_vfmadd_pd_512:
15123 case Intrinsic::x86_fma_mask_vfmsub_ps_512:
15124 case Intrinsic::x86_fma_mask_vfmsub_pd_512:
15125 case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
15126 case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
15127 case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
15128 case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
15129 case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
15130 case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
15131 case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
15132 case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
15133 auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
15134 if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
15135 return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
15136 dl, Op.getValueType(),
15140 Op.getOperand(4), Op.getOperand(1), DAG);
15145 case Intrinsic::x86_fma_vfmadd_ps:
15146 case Intrinsic::x86_fma_vfmadd_pd:
15147 case Intrinsic::x86_fma_vfmsub_ps:
15148 case Intrinsic::x86_fma_vfmsub_pd:
15149 case Intrinsic::x86_fma_vfnmadd_ps:
15150 case Intrinsic::x86_fma_vfnmadd_pd:
15151 case Intrinsic::x86_fma_vfnmsub_ps:
15152 case Intrinsic::x86_fma_vfnmsub_pd:
15153 case Intrinsic::x86_fma_vfmaddsub_ps:
15154 case Intrinsic::x86_fma_vfmaddsub_pd:
15155 case Intrinsic::x86_fma_vfmsubadd_ps:
15156 case Intrinsic::x86_fma_vfmsubadd_pd:
15157 case Intrinsic::x86_fma_vfmadd_ps_256:
15158 case Intrinsic::x86_fma_vfmadd_pd_256:
15159 case Intrinsic::x86_fma_vfmsub_ps_256:
15160 case Intrinsic::x86_fma_vfmsub_pd_256:
15161 case Intrinsic::x86_fma_vfnmadd_ps_256:
15162 case Intrinsic::x86_fma_vfnmadd_pd_256:
15163 case Intrinsic::x86_fma_vfnmsub_ps_256:
15164 case Intrinsic::x86_fma_vfnmsub_pd_256:
15165 case Intrinsic::x86_fma_vfmaddsub_ps_256:
15166 case Intrinsic::x86_fma_vfmaddsub_pd_256:
15167 case Intrinsic::x86_fma_vfmsubadd_ps_256:
15168 case Intrinsic::x86_fma_vfmsubadd_pd_256:
15169 return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
15170 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
15174 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15175 SDValue Src, SDValue Mask, SDValue Base,
15176 SDValue Index, SDValue ScaleOp, SDValue Chain,
15177 const X86Subtarget * Subtarget) {
15179 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15180 assert(C && "Invalid scale type");
15181 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15182 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15183 Index.getSimpleValueType().getVectorNumElements());
15185 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15187 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15189 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15190 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15191 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15192 SDValue Segment = DAG.getRegister(0, MVT::i32);
15193 if (Src.getOpcode() == ISD::UNDEF)
15194 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15195 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15196 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15197 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15198 return DAG.getMergeValues(RetOps, dl);
15201 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15202 SDValue Src, SDValue Mask, SDValue Base,
15203 SDValue Index, SDValue ScaleOp, SDValue Chain) {
15205 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15206 assert(C && "Invalid scale type");
15207 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15208 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15209 SDValue Segment = DAG.getRegister(0, MVT::i32);
15210 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15211 Index.getSimpleValueType().getVectorNumElements());
15213 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15215 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15217 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15218 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15219 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15220 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15221 return SDValue(Res, 1);
15224 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15225 SDValue Mask, SDValue Base, SDValue Index,
15226 SDValue ScaleOp, SDValue Chain) {
15228 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15229 assert(C && "Invalid scale type");
15230 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15231 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15232 SDValue Segment = DAG.getRegister(0, MVT::i32);
15234 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15236 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15238 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15240 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15241 //SDVTList VTs = DAG.getVTList(MVT::Other);
15242 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15243 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15244 return SDValue(Res, 0);
15247 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15248 // read performance monitor counters (x86_rdpmc).
15249 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15250 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15251 SmallVectorImpl<SDValue> &Results) {
15252 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15253 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15256 // The ECX register is used to select the index of the performance counter
15258 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15260 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15262 // Reads the content of a 64-bit performance counter and returns it in the
15263 // registers EDX:EAX.
15264 if (Subtarget->is64Bit()) {
15265 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15266 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15269 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15270 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15273 Chain = HI.getValue(1);
15275 if (Subtarget->is64Bit()) {
15276 // The EAX register is loaded with the low-order 32 bits. The EDX register
15277 // is loaded with the supported high-order bits of the counter.
15278 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15279 DAG.getConstant(32, MVT::i8));
15280 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15281 Results.push_back(Chain);
15285 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15286 SDValue Ops[] = { LO, HI };
15287 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15288 Results.push_back(Pair);
15289 Results.push_back(Chain);
15292 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15293 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15294 // also used to custom lower READCYCLECOUNTER nodes.
15295 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15296 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15297 SmallVectorImpl<SDValue> &Results) {
15298 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15299 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15302 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15303 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15304 // and the EAX register is loaded with the low-order 32 bits.
15305 if (Subtarget->is64Bit()) {
15306 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15307 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15310 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15311 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15314 SDValue Chain = HI.getValue(1);
15316 if (Opcode == X86ISD::RDTSCP_DAG) {
15317 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15319 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15320 // the ECX register. Add 'ecx' explicitly to the chain.
15321 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15323 // Explicitly store the content of ECX at the location passed in input
15324 // to the 'rdtscp' intrinsic.
15325 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15326 MachinePointerInfo(), false, false, 0);
15329 if (Subtarget->is64Bit()) {
15330 // The EDX register is loaded with the high-order 32 bits of the MSR, and
15331 // the EAX register is loaded with the low-order 32 bits.
15332 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15333 DAG.getConstant(32, MVT::i8));
15334 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15335 Results.push_back(Chain);
15339 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15340 SDValue Ops[] = { LO, HI };
15341 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15342 Results.push_back(Pair);
15343 Results.push_back(Chain);
15346 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15347 SelectionDAG &DAG) {
15348 SmallVector<SDValue, 2> Results;
15350 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15352 return DAG.getMergeValues(Results, DL);
15355 enum IntrinsicType {
15356 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST, ADX
15359 struct IntrinsicData {
15360 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
15361 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
15362 IntrinsicType Type;
15367 std::map < unsigned, IntrinsicData> IntrMap;
15368 static void InitIntinsicsMap() {
15369 static bool Initialized = false;
15372 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
15373 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
15374 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
15375 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
15376 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
15377 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
15378 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
15379 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
15380 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
15381 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
15382 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
15383 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
15384 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
15385 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
15386 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
15387 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
15388 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
15389 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
15391 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
15392 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
15393 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
15394 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
15395 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
15396 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
15397 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
15398 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
15399 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
15400 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
15401 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
15402 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
15403 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
15404 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
15405 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
15406 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
15408 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
15409 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
15410 X86::VGATHERPF1QPSm)));
15411 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
15412 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
15413 X86::VGATHERPF1QPDm)));
15414 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
15415 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
15416 X86::VGATHERPF1DPDm)));
15417 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
15418 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
15419 X86::VGATHERPF1DPSm)));
15420 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
15421 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
15422 X86::VSCATTERPF1QPSm)));
15423 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
15424 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
15425 X86::VSCATTERPF1QPDm)));
15426 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
15427 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
15428 X86::VSCATTERPF1DPDm)));
15429 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
15430 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
15431 X86::VSCATTERPF1DPSm)));
15432 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
15433 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15434 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
15435 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15436 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
15437 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
15438 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
15439 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15440 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
15441 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15442 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
15443 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
15444 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
15445 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
15446 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
15447 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
15448 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
15449 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
15450 IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
15451 IntrinsicData(RDPMC, X86ISD::RDPMC_DAG, 0)));
15452 IntrMap.insert(std::make_pair(Intrinsic::x86_addcarryx_u32,
15453 IntrinsicData(ADX, X86ISD::ADC, 0)));
15454 IntrMap.insert(std::make_pair(Intrinsic::x86_addcarryx_u64,
15455 IntrinsicData(ADX, X86ISD::ADC, 0)));
15456 IntrMap.insert(std::make_pair(Intrinsic::x86_addcarry_u32,
15457 IntrinsicData(ADX, X86ISD::ADC, 0)));
15458 IntrMap.insert(std::make_pair(Intrinsic::x86_addcarry_u64,
15459 IntrinsicData(ADX, X86ISD::ADC, 0)));
15460 IntrMap.insert(std::make_pair(Intrinsic::x86_subborrow_u32,
15461 IntrinsicData(ADX, X86ISD::SBB, 0)));
15462 IntrMap.insert(std::make_pair(Intrinsic::x86_subborrow_u64,
15463 IntrinsicData(ADX, X86ISD::SBB, 0)));
15464 Initialized = true;
15467 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15468 SelectionDAG &DAG) {
15469 InitIntinsicsMap();
15470 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15471 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
15472 if (itr == IntrMap.end())
15476 IntrinsicData Intr = itr->second;
15477 switch(Intr.Type) {
15480 // Emit the node with the right value type.
15481 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15482 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
15484 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15485 // Otherwise return the value from Rand, which is always 0, casted to i32.
15486 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15487 DAG.getConstant(1, Op->getValueType(1)),
15488 DAG.getConstant(X86::COND_B, MVT::i32),
15489 SDValue(Result.getNode(), 1) };
15490 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15491 DAG.getVTList(Op->getValueType(1), MVT::Glue),
15494 // Return { result, isValid, chain }.
15495 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15496 SDValue(Result.getNode(), 2));
15499 //gather(v1, mask, index, base, scale);
15500 SDValue Chain = Op.getOperand(0);
15501 SDValue Src = Op.getOperand(2);
15502 SDValue Base = Op.getOperand(3);
15503 SDValue Index = Op.getOperand(4);
15504 SDValue Mask = Op.getOperand(5);
15505 SDValue Scale = Op.getOperand(6);
15506 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15510 //scatter(base, mask, index, v1, scale);
15511 SDValue Chain = Op.getOperand(0);
15512 SDValue Base = Op.getOperand(2);
15513 SDValue Mask = Op.getOperand(3);
15514 SDValue Index = Op.getOperand(4);
15515 SDValue Src = Op.getOperand(5);
15516 SDValue Scale = Op.getOperand(6);
15517 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15520 SDValue Hint = Op.getOperand(6);
15522 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15523 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15524 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15525 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
15526 SDValue Chain = Op.getOperand(0);
15527 SDValue Mask = Op.getOperand(2);
15528 SDValue Index = Op.getOperand(3);
15529 SDValue Base = Op.getOperand(4);
15530 SDValue Scale = Op.getOperand(5);
15531 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15533 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15535 SmallVector<SDValue, 2> Results;
15536 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
15537 return DAG.getMergeValues(Results, dl);
15539 // Read Performance Monitoring Counters.
15541 SmallVector<SDValue, 2> Results;
15542 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15543 return DAG.getMergeValues(Results, dl);
15545 // XTEST intrinsics.
15547 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15548 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
15549 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15550 DAG.getConstant(X86::COND_NE, MVT::i8),
15552 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15553 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15554 Ret, SDValue(InTrans.getNode(), 1));
15558 SmallVector<SDValue, 2> Results;
15559 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15560 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15561 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15562 DAG.getConstant(-1, MVT::i8));
15563 SDValue Res = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(3),
15564 Op.getOperand(4), GenCF.getValue(1));
15565 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15566 Op.getOperand(5), MachinePointerInfo(),
15568 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15569 DAG.getConstant(X86::COND_B, MVT::i8),
15571 Results.push_back(SetCC);
15572 Results.push_back(Store);
15573 return DAG.getMergeValues(Results, dl);
15576 llvm_unreachable("Unknown Intrinsic Type");
15579 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15580 SelectionDAG &DAG) const {
15581 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15582 MFI->setReturnAddressIsTaken(true);
15584 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15587 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15589 EVT PtrVT = getPointerTy();
15592 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15593 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15594 DAG.getSubtarget().getRegisterInfo());
15595 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15596 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15597 DAG.getNode(ISD::ADD, dl, PtrVT,
15598 FrameAddr, Offset),
15599 MachinePointerInfo(), false, false, false, 0);
15602 // Just load the return address.
15603 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15604 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15605 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15608 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15609 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15610 MFI->setFrameAddressIsTaken(true);
15612 EVT VT = Op.getValueType();
15613 SDLoc dl(Op); // FIXME probably not meaningful
15614 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15615 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15616 DAG.getSubtarget().getRegisterInfo());
15617 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15618 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15619 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15620 "Invalid Frame Register!");
15621 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15623 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15624 MachinePointerInfo(),
15625 false, false, false, 0);
15629 // FIXME? Maybe this could be a TableGen attribute on some registers and
15630 // this table could be generated automatically from RegInfo.
15631 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15633 unsigned Reg = StringSwitch<unsigned>(RegName)
15634 .Case("esp", X86::ESP)
15635 .Case("rsp", X86::RSP)
15639 report_fatal_error("Invalid register name global variable");
15642 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15643 SelectionDAG &DAG) const {
15644 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15645 DAG.getSubtarget().getRegisterInfo());
15646 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15649 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15650 SDValue Chain = Op.getOperand(0);
15651 SDValue Offset = Op.getOperand(1);
15652 SDValue Handler = Op.getOperand(2);
15655 EVT PtrVT = getPointerTy();
15656 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15657 DAG.getSubtarget().getRegisterInfo());
15658 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15659 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15660 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15661 "Invalid Frame Register!");
15662 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15663 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15665 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15666 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15667 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15668 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15670 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15672 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15673 DAG.getRegister(StoreAddrReg, PtrVT));
15676 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15677 SelectionDAG &DAG) const {
15679 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15680 DAG.getVTList(MVT::i32, MVT::Other),
15681 Op.getOperand(0), Op.getOperand(1));
15684 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15685 SelectionDAG &DAG) const {
15687 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15688 Op.getOperand(0), Op.getOperand(1));
15691 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15692 return Op.getOperand(0);
15695 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15696 SelectionDAG &DAG) const {
15697 SDValue Root = Op.getOperand(0);
15698 SDValue Trmp = Op.getOperand(1); // trampoline
15699 SDValue FPtr = Op.getOperand(2); // nested function
15700 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15703 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15704 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15706 if (Subtarget->is64Bit()) {
15707 SDValue OutChains[6];
15709 // Large code-model.
15710 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15711 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15713 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15714 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15716 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15718 // Load the pointer to the nested function into R11.
15719 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15720 SDValue Addr = Trmp;
15721 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15722 Addr, MachinePointerInfo(TrmpAddr),
15725 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15726 DAG.getConstant(2, MVT::i64));
15727 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15728 MachinePointerInfo(TrmpAddr, 2),
15731 // Load the 'nest' parameter value into R10.
15732 // R10 is specified in X86CallingConv.td
15733 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15734 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15735 DAG.getConstant(10, MVT::i64));
15736 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15737 Addr, MachinePointerInfo(TrmpAddr, 10),
15740 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15741 DAG.getConstant(12, MVT::i64));
15742 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15743 MachinePointerInfo(TrmpAddr, 12),
15746 // Jump to the nested function.
15747 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15748 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15749 DAG.getConstant(20, MVT::i64));
15750 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15751 Addr, MachinePointerInfo(TrmpAddr, 20),
15754 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15755 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15756 DAG.getConstant(22, MVT::i64));
15757 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15758 MachinePointerInfo(TrmpAddr, 22),
15761 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15763 const Function *Func =
15764 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15765 CallingConv::ID CC = Func->getCallingConv();
15770 llvm_unreachable("Unsupported calling convention");
15771 case CallingConv::C:
15772 case CallingConv::X86_StdCall: {
15773 // Pass 'nest' parameter in ECX.
15774 // Must be kept in sync with X86CallingConv.td
15775 NestReg = X86::ECX;
15777 // Check that ECX wasn't needed by an 'inreg' parameter.
15778 FunctionType *FTy = Func->getFunctionType();
15779 const AttributeSet &Attrs = Func->getAttributes();
15781 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15782 unsigned InRegCount = 0;
15785 for (FunctionType::param_iterator I = FTy->param_begin(),
15786 E = FTy->param_end(); I != E; ++I, ++Idx)
15787 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15788 // FIXME: should only count parameters that are lowered to integers.
15789 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15791 if (InRegCount > 2) {
15792 report_fatal_error("Nest register in use - reduce number of inreg"
15798 case CallingConv::X86_FastCall:
15799 case CallingConv::X86_ThisCall:
15800 case CallingConv::Fast:
15801 // Pass 'nest' parameter in EAX.
15802 // Must be kept in sync with X86CallingConv.td
15803 NestReg = X86::EAX;
15807 SDValue OutChains[4];
15808 SDValue Addr, Disp;
15810 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15811 DAG.getConstant(10, MVT::i32));
15812 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15814 // This is storing the opcode for MOV32ri.
15815 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15816 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15817 OutChains[0] = DAG.getStore(Root, dl,
15818 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15819 Trmp, MachinePointerInfo(TrmpAddr),
15822 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15823 DAG.getConstant(1, MVT::i32));
15824 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15825 MachinePointerInfo(TrmpAddr, 1),
15828 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15829 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15830 DAG.getConstant(5, MVT::i32));
15831 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15832 MachinePointerInfo(TrmpAddr, 5),
15835 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15836 DAG.getConstant(6, MVT::i32));
15837 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15838 MachinePointerInfo(TrmpAddr, 6),
15841 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15845 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15846 SelectionDAG &DAG) const {
15848 The rounding mode is in bits 11:10 of FPSR, and has the following
15850 00 Round to nearest
15855 FLT_ROUNDS, on the other hand, expects the following:
15862 To perform the conversion, we do:
15863 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15866 MachineFunction &MF = DAG.getMachineFunction();
15867 const TargetMachine &TM = MF.getTarget();
15868 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15869 unsigned StackAlignment = TFI.getStackAlignment();
15870 MVT VT = Op.getSimpleValueType();
15873 // Save FP Control Word to stack slot
15874 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15875 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15877 MachineMemOperand *MMO =
15878 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15879 MachineMemOperand::MOStore, 2, 2);
15881 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15882 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15883 DAG.getVTList(MVT::Other),
15884 Ops, MVT::i16, MMO);
15886 // Load FP Control Word from stack slot
15887 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15888 MachinePointerInfo(), false, false, false, 0);
15890 // Transform as necessary
15892 DAG.getNode(ISD::SRL, DL, MVT::i16,
15893 DAG.getNode(ISD::AND, DL, MVT::i16,
15894 CWD, DAG.getConstant(0x800, MVT::i16)),
15895 DAG.getConstant(11, MVT::i8));
15897 DAG.getNode(ISD::SRL, DL, MVT::i16,
15898 DAG.getNode(ISD::AND, DL, MVT::i16,
15899 CWD, DAG.getConstant(0x400, MVT::i16)),
15900 DAG.getConstant(9, MVT::i8));
15903 DAG.getNode(ISD::AND, DL, MVT::i16,
15904 DAG.getNode(ISD::ADD, DL, MVT::i16,
15905 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15906 DAG.getConstant(1, MVT::i16)),
15907 DAG.getConstant(3, MVT::i16));
15909 return DAG.getNode((VT.getSizeInBits() < 16 ?
15910 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15913 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15914 MVT VT = Op.getSimpleValueType();
15916 unsigned NumBits = VT.getSizeInBits();
15919 Op = Op.getOperand(0);
15920 if (VT == MVT::i8) {
15921 // Zero extend to i32 since there is not an i8 bsr.
15923 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15926 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15927 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15928 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15930 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15933 DAG.getConstant(NumBits+NumBits-1, OpVT),
15934 DAG.getConstant(X86::COND_E, MVT::i8),
15937 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15939 // Finally xor with NumBits-1.
15940 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15943 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15947 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15948 MVT VT = Op.getSimpleValueType();
15950 unsigned NumBits = VT.getSizeInBits();
15953 Op = Op.getOperand(0);
15954 if (VT == MVT::i8) {
15955 // Zero extend to i32 since there is not an i8 bsr.
15957 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15960 // Issue a bsr (scan bits in reverse).
15961 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15962 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15964 // And xor with NumBits-1.
15965 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15968 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15972 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15973 MVT VT = Op.getSimpleValueType();
15974 unsigned NumBits = VT.getSizeInBits();
15976 Op = Op.getOperand(0);
15978 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15979 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15980 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15982 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15985 DAG.getConstant(NumBits, VT),
15986 DAG.getConstant(X86::COND_E, MVT::i8),
15989 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15992 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15993 // ones, and then concatenate the result back.
15994 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15995 MVT VT = Op.getSimpleValueType();
15997 assert(VT.is256BitVector() && VT.isInteger() &&
15998 "Unsupported value type for operation");
16000 unsigned NumElems = VT.getVectorNumElements();
16003 // Extract the LHS vectors
16004 SDValue LHS = Op.getOperand(0);
16005 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16006 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16008 // Extract the RHS vectors
16009 SDValue RHS = Op.getOperand(1);
16010 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16011 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16013 MVT EltVT = VT.getVectorElementType();
16014 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16016 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16017 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16018 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16021 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16022 assert(Op.getSimpleValueType().is256BitVector() &&
16023 Op.getSimpleValueType().isInteger() &&
16024 "Only handle AVX 256-bit vector integer operation");
16025 return Lower256IntArith(Op, DAG);
16028 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16029 assert(Op.getSimpleValueType().is256BitVector() &&
16030 Op.getSimpleValueType().isInteger() &&
16031 "Only handle AVX 256-bit vector integer operation");
16032 return Lower256IntArith(Op, DAG);
16035 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16036 SelectionDAG &DAG) {
16038 MVT VT = Op.getSimpleValueType();
16040 // Decompose 256-bit ops into smaller 128-bit ops.
16041 if (VT.is256BitVector() && !Subtarget->hasInt256())
16042 return Lower256IntArith(Op, DAG);
16044 SDValue A = Op.getOperand(0);
16045 SDValue B = Op.getOperand(1);
16047 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16048 if (VT == MVT::v4i32) {
16049 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16050 "Should not custom lower when pmuldq is available!");
16052 // Extract the odd parts.
16053 static const int UnpackMask[] = { 1, -1, 3, -1 };
16054 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16055 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16057 // Multiply the even parts.
16058 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16059 // Now multiply odd parts.
16060 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16062 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16063 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16065 // Merge the two vectors back together with a shuffle. This expands into 2
16067 static const int ShufMask[] = { 0, 4, 2, 6 };
16068 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16071 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16072 "Only know how to lower V2I64/V4I64/V8I64 multiply");
16074 // Ahi = psrlqi(a, 32);
16075 // Bhi = psrlqi(b, 32);
16077 // AloBlo = pmuludq(a, b);
16078 // AloBhi = pmuludq(a, Bhi);
16079 // AhiBlo = pmuludq(Ahi, b);
16081 // AloBhi = psllqi(AloBhi, 32);
16082 // AhiBlo = psllqi(AhiBlo, 32);
16083 // return AloBlo + AloBhi + AhiBlo;
16085 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16086 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16088 // Bit cast to 32-bit vectors for MULUDQ
16089 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16090 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16091 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16092 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16093 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16094 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16096 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16097 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16098 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16100 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16101 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16103 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16104 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16107 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16108 assert(Subtarget->isTargetWin64() && "Unexpected target");
16109 EVT VT = Op.getValueType();
16110 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16111 "Unexpected return type for lowering");
16115 switch (Op->getOpcode()) {
16116 default: llvm_unreachable("Unexpected request for libcall!");
16117 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
16118 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
16119 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
16120 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
16121 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
16122 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16126 SDValue InChain = DAG.getEntryNode();
16128 TargetLowering::ArgListTy Args;
16129 TargetLowering::ArgListEntry Entry;
16130 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16131 EVT ArgVT = Op->getOperand(i).getValueType();
16132 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16133 "Unexpected argument type for lowering");
16134 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16135 Entry.Node = StackPtr;
16136 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16138 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16139 Entry.Ty = PointerType::get(ArgTy,0);
16140 Entry.isSExt = false;
16141 Entry.isZExt = false;
16142 Args.push_back(Entry);
16145 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16148 TargetLowering::CallLoweringInfo CLI(DAG);
16149 CLI.setDebugLoc(dl).setChain(InChain)
16150 .setCallee(getLibcallCallingConv(LC),
16151 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16152 Callee, std::move(Args), 0)
16153 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16155 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16156 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16159 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16160 SelectionDAG &DAG) {
16161 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16162 EVT VT = Op0.getValueType();
16165 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16166 (VT == MVT::v8i32 && Subtarget->hasInt256()));
16168 // PMULxD operations multiply each even value (starting at 0) of LHS with
16169 // the related value of RHS and produce a widen result.
16170 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16171 // => <2 x i64> <ae|cg>
16173 // In other word, to have all the results, we need to perform two PMULxD:
16174 // 1. one with the even values.
16175 // 2. one with the odd values.
16176 // To achieve #2, with need to place the odd values at an even position.
16178 // Place the odd value at an even position (basically, shift all values 1
16179 // step to the left):
16180 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16181 // <a|b|c|d> => <b|undef|d|undef>
16182 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16183 // <e|f|g|h> => <f|undef|h|undef>
16184 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16186 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16188 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16189 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16191 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16192 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16193 // => <2 x i64> <ae|cg>
16194 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16195 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16196 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16197 // => <2 x i64> <bf|dh>
16198 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16199 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16201 // Shuffle it back into the right order.
16202 SDValue Highs, Lows;
16203 if (VT == MVT::v8i32) {
16204 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16205 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16206 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16207 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16209 const int HighMask[] = {1, 5, 3, 7};
16210 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16211 const int LowMask[] = {0, 4, 2, 6};
16212 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16215 // If we have a signed multiply but no PMULDQ fix up the high parts of a
16216 // unsigned multiply.
16217 if (IsSigned && !Subtarget->hasSSE41()) {
16219 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16220 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16221 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16222 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16223 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16225 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16226 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16229 // The first result of MUL_LOHI is actually the low value, followed by the
16231 SDValue Ops[] = {Lows, Highs};
16232 return DAG.getMergeValues(Ops, dl);
16235 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16236 const X86Subtarget *Subtarget) {
16237 MVT VT = Op.getSimpleValueType();
16239 SDValue R = Op.getOperand(0);
16240 SDValue Amt = Op.getOperand(1);
16242 // Optimize shl/srl/sra with constant shift amount.
16243 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16244 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16245 uint64_t ShiftAmt = ShiftConst->getZExtValue();
16247 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16248 (Subtarget->hasInt256() &&
16249 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16250 (Subtarget->hasAVX512() &&
16251 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16252 if (Op.getOpcode() == ISD::SHL)
16253 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16255 if (Op.getOpcode() == ISD::SRL)
16256 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16258 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16259 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16263 if (VT == MVT::v16i8) {
16264 if (Op.getOpcode() == ISD::SHL) {
16265 // Make a large shift.
16266 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16267 MVT::v8i16, R, ShiftAmt,
16269 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16270 // Zero out the rightmost bits.
16271 SmallVector<SDValue, 16> V(16,
16272 DAG.getConstant(uint8_t(-1U << ShiftAmt),
16274 return DAG.getNode(ISD::AND, dl, VT, SHL,
16275 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16277 if (Op.getOpcode() == ISD::SRL) {
16278 // Make a large shift.
16279 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16280 MVT::v8i16, R, ShiftAmt,
16282 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16283 // Zero out the leftmost bits.
16284 SmallVector<SDValue, 16> V(16,
16285 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16287 return DAG.getNode(ISD::AND, dl, VT, SRL,
16288 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16290 if (Op.getOpcode() == ISD::SRA) {
16291 if (ShiftAmt == 7) {
16292 // R s>> 7 === R s< 0
16293 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16294 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16297 // R s>> a === ((R u>> a) ^ m) - m
16298 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16299 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
16301 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16302 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16303 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16306 llvm_unreachable("Unknown shift opcode.");
16309 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
16310 if (Op.getOpcode() == ISD::SHL) {
16311 // Make a large shift.
16312 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16313 MVT::v16i16, R, ShiftAmt,
16315 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16316 // Zero out the rightmost bits.
16317 SmallVector<SDValue, 32> V(32,
16318 DAG.getConstant(uint8_t(-1U << ShiftAmt),
16320 return DAG.getNode(ISD::AND, dl, VT, SHL,
16321 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16323 if (Op.getOpcode() == ISD::SRL) {
16324 // Make a large shift.
16325 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16326 MVT::v16i16, R, ShiftAmt,
16328 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16329 // Zero out the leftmost bits.
16330 SmallVector<SDValue, 32> V(32,
16331 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16333 return DAG.getNode(ISD::AND, dl, VT, SRL,
16334 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16336 if (Op.getOpcode() == ISD::SRA) {
16337 if (ShiftAmt == 7) {
16338 // R s>> 7 === R s< 0
16339 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16340 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16343 // R s>> a === ((R u>> a) ^ m) - m
16344 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16345 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
16347 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16348 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16349 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16352 llvm_unreachable("Unknown shift opcode.");
16357 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16358 if (!Subtarget->is64Bit() &&
16359 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16360 Amt.getOpcode() == ISD::BITCAST &&
16361 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16362 Amt = Amt.getOperand(0);
16363 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16364 VT.getVectorNumElements();
16365 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16366 uint64_t ShiftAmt = 0;
16367 for (unsigned i = 0; i != Ratio; ++i) {
16368 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16372 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16374 // Check remaining shift amounts.
16375 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16376 uint64_t ShAmt = 0;
16377 for (unsigned j = 0; j != Ratio; ++j) {
16378 ConstantSDNode *C =
16379 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16383 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16385 if (ShAmt != ShiftAmt)
16388 switch (Op.getOpcode()) {
16390 llvm_unreachable("Unknown shift opcode!");
16392 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16395 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16398 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16406 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16407 const X86Subtarget* Subtarget) {
16408 MVT VT = Op.getSimpleValueType();
16410 SDValue R = Op.getOperand(0);
16411 SDValue Amt = Op.getOperand(1);
16413 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16414 VT == MVT::v4i32 || VT == MVT::v8i16 ||
16415 (Subtarget->hasInt256() &&
16416 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16417 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16418 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16420 EVT EltVT = VT.getVectorElementType();
16422 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16423 unsigned NumElts = VT.getVectorNumElements();
16425 for (i = 0; i != NumElts; ++i) {
16426 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
16430 for (j = i; j != NumElts; ++j) {
16431 SDValue Arg = Amt.getOperand(j);
16432 if (Arg.getOpcode() == ISD::UNDEF) continue;
16433 if (Arg != Amt.getOperand(i))
16436 if (i != NumElts && j == NumElts)
16437 BaseShAmt = Amt.getOperand(i);
16439 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16440 Amt = Amt.getOperand(0);
16441 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
16442 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
16443 SDValue InVec = Amt.getOperand(0);
16444 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16445 unsigned NumElts = InVec.getValueType().getVectorNumElements();
16447 for (; i != NumElts; ++i) {
16448 SDValue Arg = InVec.getOperand(i);
16449 if (Arg.getOpcode() == ISD::UNDEF) continue;
16453 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16454 if (ConstantSDNode *C =
16455 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16456 unsigned SplatIdx =
16457 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16458 if (C->getZExtValue() == SplatIdx)
16459 BaseShAmt = InVec.getOperand(1);
16462 if (!BaseShAmt.getNode())
16463 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16464 DAG.getIntPtrConstant(0));
16468 if (BaseShAmt.getNode()) {
16469 if (EltVT.bitsGT(MVT::i32))
16470 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16471 else if (EltVT.bitsLT(MVT::i32))
16472 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16474 switch (Op.getOpcode()) {
16476 llvm_unreachable("Unknown shift opcode!");
16478 switch (VT.SimpleTy) {
16479 default: return SDValue();
16488 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16491 switch (VT.SimpleTy) {
16492 default: return SDValue();
16499 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16502 switch (VT.SimpleTy) {
16503 default: return SDValue();
16512 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16518 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16519 if (!Subtarget->is64Bit() &&
16520 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16521 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16522 Amt.getOpcode() == ISD::BITCAST &&
16523 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16524 Amt = Amt.getOperand(0);
16525 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16526 VT.getVectorNumElements();
16527 std::vector<SDValue> Vals(Ratio);
16528 for (unsigned i = 0; i != Ratio; ++i)
16529 Vals[i] = Amt.getOperand(i);
16530 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16531 for (unsigned j = 0; j != Ratio; ++j)
16532 if (Vals[j] != Amt.getOperand(i + j))
16535 switch (Op.getOpcode()) {
16537 llvm_unreachable("Unknown shift opcode!");
16539 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16541 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16543 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16550 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16551 SelectionDAG &DAG) {
16552 MVT VT = Op.getSimpleValueType();
16554 SDValue R = Op.getOperand(0);
16555 SDValue Amt = Op.getOperand(1);
16558 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16559 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16561 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16565 V = LowerScalarVariableShift(Op, DAG, Subtarget);
16569 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16571 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16572 if (Subtarget->hasInt256()) {
16573 if (Op.getOpcode() == ISD::SRL &&
16574 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16575 VT == MVT::v4i64 || VT == MVT::v8i32))
16577 if (Op.getOpcode() == ISD::SHL &&
16578 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16579 VT == MVT::v4i64 || VT == MVT::v8i32))
16581 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16585 // If possible, lower this packed shift into a vector multiply instead of
16586 // expanding it into a sequence of scalar shifts.
16587 // Do this only if the vector shift count is a constant build_vector.
16588 if (Op.getOpcode() == ISD::SHL &&
16589 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16590 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16591 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16592 SmallVector<SDValue, 8> Elts;
16593 EVT SVT = VT.getScalarType();
16594 unsigned SVTBits = SVT.getSizeInBits();
16595 const APInt &One = APInt(SVTBits, 1);
16596 unsigned NumElems = VT.getVectorNumElements();
16598 for (unsigned i=0; i !=NumElems; ++i) {
16599 SDValue Op = Amt->getOperand(i);
16600 if (Op->getOpcode() == ISD::UNDEF) {
16601 Elts.push_back(Op);
16605 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16606 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16607 uint64_t ShAmt = C.getZExtValue();
16608 if (ShAmt >= SVTBits) {
16609 Elts.push_back(DAG.getUNDEF(SVT));
16612 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16614 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16615 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16618 // Lower SHL with variable shift amount.
16619 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16620 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16622 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16623 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16624 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16625 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16628 // If possible, lower this shift as a sequence of two shifts by
16629 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16631 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16633 // Could be rewritten as:
16634 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16636 // The advantage is that the two shifts from the example would be
16637 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16638 // the vector shift into four scalar shifts plus four pairs of vector
16640 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16641 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16642 unsigned TargetOpcode = X86ISD::MOVSS;
16643 bool CanBeSimplified;
16644 // The splat value for the first packed shift (the 'X' from the example).
16645 SDValue Amt1 = Amt->getOperand(0);
16646 // The splat value for the second packed shift (the 'Y' from the example).
16647 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16648 Amt->getOperand(2);
16650 // See if it is possible to replace this node with a sequence of
16651 // two shifts followed by a MOVSS/MOVSD
16652 if (VT == MVT::v4i32) {
16653 // Check if it is legal to use a MOVSS.
16654 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16655 Amt2 == Amt->getOperand(3);
16656 if (!CanBeSimplified) {
16657 // Otherwise, check if we can still simplify this node using a MOVSD.
16658 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16659 Amt->getOperand(2) == Amt->getOperand(3);
16660 TargetOpcode = X86ISD::MOVSD;
16661 Amt2 = Amt->getOperand(2);
16664 // Do similar checks for the case where the machine value type
16666 CanBeSimplified = Amt1 == Amt->getOperand(1);
16667 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16668 CanBeSimplified = Amt2 == Amt->getOperand(i);
16670 if (!CanBeSimplified) {
16671 TargetOpcode = X86ISD::MOVSD;
16672 CanBeSimplified = true;
16673 Amt2 = Amt->getOperand(4);
16674 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16675 CanBeSimplified = Amt1 == Amt->getOperand(i);
16676 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16677 CanBeSimplified = Amt2 == Amt->getOperand(j);
16681 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16682 isa<ConstantSDNode>(Amt2)) {
16683 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16684 EVT CastVT = MVT::v4i32;
16686 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16687 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16689 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16690 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16691 if (TargetOpcode == X86ISD::MOVSD)
16692 CastVT = MVT::v2i64;
16693 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16694 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16695 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16697 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16701 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16702 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16705 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16706 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16708 // Turn 'a' into a mask suitable for VSELECT
16709 SDValue VSelM = DAG.getConstant(0x80, VT);
16710 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16711 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16713 SDValue CM1 = DAG.getConstant(0x0f, VT);
16714 SDValue CM2 = DAG.getConstant(0x3f, VT);
16716 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16717 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16718 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16719 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16720 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16723 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16724 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16725 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16727 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16728 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16729 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16730 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16731 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16734 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16735 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16736 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16738 // return VSELECT(r, r+r, a);
16739 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16740 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16744 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16745 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16746 // solution better.
16747 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16748 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16750 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16751 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16752 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16753 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16754 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16757 // Decompose 256-bit shifts into smaller 128-bit shifts.
16758 if (VT.is256BitVector()) {
16759 unsigned NumElems = VT.getVectorNumElements();
16760 MVT EltVT = VT.getVectorElementType();
16761 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16763 // Extract the two vectors
16764 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16765 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16767 // Recreate the shift amount vectors
16768 SDValue Amt1, Amt2;
16769 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16770 // Constant shift amount
16771 SmallVector<SDValue, 4> Amt1Csts;
16772 SmallVector<SDValue, 4> Amt2Csts;
16773 for (unsigned i = 0; i != NumElems/2; ++i)
16774 Amt1Csts.push_back(Amt->getOperand(i));
16775 for (unsigned i = NumElems/2; i != NumElems; ++i)
16776 Amt2Csts.push_back(Amt->getOperand(i));
16778 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16779 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16781 // Variable shift amount
16782 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16783 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16786 // Issue new vector shifts for the smaller types
16787 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16788 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16790 // Concatenate the result back
16791 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16797 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16798 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16799 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16800 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16801 // has only one use.
16802 SDNode *N = Op.getNode();
16803 SDValue LHS = N->getOperand(0);
16804 SDValue RHS = N->getOperand(1);
16805 unsigned BaseOp = 0;
16808 switch (Op.getOpcode()) {
16809 default: llvm_unreachable("Unknown ovf instruction!");
16811 // A subtract of one will be selected as a INC. Note that INC doesn't
16812 // set CF, so we can't do this for UADDO.
16813 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16815 BaseOp = X86ISD::INC;
16816 Cond = X86::COND_O;
16819 BaseOp = X86ISD::ADD;
16820 Cond = X86::COND_O;
16823 BaseOp = X86ISD::ADD;
16824 Cond = X86::COND_B;
16827 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16828 // set CF, so we can't do this for USUBO.
16829 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16831 BaseOp = X86ISD::DEC;
16832 Cond = X86::COND_O;
16835 BaseOp = X86ISD::SUB;
16836 Cond = X86::COND_O;
16839 BaseOp = X86ISD::SUB;
16840 Cond = X86::COND_B;
16843 BaseOp = X86ISD::SMUL;
16844 Cond = X86::COND_O;
16846 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16847 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16849 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16852 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16853 DAG.getConstant(X86::COND_O, MVT::i32),
16854 SDValue(Sum.getNode(), 2));
16856 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16860 // Also sets EFLAGS.
16861 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16862 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16865 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16866 DAG.getConstant(Cond, MVT::i32),
16867 SDValue(Sum.getNode(), 1));
16869 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16872 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16873 SelectionDAG &DAG) const {
16875 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16876 MVT VT = Op.getSimpleValueType();
16878 if (!Subtarget->hasSSE2() || !VT.isVector())
16881 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16882 ExtraVT.getScalarType().getSizeInBits();
16884 switch (VT.SimpleTy) {
16885 default: return SDValue();
16888 if (!Subtarget->hasFp256())
16890 if (!Subtarget->hasInt256()) {
16891 // needs to be split
16892 unsigned NumElems = VT.getVectorNumElements();
16894 // Extract the LHS vectors
16895 SDValue LHS = Op.getOperand(0);
16896 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16897 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16899 MVT EltVT = VT.getVectorElementType();
16900 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16902 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16903 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16904 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16906 SDValue Extra = DAG.getValueType(ExtraVT);
16908 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16909 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16911 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16916 SDValue Op0 = Op.getOperand(0);
16917 SDValue Op00 = Op0.getOperand(0);
16919 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16920 if (Op0.getOpcode() == ISD::BITCAST &&
16921 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16922 // (sext (vzext x)) -> (vsext x)
16923 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16924 if (Tmp1.getNode()) {
16925 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16926 // This folding is only valid when the in-reg type is a vector of i8,
16928 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16929 ExtraEltVT == MVT::i32) {
16930 SDValue Tmp1Op0 = Tmp1.getOperand(0);
16931 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16932 "This optimization is invalid without a VZEXT.");
16933 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16939 // If the above didn't work, then just use Shift-Left + Shift-Right.
16940 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16942 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16948 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16949 SelectionDAG &DAG) {
16951 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16952 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16953 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16954 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16956 // The only fence that needs an instruction is a sequentially-consistent
16957 // cross-thread fence.
16958 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16959 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16960 // no-sse2). There isn't any reason to disable it if the target processor
16962 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16963 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16965 SDValue Chain = Op.getOperand(0);
16966 SDValue Zero = DAG.getConstant(0, MVT::i32);
16968 DAG.getRegister(X86::ESP, MVT::i32), // Base
16969 DAG.getTargetConstant(1, MVT::i8), // Scale
16970 DAG.getRegister(0, MVT::i32), // Index
16971 DAG.getTargetConstant(0, MVT::i32), // Disp
16972 DAG.getRegister(0, MVT::i32), // Segment.
16976 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16977 return SDValue(Res, 0);
16980 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16981 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16984 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16985 SelectionDAG &DAG) {
16986 MVT T = Op.getSimpleValueType();
16990 switch(T.SimpleTy) {
16991 default: llvm_unreachable("Invalid value type!");
16992 case MVT::i8: Reg = X86::AL; size = 1; break;
16993 case MVT::i16: Reg = X86::AX; size = 2; break;
16994 case MVT::i32: Reg = X86::EAX; size = 4; break;
16996 assert(Subtarget->is64Bit() && "Node not type legal!");
16997 Reg = X86::RAX; size = 8;
17000 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17001 Op.getOperand(2), SDValue());
17002 SDValue Ops[] = { cpIn.getValue(0),
17005 DAG.getTargetConstant(size, MVT::i8),
17006 cpIn.getValue(1) };
17007 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17008 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17009 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17013 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17014 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17015 MVT::i32, cpOut.getValue(2));
17016 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17017 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17019 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17020 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17021 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17025 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17026 SelectionDAG &DAG) {
17027 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17028 MVT DstVT = Op.getSimpleValueType();
17030 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17031 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17032 if (DstVT != MVT::f64)
17033 // This conversion needs to be expanded.
17036 SDValue InVec = Op->getOperand(0);
17038 unsigned NumElts = SrcVT.getVectorNumElements();
17039 EVT SVT = SrcVT.getVectorElementType();
17041 // Widen the vector in input in the case of MVT::v2i32.
17042 // Example: from MVT::v2i32 to MVT::v4i32.
17043 SmallVector<SDValue, 16> Elts;
17044 for (unsigned i = 0, e = NumElts; i != e; ++i)
17045 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17046 DAG.getIntPtrConstant(i)));
17048 // Explicitly mark the extra elements as Undef.
17049 SDValue Undef = DAG.getUNDEF(SVT);
17050 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
17051 Elts.push_back(Undef);
17053 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17054 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17055 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17056 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17057 DAG.getIntPtrConstant(0));
17060 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17061 Subtarget->hasMMX() && "Unexpected custom BITCAST");
17062 assert((DstVT == MVT::i64 ||
17063 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17064 "Unexpected custom BITCAST");
17065 // i64 <=> MMX conversions are Legal.
17066 if (SrcVT==MVT::i64 && DstVT.isVector())
17068 if (DstVT==MVT::i64 && SrcVT.isVector())
17070 // MMX <=> MMX conversions are Legal.
17071 if (SrcVT.isVector() && DstVT.isVector())
17073 // All other conversions need to be expanded.
17077 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17078 SDNode *Node = Op.getNode();
17080 EVT T = Node->getValueType(0);
17081 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17082 DAG.getConstant(0, T), Node->getOperand(2));
17083 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17084 cast<AtomicSDNode>(Node)->getMemoryVT(),
17085 Node->getOperand(0),
17086 Node->getOperand(1), negOp,
17087 cast<AtomicSDNode>(Node)->getMemOperand(),
17088 cast<AtomicSDNode>(Node)->getOrdering(),
17089 cast<AtomicSDNode>(Node)->getSynchScope());
17092 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17093 SDNode *Node = Op.getNode();
17095 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17097 // Convert seq_cst store -> xchg
17098 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17099 // FIXME: On 32-bit, store -> fist or movq would be more efficient
17100 // (The only way to get a 16-byte store is cmpxchg16b)
17101 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17102 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17103 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17104 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17105 cast<AtomicSDNode>(Node)->getMemoryVT(),
17106 Node->getOperand(0),
17107 Node->getOperand(1), Node->getOperand(2),
17108 cast<AtomicSDNode>(Node)->getMemOperand(),
17109 cast<AtomicSDNode>(Node)->getOrdering(),
17110 cast<AtomicSDNode>(Node)->getSynchScope());
17111 return Swap.getValue(1);
17113 // Other atomic stores have a simple pattern.
17117 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17118 EVT VT = Op.getNode()->getSimpleValueType(0);
17120 // Let legalize expand this if it isn't a legal type yet.
17121 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17124 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17127 bool ExtraOp = false;
17128 switch (Op.getOpcode()) {
17129 default: llvm_unreachable("Invalid code");
17130 case ISD::ADDC: Opc = X86ISD::ADD; break;
17131 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17132 case ISD::SUBC: Opc = X86ISD::SUB; break;
17133 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17137 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17139 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17140 Op.getOperand(1), Op.getOperand(2));
17143 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17144 SelectionDAG &DAG) {
17145 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17147 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17148 // which returns the values as { float, float } (in XMM0) or
17149 // { double, double } (which is returned in XMM0, XMM1).
17151 SDValue Arg = Op.getOperand(0);
17152 EVT ArgVT = Arg.getValueType();
17153 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17155 TargetLowering::ArgListTy Args;
17156 TargetLowering::ArgListEntry Entry;
17160 Entry.isSExt = false;
17161 Entry.isZExt = false;
17162 Args.push_back(Entry);
17164 bool isF64 = ArgVT == MVT::f64;
17165 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17166 // the small struct {f32, f32} is returned in (eax, edx). For f64,
17167 // the results are returned via SRet in memory.
17168 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
17169 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17170 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17172 Type *RetTy = isF64
17173 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
17174 : (Type*)VectorType::get(ArgTy, 4);
17176 TargetLowering::CallLoweringInfo CLI(DAG);
17177 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17178 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17180 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17183 // Returned in xmm0 and xmm1.
17184 return CallResult.first;
17186 // Returned in bits 0:31 and 32:64 xmm0.
17187 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17188 CallResult.first, DAG.getIntPtrConstant(0));
17189 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17190 CallResult.first, DAG.getIntPtrConstant(1));
17191 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17192 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17195 /// LowerOperation - Provide custom lowering hooks for some operations.
17197 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17198 switch (Op.getOpcode()) {
17199 default: llvm_unreachable("Should not custom lower this!");
17200 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
17201 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17202 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17203 return LowerCMP_SWAP(Op, Subtarget, DAG);
17204 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
17205 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
17206 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
17207 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
17208 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
17209 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
17210 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17211 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
17212 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17213 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17214 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
17215 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
17216 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
17217 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
17218 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
17219 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
17220 case ISD::SHL_PARTS:
17221 case ISD::SRA_PARTS:
17222 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
17223 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
17224 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
17225 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
17226 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
17227 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17228 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
17229 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
17230 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
17231 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
17232 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
17233 case ISD::FABS: return LowerFABS(Op, DAG);
17234 case ISD::FNEG: return LowerFNEG(Op, DAG);
17235 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
17236 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
17237 case ISD::SETCC: return LowerSETCC(Op, DAG);
17238 case ISD::SELECT: return LowerSELECT(Op, DAG);
17239 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
17240 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
17241 case ISD::VASTART: return LowerVASTART(Op, DAG);
17242 case ISD::VAARG: return LowerVAARG(Op, DAG);
17243 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
17244 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
17245 case ISD::INTRINSIC_VOID:
17246 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17247 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
17248 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
17249 case ISD::FRAME_TO_ARGS_OFFSET:
17250 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17251 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17252 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
17253 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
17254 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
17255 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
17256 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
17257 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
17258 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
17259 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17260 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
17261 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
17262 case ISD::UMUL_LOHI:
17263 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
17266 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
17272 case ISD::UMULO: return LowerXALUO(Op, DAG);
17273 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17274 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
17278 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17279 case ISD::ADD: return LowerADD(Op, DAG);
17280 case ISD::SUB: return LowerSUB(Op, DAG);
17281 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
17285 static void ReplaceATOMIC_LOAD(SDNode *Node,
17286 SmallVectorImpl<SDValue> &Results,
17287 SelectionDAG &DAG) {
17289 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17291 // Convert wide load -> cmpxchg8b/cmpxchg16b
17292 // FIXME: On 32-bit, load -> fild or movq would be more efficient
17293 // (The only way to get a 16-byte load is cmpxchg16b)
17294 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
17295 SDValue Zero = DAG.getConstant(0, VT);
17296 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
17298 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
17299 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
17300 cast<AtomicSDNode>(Node)->getMemOperand(),
17301 cast<AtomicSDNode>(Node)->getOrdering(),
17302 cast<AtomicSDNode>(Node)->getOrdering(),
17303 cast<AtomicSDNode>(Node)->getSynchScope());
17304 Results.push_back(Swap.getValue(0));
17305 Results.push_back(Swap.getValue(2));
17308 /// ReplaceNodeResults - Replace a node with an illegal result type
17309 /// with a new node built out of custom code.
17310 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17311 SmallVectorImpl<SDValue>&Results,
17312 SelectionDAG &DAG) const {
17314 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17315 switch (N->getOpcode()) {
17317 llvm_unreachable("Do not know how to custom type legalize this operation!");
17318 case ISD::SIGN_EXTEND_INREG:
17323 // We don't want to expand or promote these.
17330 case ISD::UDIVREM: {
17331 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17332 Results.push_back(V);
17335 case ISD::FP_TO_SINT:
17336 case ISD::FP_TO_UINT: {
17337 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17339 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17342 std::pair<SDValue,SDValue> Vals =
17343 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17344 SDValue FIST = Vals.first, StackSlot = Vals.second;
17345 if (FIST.getNode()) {
17346 EVT VT = N->getValueType(0);
17347 // Return a load from the stack slot.
17348 if (StackSlot.getNode())
17349 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17350 MachinePointerInfo(),
17351 false, false, false, 0));
17353 Results.push_back(FIST);
17357 case ISD::UINT_TO_FP: {
17358 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17359 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17360 N->getValueType(0) != MVT::v2f32)
17362 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17364 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17366 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17367 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17368 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17369 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17370 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17371 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17374 case ISD::FP_ROUND: {
17375 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17377 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17378 Results.push_back(V);
17381 case ISD::INTRINSIC_W_CHAIN: {
17382 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17384 default : llvm_unreachable("Do not know how to custom type "
17385 "legalize this intrinsic operation!");
17386 case Intrinsic::x86_rdtsc:
17387 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17389 case Intrinsic::x86_rdtscp:
17390 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17392 case Intrinsic::x86_rdpmc:
17393 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17396 case ISD::READCYCLECOUNTER: {
17397 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17400 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17401 EVT T = N->getValueType(0);
17402 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17403 bool Regs64bit = T == MVT::i128;
17404 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17405 SDValue cpInL, cpInH;
17406 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17407 DAG.getConstant(0, HalfT));
17408 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17409 DAG.getConstant(1, HalfT));
17410 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17411 Regs64bit ? X86::RAX : X86::EAX,
17413 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17414 Regs64bit ? X86::RDX : X86::EDX,
17415 cpInH, cpInL.getValue(1));
17416 SDValue swapInL, swapInH;
17417 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17418 DAG.getConstant(0, HalfT));
17419 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17420 DAG.getConstant(1, HalfT));
17421 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17422 Regs64bit ? X86::RBX : X86::EBX,
17423 swapInL, cpInH.getValue(1));
17424 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17425 Regs64bit ? X86::RCX : X86::ECX,
17426 swapInH, swapInL.getValue(1));
17427 SDValue Ops[] = { swapInH.getValue(0),
17429 swapInH.getValue(1) };
17430 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17431 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17432 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17433 X86ISD::LCMPXCHG8_DAG;
17434 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17435 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17436 Regs64bit ? X86::RAX : X86::EAX,
17437 HalfT, Result.getValue(1));
17438 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17439 Regs64bit ? X86::RDX : X86::EDX,
17440 HalfT, cpOutL.getValue(2));
17441 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17443 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17444 MVT::i32, cpOutH.getValue(2));
17446 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17447 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17448 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17450 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17451 Results.push_back(Success);
17452 Results.push_back(EFLAGS.getValue(1));
17455 case ISD::ATOMIC_SWAP:
17456 case ISD::ATOMIC_LOAD_ADD:
17457 case ISD::ATOMIC_LOAD_SUB:
17458 case ISD::ATOMIC_LOAD_AND:
17459 case ISD::ATOMIC_LOAD_OR:
17460 case ISD::ATOMIC_LOAD_XOR:
17461 case ISD::ATOMIC_LOAD_NAND:
17462 case ISD::ATOMIC_LOAD_MIN:
17463 case ISD::ATOMIC_LOAD_MAX:
17464 case ISD::ATOMIC_LOAD_UMIN:
17465 case ISD::ATOMIC_LOAD_UMAX:
17466 // Delegate to generic TypeLegalization. Situations we can really handle
17467 // should have already been dealt with by X86AtomicExpandPass.cpp.
17469 case ISD::ATOMIC_LOAD: {
17470 ReplaceATOMIC_LOAD(N, Results, DAG);
17473 case ISD::BITCAST: {
17474 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17475 EVT DstVT = N->getValueType(0);
17476 EVT SrcVT = N->getOperand(0)->getValueType(0);
17478 if (SrcVT != MVT::f64 ||
17479 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17482 unsigned NumElts = DstVT.getVectorNumElements();
17483 EVT SVT = DstVT.getVectorElementType();
17484 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17485 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17486 MVT::v2f64, N->getOperand(0));
17487 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17489 if (ExperimentalVectorWideningLegalization) {
17490 // If we are legalizing vectors by widening, we already have the desired
17491 // legal vector type, just return it.
17492 Results.push_back(ToVecInt);
17496 SmallVector<SDValue, 8> Elts;
17497 for (unsigned i = 0, e = NumElts; i != e; ++i)
17498 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17499 ToVecInt, DAG.getIntPtrConstant(i)));
17501 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17506 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17508 default: return nullptr;
17509 case X86ISD::BSF: return "X86ISD::BSF";
17510 case X86ISD::BSR: return "X86ISD::BSR";
17511 case X86ISD::SHLD: return "X86ISD::SHLD";
17512 case X86ISD::SHRD: return "X86ISD::SHRD";
17513 case X86ISD::FAND: return "X86ISD::FAND";
17514 case X86ISD::FANDN: return "X86ISD::FANDN";
17515 case X86ISD::FOR: return "X86ISD::FOR";
17516 case X86ISD::FXOR: return "X86ISD::FXOR";
17517 case X86ISD::FSRL: return "X86ISD::FSRL";
17518 case X86ISD::FILD: return "X86ISD::FILD";
17519 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17520 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17521 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17522 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17523 case X86ISD::FLD: return "X86ISD::FLD";
17524 case X86ISD::FST: return "X86ISD::FST";
17525 case X86ISD::CALL: return "X86ISD::CALL";
17526 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17527 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17528 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17529 case X86ISD::BT: return "X86ISD::BT";
17530 case X86ISD::CMP: return "X86ISD::CMP";
17531 case X86ISD::COMI: return "X86ISD::COMI";
17532 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17533 case X86ISD::CMPM: return "X86ISD::CMPM";
17534 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17535 case X86ISD::SETCC: return "X86ISD::SETCC";
17536 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17537 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17538 case X86ISD::CMOV: return "X86ISD::CMOV";
17539 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17540 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17541 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17542 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17543 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17544 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17545 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17546 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17547 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17548 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17549 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17550 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17551 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17552 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17553 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17554 case X86ISD::BLENDV: return "X86ISD::BLENDV";
17555 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17556 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17557 case X86ISD::HADD: return "X86ISD::HADD";
17558 case X86ISD::HSUB: return "X86ISD::HSUB";
17559 case X86ISD::FHADD: return "X86ISD::FHADD";
17560 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17561 case X86ISD::UMAX: return "X86ISD::UMAX";
17562 case X86ISD::UMIN: return "X86ISD::UMIN";
17563 case X86ISD::SMAX: return "X86ISD::SMAX";
17564 case X86ISD::SMIN: return "X86ISD::SMIN";
17565 case X86ISD::FMAX: return "X86ISD::FMAX";
17566 case X86ISD::FMIN: return "X86ISD::FMIN";
17567 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17568 case X86ISD::FMINC: return "X86ISD::FMINC";
17569 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17570 case X86ISD::FRCP: return "X86ISD::FRCP";
17571 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17572 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17573 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17574 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17575 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17576 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17577 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17578 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17579 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17580 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17581 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17582 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17583 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17584 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17585 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17586 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17587 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17588 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17589 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17590 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17591 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17592 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17593 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17594 case X86ISD::VSHL: return "X86ISD::VSHL";
17595 case X86ISD::VSRL: return "X86ISD::VSRL";
17596 case X86ISD::VSRA: return "X86ISD::VSRA";
17597 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17598 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17599 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17600 case X86ISD::CMPP: return "X86ISD::CMPP";
17601 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17602 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17603 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17604 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17605 case X86ISD::ADD: return "X86ISD::ADD";
17606 case X86ISD::SUB: return "X86ISD::SUB";
17607 case X86ISD::ADC: return "X86ISD::ADC";
17608 case X86ISD::SBB: return "X86ISD::SBB";
17609 case X86ISD::SMUL: return "X86ISD::SMUL";
17610 case X86ISD::UMUL: return "X86ISD::UMUL";
17611 case X86ISD::INC: return "X86ISD::INC";
17612 case X86ISD::DEC: return "X86ISD::DEC";
17613 case X86ISD::OR: return "X86ISD::OR";
17614 case X86ISD::XOR: return "X86ISD::XOR";
17615 case X86ISD::AND: return "X86ISD::AND";
17616 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17617 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17618 case X86ISD::PTEST: return "X86ISD::PTEST";
17619 case X86ISD::TESTP: return "X86ISD::TESTP";
17620 case X86ISD::TESTM: return "X86ISD::TESTM";
17621 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17622 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17623 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17624 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17625 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17626 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17627 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17628 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17629 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17630 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17631 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17632 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17633 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17634 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17635 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17636 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17637 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17638 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17639 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17640 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17641 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17642 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17643 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17644 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
17645 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17646 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
17647 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17648 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17649 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17650 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17651 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17652 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17653 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17654 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17655 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17656 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17657 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17658 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17659 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17660 case X86ISD::SAHF: return "X86ISD::SAHF";
17661 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17662 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17663 case X86ISD::FMADD: return "X86ISD::FMADD";
17664 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17665 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17666 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17667 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17668 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17669 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
17670 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
17671 case X86ISD::XTEST: return "X86ISD::XTEST";
17675 // isLegalAddressingMode - Return true if the addressing mode represented
17676 // by AM is legal for this target, for a load/store of the specified type.
17677 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17679 // X86 supports extremely general addressing modes.
17680 CodeModel::Model M = getTargetMachine().getCodeModel();
17681 Reloc::Model R = getTargetMachine().getRelocationModel();
17683 // X86 allows a sign-extended 32-bit immediate field as a displacement.
17684 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17689 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17691 // If a reference to this global requires an extra load, we can't fold it.
17692 if (isGlobalStubReference(GVFlags))
17695 // If BaseGV requires a register for the PIC base, we cannot also have a
17696 // BaseReg specified.
17697 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17700 // If lower 4G is not available, then we must use rip-relative addressing.
17701 if ((M != CodeModel::Small || R != Reloc::Static) &&
17702 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17706 switch (AM.Scale) {
17712 // These scales always work.
17717 // These scales are formed with basereg+scalereg. Only accept if there is
17722 default: // Other stuff never works.
17729 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17730 unsigned Bits = Ty->getScalarSizeInBits();
17732 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17733 // particularly cheaper than those without.
17737 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17738 // variable shifts just as cheap as scalar ones.
17739 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17742 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17743 // fully general vector.
17747 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17748 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17750 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17751 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17752 return NumBits1 > NumBits2;
17755 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17756 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17759 if (!isTypeLegal(EVT::getEVT(Ty1)))
17762 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17764 // Assuming the caller doesn't have a zeroext or signext return parameter,
17765 // truncation all the way down to i1 is valid.
17769 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17770 return isInt<32>(Imm);
17773 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17774 // Can also use sub to handle negated immediates.
17775 return isInt<32>(Imm);
17778 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17779 if (!VT1.isInteger() || !VT2.isInteger())
17781 unsigned NumBits1 = VT1.getSizeInBits();
17782 unsigned NumBits2 = VT2.getSizeInBits();
17783 return NumBits1 > NumBits2;
17786 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17787 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17788 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17791 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17792 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17793 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17796 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17797 EVT VT1 = Val.getValueType();
17798 if (isZExtFree(VT1, VT2))
17801 if (Val.getOpcode() != ISD::LOAD)
17804 if (!VT1.isSimple() || !VT1.isInteger() ||
17805 !VT2.isSimple() || !VT2.isInteger())
17808 switch (VT1.getSimpleVT().SimpleTy) {
17813 // X86 has 8, 16, and 32-bit zero-extending loads.
17821 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17822 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17825 VT = VT.getScalarType();
17827 if (!VT.isSimple())
17830 switch (VT.getSimpleVT().SimpleTy) {
17841 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17842 // i16 instructions are longer (0x66 prefix) and potentially slower.
17843 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17846 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17847 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17848 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17849 /// are assumed to be legal.
17851 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17853 if (!VT.isSimple())
17856 MVT SVT = VT.getSimpleVT();
17858 // Very little shuffling can be done for 64-bit vectors right now.
17859 if (VT.getSizeInBits() == 64)
17862 // If this is a single-input shuffle with no 128 bit lane crossings we can
17863 // lower it into pshufb.
17864 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17865 (SVT.is256BitVector() && Subtarget->hasInt256())) {
17866 bool isLegal = true;
17867 for (unsigned I = 0, E = M.size(); I != E; ++I) {
17868 if (M[I] >= (int)SVT.getVectorNumElements() ||
17869 ShuffleCrosses128bitLane(SVT, I, M[I])) {
17878 // FIXME: blends, shifts.
17879 return (SVT.getVectorNumElements() == 2 ||
17880 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17881 isMOVLMask(M, SVT) ||
17882 isMOVHLPSMask(M, SVT) ||
17883 isSHUFPMask(M, SVT) ||
17884 isPSHUFDMask(M, SVT) ||
17885 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17886 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17887 isPALIGNRMask(M, SVT, Subtarget) ||
17888 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17889 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17890 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17891 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17892 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17896 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17898 if (!VT.isSimple())
17901 MVT SVT = VT.getSimpleVT();
17902 unsigned NumElts = SVT.getVectorNumElements();
17903 // FIXME: This collection of masks seems suspect.
17906 if (NumElts == 4 && SVT.is128BitVector()) {
17907 return (isMOVLMask(Mask, SVT) ||
17908 isCommutedMOVLMask(Mask, SVT, true) ||
17909 isSHUFPMask(Mask, SVT) ||
17910 isSHUFPMask(Mask, SVT, /* Commuted */ true));
17915 //===----------------------------------------------------------------------===//
17916 // X86 Scheduler Hooks
17917 //===----------------------------------------------------------------------===//
17919 /// Utility function to emit xbegin specifying the start of an RTM region.
17920 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17921 const TargetInstrInfo *TII) {
17922 DebugLoc DL = MI->getDebugLoc();
17924 const BasicBlock *BB = MBB->getBasicBlock();
17925 MachineFunction::iterator I = MBB;
17928 // For the v = xbegin(), we generate
17939 MachineBasicBlock *thisMBB = MBB;
17940 MachineFunction *MF = MBB->getParent();
17941 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17942 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17943 MF->insert(I, mainMBB);
17944 MF->insert(I, sinkMBB);
17946 // Transfer the remainder of BB and its successor edges to sinkMBB.
17947 sinkMBB->splice(sinkMBB->begin(), MBB,
17948 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17949 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17953 // # fallthrough to mainMBB
17954 // # abortion to sinkMBB
17955 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17956 thisMBB->addSuccessor(mainMBB);
17957 thisMBB->addSuccessor(sinkMBB);
17961 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17962 mainMBB->addSuccessor(sinkMBB);
17965 // EAX is live into the sinkMBB
17966 sinkMBB->addLiveIn(X86::EAX);
17967 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17968 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17971 MI->eraseFromParent();
17975 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17976 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17977 // in the .td file.
17978 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17979 const TargetInstrInfo *TII) {
17981 switch (MI->getOpcode()) {
17982 default: llvm_unreachable("illegal opcode!");
17983 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17984 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17985 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17986 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17987 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17988 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17989 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17990 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17993 DebugLoc dl = MI->getDebugLoc();
17994 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17996 unsigned NumArgs = MI->getNumOperands();
17997 for (unsigned i = 1; i < NumArgs; ++i) {
17998 MachineOperand &Op = MI->getOperand(i);
17999 if (!(Op.isReg() && Op.isImplicit()))
18000 MIB.addOperand(Op);
18002 if (MI->hasOneMemOperand())
18003 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18005 BuildMI(*BB, MI, dl,
18006 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18007 .addReg(X86::XMM0);
18009 MI->eraseFromParent();
18013 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18014 // defs in an instruction pattern
18015 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18016 const TargetInstrInfo *TII) {
18018 switch (MI->getOpcode()) {
18019 default: llvm_unreachable("illegal opcode!");
18020 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
18021 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18022 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
18023 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18024 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
18025 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18026 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
18027 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18030 DebugLoc dl = MI->getDebugLoc();
18031 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18033 unsigned NumArgs = MI->getNumOperands(); // remove the results
18034 for (unsigned i = 1; i < NumArgs; ++i) {
18035 MachineOperand &Op = MI->getOperand(i);
18036 if (!(Op.isReg() && Op.isImplicit()))
18037 MIB.addOperand(Op);
18039 if (MI->hasOneMemOperand())
18040 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18042 BuildMI(*BB, MI, dl,
18043 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18046 MI->eraseFromParent();
18050 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18051 const TargetInstrInfo *TII,
18052 const X86Subtarget* Subtarget) {
18053 DebugLoc dl = MI->getDebugLoc();
18055 // Address into RAX/EAX, other two args into ECX, EDX.
18056 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18057 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18058 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18059 for (int i = 0; i < X86::AddrNumOperands; ++i)
18060 MIB.addOperand(MI->getOperand(i));
18062 unsigned ValOps = X86::AddrNumOperands;
18063 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18064 .addReg(MI->getOperand(ValOps).getReg());
18065 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18066 .addReg(MI->getOperand(ValOps+1).getReg());
18068 // The instruction doesn't actually take any operands though.
18069 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18071 MI->eraseFromParent(); // The pseudo is gone now.
18075 MachineBasicBlock *
18076 X86TargetLowering::EmitVAARG64WithCustomInserter(
18078 MachineBasicBlock *MBB) const {
18079 // Emit va_arg instruction on X86-64.
18081 // Operands to this pseudo-instruction:
18082 // 0 ) Output : destination address (reg)
18083 // 1-5) Input : va_list address (addr, i64mem)
18084 // 6 ) ArgSize : Size (in bytes) of vararg type
18085 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18086 // 8 ) Align : Alignment of type
18087 // 9 ) EFLAGS (implicit-def)
18089 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18090 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
18092 unsigned DestReg = MI->getOperand(0).getReg();
18093 MachineOperand &Base = MI->getOperand(1);
18094 MachineOperand &Scale = MI->getOperand(2);
18095 MachineOperand &Index = MI->getOperand(3);
18096 MachineOperand &Disp = MI->getOperand(4);
18097 MachineOperand &Segment = MI->getOperand(5);
18098 unsigned ArgSize = MI->getOperand(6).getImm();
18099 unsigned ArgMode = MI->getOperand(7).getImm();
18100 unsigned Align = MI->getOperand(8).getImm();
18102 // Memory Reference
18103 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18104 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18105 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18107 // Machine Information
18108 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18109 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18110 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18111 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18112 DebugLoc DL = MI->getDebugLoc();
18114 // struct va_list {
18117 // i64 overflow_area (address)
18118 // i64 reg_save_area (address)
18120 // sizeof(va_list) = 24
18121 // alignment(va_list) = 8
18123 unsigned TotalNumIntRegs = 6;
18124 unsigned TotalNumXMMRegs = 8;
18125 bool UseGPOffset = (ArgMode == 1);
18126 bool UseFPOffset = (ArgMode == 2);
18127 unsigned MaxOffset = TotalNumIntRegs * 8 +
18128 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18130 /* Align ArgSize to a multiple of 8 */
18131 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18132 bool NeedsAlign = (Align > 8);
18134 MachineBasicBlock *thisMBB = MBB;
18135 MachineBasicBlock *overflowMBB;
18136 MachineBasicBlock *offsetMBB;
18137 MachineBasicBlock *endMBB;
18139 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
18140 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
18141 unsigned OffsetReg = 0;
18143 if (!UseGPOffset && !UseFPOffset) {
18144 // If we only pull from the overflow region, we don't create a branch.
18145 // We don't need to alter control flow.
18146 OffsetDestReg = 0; // unused
18147 OverflowDestReg = DestReg;
18149 offsetMBB = nullptr;
18150 overflowMBB = thisMBB;
18153 // First emit code to check if gp_offset (or fp_offset) is below the bound.
18154 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18155 // If not, pull from overflow_area. (branch to overflowMBB)
18160 // offsetMBB overflowMBB
18165 // Registers for the PHI in endMBB
18166 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18167 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18169 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18170 MachineFunction *MF = MBB->getParent();
18171 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18172 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18173 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18175 MachineFunction::iterator MBBIter = MBB;
18178 // Insert the new basic blocks
18179 MF->insert(MBBIter, offsetMBB);
18180 MF->insert(MBBIter, overflowMBB);
18181 MF->insert(MBBIter, endMBB);
18183 // Transfer the remainder of MBB and its successor edges to endMBB.
18184 endMBB->splice(endMBB->begin(), thisMBB,
18185 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18186 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18188 // Make offsetMBB and overflowMBB successors of thisMBB
18189 thisMBB->addSuccessor(offsetMBB);
18190 thisMBB->addSuccessor(overflowMBB);
18192 // endMBB is a successor of both offsetMBB and overflowMBB
18193 offsetMBB->addSuccessor(endMBB);
18194 overflowMBB->addSuccessor(endMBB);
18196 // Load the offset value into a register
18197 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18198 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18202 .addDisp(Disp, UseFPOffset ? 4 : 0)
18203 .addOperand(Segment)
18204 .setMemRefs(MMOBegin, MMOEnd);
18206 // Check if there is enough room left to pull this argument.
18207 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18209 .addImm(MaxOffset + 8 - ArgSizeA8);
18211 // Branch to "overflowMBB" if offset >= max
18212 // Fall through to "offsetMBB" otherwise
18213 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18214 .addMBB(overflowMBB);
18217 // In offsetMBB, emit code to use the reg_save_area.
18219 assert(OffsetReg != 0);
18221 // Read the reg_save_area address.
18222 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18223 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18228 .addOperand(Segment)
18229 .setMemRefs(MMOBegin, MMOEnd);
18231 // Zero-extend the offset
18232 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18233 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18236 .addImm(X86::sub_32bit);
18238 // Add the offset to the reg_save_area to get the final address.
18239 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18240 .addReg(OffsetReg64)
18241 .addReg(RegSaveReg);
18243 // Compute the offset for the next argument
18244 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18245 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18247 .addImm(UseFPOffset ? 16 : 8);
18249 // Store it back into the va_list.
18250 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18254 .addDisp(Disp, UseFPOffset ? 4 : 0)
18255 .addOperand(Segment)
18256 .addReg(NextOffsetReg)
18257 .setMemRefs(MMOBegin, MMOEnd);
18260 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
18265 // Emit code to use overflow area
18268 // Load the overflow_area address into a register.
18269 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18270 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18275 .addOperand(Segment)
18276 .setMemRefs(MMOBegin, MMOEnd);
18278 // If we need to align it, do so. Otherwise, just copy the address
18279 // to OverflowDestReg.
18281 // Align the overflow address
18282 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18283 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18285 // aligned_addr = (addr + (align-1)) & ~(align-1)
18286 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18287 .addReg(OverflowAddrReg)
18290 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18292 .addImm(~(uint64_t)(Align-1));
18294 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18295 .addReg(OverflowAddrReg);
18298 // Compute the next overflow address after this argument.
18299 // (the overflow address should be kept 8-byte aligned)
18300 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18301 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18302 .addReg(OverflowDestReg)
18303 .addImm(ArgSizeA8);
18305 // Store the new overflow address.
18306 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18311 .addOperand(Segment)
18312 .addReg(NextAddrReg)
18313 .setMemRefs(MMOBegin, MMOEnd);
18315 // If we branched, emit the PHI to the front of endMBB.
18317 BuildMI(*endMBB, endMBB->begin(), DL,
18318 TII->get(X86::PHI), DestReg)
18319 .addReg(OffsetDestReg).addMBB(offsetMBB)
18320 .addReg(OverflowDestReg).addMBB(overflowMBB);
18323 // Erase the pseudo instruction
18324 MI->eraseFromParent();
18329 MachineBasicBlock *
18330 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18332 MachineBasicBlock *MBB) const {
18333 // Emit code to save XMM registers to the stack. The ABI says that the
18334 // number of registers to save is given in %al, so it's theoretically
18335 // possible to do an indirect jump trick to avoid saving all of them,
18336 // however this code takes a simpler approach and just executes all
18337 // of the stores if %al is non-zero. It's less code, and it's probably
18338 // easier on the hardware branch predictor, and stores aren't all that
18339 // expensive anyway.
18341 // Create the new basic blocks. One block contains all the XMM stores,
18342 // and one block is the final destination regardless of whether any
18343 // stores were performed.
18344 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18345 MachineFunction *F = MBB->getParent();
18346 MachineFunction::iterator MBBIter = MBB;
18348 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18349 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18350 F->insert(MBBIter, XMMSaveMBB);
18351 F->insert(MBBIter, EndMBB);
18353 // Transfer the remainder of MBB and its successor edges to EndMBB.
18354 EndMBB->splice(EndMBB->begin(), MBB,
18355 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18356 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18358 // The original block will now fall through to the XMM save block.
18359 MBB->addSuccessor(XMMSaveMBB);
18360 // The XMMSaveMBB will fall through to the end block.
18361 XMMSaveMBB->addSuccessor(EndMBB);
18363 // Now add the instructions.
18364 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18365 DebugLoc DL = MI->getDebugLoc();
18367 unsigned CountReg = MI->getOperand(0).getReg();
18368 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18369 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18371 if (!Subtarget->isTargetWin64()) {
18372 // If %al is 0, branch around the XMM save block.
18373 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18374 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
18375 MBB->addSuccessor(EndMBB);
18378 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18379 // that was just emitted, but clearly shouldn't be "saved".
18380 assert((MI->getNumOperands() <= 3 ||
18381 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18382 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18383 && "Expected last argument to be EFLAGS");
18384 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18385 // In the XMM save block, save all the XMM argument registers.
18386 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18387 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18388 MachineMemOperand *MMO =
18389 F->getMachineMemOperand(
18390 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18391 MachineMemOperand::MOStore,
18392 /*Size=*/16, /*Align=*/16);
18393 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18394 .addFrameIndex(RegSaveFrameIndex)
18395 .addImm(/*Scale=*/1)
18396 .addReg(/*IndexReg=*/0)
18397 .addImm(/*Disp=*/Offset)
18398 .addReg(/*Segment=*/0)
18399 .addReg(MI->getOperand(i).getReg())
18400 .addMemOperand(MMO);
18403 MI->eraseFromParent(); // The pseudo instruction is gone now.
18408 // The EFLAGS operand of SelectItr might be missing a kill marker
18409 // because there were multiple uses of EFLAGS, and ISel didn't know
18410 // which to mark. Figure out whether SelectItr should have had a
18411 // kill marker, and set it if it should. Returns the correct kill
18413 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18414 MachineBasicBlock* BB,
18415 const TargetRegisterInfo* TRI) {
18416 // Scan forward through BB for a use/def of EFLAGS.
18417 MachineBasicBlock::iterator miI(std::next(SelectItr));
18418 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18419 const MachineInstr& mi = *miI;
18420 if (mi.readsRegister(X86::EFLAGS))
18422 if (mi.definesRegister(X86::EFLAGS))
18423 break; // Should have kill-flag - update below.
18426 // If we hit the end of the block, check whether EFLAGS is live into a
18428 if (miI == BB->end()) {
18429 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18430 sEnd = BB->succ_end();
18431 sItr != sEnd; ++sItr) {
18432 MachineBasicBlock* succ = *sItr;
18433 if (succ->isLiveIn(X86::EFLAGS))
18438 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18439 // out. SelectMI should have a kill flag on EFLAGS.
18440 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18444 MachineBasicBlock *
18445 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18446 MachineBasicBlock *BB) const {
18447 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18448 DebugLoc DL = MI->getDebugLoc();
18450 // To "insert" a SELECT_CC instruction, we actually have to insert the
18451 // diamond control-flow pattern. The incoming instruction knows the
18452 // destination vreg to set, the condition code register to branch on, the
18453 // true/false values to select between, and a branch opcode to use.
18454 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18455 MachineFunction::iterator It = BB;
18461 // cmpTY ccX, r1, r2
18463 // fallthrough --> copy0MBB
18464 MachineBasicBlock *thisMBB = BB;
18465 MachineFunction *F = BB->getParent();
18466 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18467 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18468 F->insert(It, copy0MBB);
18469 F->insert(It, sinkMBB);
18471 // If the EFLAGS register isn't dead in the terminator, then claim that it's
18472 // live into the sink and copy blocks.
18473 const TargetRegisterInfo *TRI =
18474 BB->getParent()->getSubtarget().getRegisterInfo();
18475 if (!MI->killsRegister(X86::EFLAGS) &&
18476 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18477 copy0MBB->addLiveIn(X86::EFLAGS);
18478 sinkMBB->addLiveIn(X86::EFLAGS);
18481 // Transfer the remainder of BB and its successor edges to sinkMBB.
18482 sinkMBB->splice(sinkMBB->begin(), BB,
18483 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18484 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18486 // Add the true and fallthrough blocks as its successors.
18487 BB->addSuccessor(copy0MBB);
18488 BB->addSuccessor(sinkMBB);
18490 // Create the conditional branch instruction.
18492 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18493 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18496 // %FalseValue = ...
18497 // # fallthrough to sinkMBB
18498 copy0MBB->addSuccessor(sinkMBB);
18501 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18503 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18504 TII->get(X86::PHI), MI->getOperand(0).getReg())
18505 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18506 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18508 MI->eraseFromParent(); // The pseudo instruction is gone now.
18512 MachineBasicBlock *
18513 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18514 bool Is64Bit) const {
18515 MachineFunction *MF = BB->getParent();
18516 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18517 DebugLoc DL = MI->getDebugLoc();
18518 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18520 assert(MF->shouldSplitStack());
18522 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18523 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18526 // ... [Till the alloca]
18527 // If stacklet is not large enough, jump to mallocMBB
18530 // Allocate by subtracting from RSP
18531 // Jump to continueMBB
18534 // Allocate by call to runtime
18538 // [rest of original BB]
18541 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18542 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18543 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18545 MachineRegisterInfo &MRI = MF->getRegInfo();
18546 const TargetRegisterClass *AddrRegClass =
18547 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18549 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18550 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18551 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18552 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18553 sizeVReg = MI->getOperand(1).getReg(),
18554 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18556 MachineFunction::iterator MBBIter = BB;
18559 MF->insert(MBBIter, bumpMBB);
18560 MF->insert(MBBIter, mallocMBB);
18561 MF->insert(MBBIter, continueMBB);
18563 continueMBB->splice(continueMBB->begin(), BB,
18564 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18565 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18567 // Add code to the main basic block to check if the stack limit has been hit,
18568 // and if so, jump to mallocMBB otherwise to bumpMBB.
18569 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18570 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18571 .addReg(tmpSPVReg).addReg(sizeVReg);
18572 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18573 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18574 .addReg(SPLimitVReg);
18575 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18577 // bumpMBB simply decreases the stack pointer, since we know the current
18578 // stacklet has enough space.
18579 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18580 .addReg(SPLimitVReg);
18581 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18582 .addReg(SPLimitVReg);
18583 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18585 // Calls into a routine in libgcc to allocate more space from the heap.
18586 const uint32_t *RegMask = MF->getTarget()
18587 .getSubtargetImpl()
18588 ->getRegisterInfo()
18589 ->getCallPreservedMask(CallingConv::C);
18591 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18593 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18594 .addExternalSymbol("__morestack_allocate_stack_space")
18595 .addRegMask(RegMask)
18596 .addReg(X86::RDI, RegState::Implicit)
18597 .addReg(X86::RAX, RegState::ImplicitDefine);
18599 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18601 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18602 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18603 .addExternalSymbol("__morestack_allocate_stack_space")
18604 .addRegMask(RegMask)
18605 .addReg(X86::EAX, RegState::ImplicitDefine);
18609 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18612 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18613 .addReg(Is64Bit ? X86::RAX : X86::EAX);
18614 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18616 // Set up the CFG correctly.
18617 BB->addSuccessor(bumpMBB);
18618 BB->addSuccessor(mallocMBB);
18619 mallocMBB->addSuccessor(continueMBB);
18620 bumpMBB->addSuccessor(continueMBB);
18622 // Take care of the PHI nodes.
18623 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18624 MI->getOperand(0).getReg())
18625 .addReg(mallocPtrVReg).addMBB(mallocMBB)
18626 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18628 // Delete the original pseudo instruction.
18629 MI->eraseFromParent();
18632 return continueMBB;
18635 MachineBasicBlock *
18636 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18637 MachineBasicBlock *BB) const {
18638 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18639 DebugLoc DL = MI->getDebugLoc();
18641 assert(!Subtarget->isTargetMacho());
18643 // The lowering is pretty easy: we're just emitting the call to _alloca. The
18644 // non-trivial part is impdef of ESP.
18646 if (Subtarget->isTargetWin64()) {
18647 if (Subtarget->isTargetCygMing()) {
18648 // ___chkstk(Mingw64):
18649 // Clobbers R10, R11, RAX and EFLAGS.
18651 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18652 .addExternalSymbol("___chkstk")
18653 .addReg(X86::RAX, RegState::Implicit)
18654 .addReg(X86::RSP, RegState::Implicit)
18655 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18656 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18657 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18659 // __chkstk(MSVCRT): does not update stack pointer.
18660 // Clobbers R10, R11 and EFLAGS.
18661 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18662 .addExternalSymbol("__chkstk")
18663 .addReg(X86::RAX, RegState::Implicit)
18664 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18665 // RAX has the offset to be subtracted from RSP.
18666 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18671 const char *StackProbeSymbol =
18672 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18674 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18675 .addExternalSymbol(StackProbeSymbol)
18676 .addReg(X86::EAX, RegState::Implicit)
18677 .addReg(X86::ESP, RegState::Implicit)
18678 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18679 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18680 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18683 MI->eraseFromParent(); // The pseudo instruction is gone now.
18687 MachineBasicBlock *
18688 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18689 MachineBasicBlock *BB) const {
18690 // This is pretty easy. We're taking the value that we received from
18691 // our load from the relocation, sticking it in either RDI (x86-64)
18692 // or EAX and doing an indirect call. The return value will then
18693 // be in the normal return register.
18694 MachineFunction *F = BB->getParent();
18695 const X86InstrInfo *TII =
18696 static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18697 DebugLoc DL = MI->getDebugLoc();
18699 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18700 assert(MI->getOperand(3).isGlobal() && "This should be a global");
18702 // Get a register mask for the lowered call.
18703 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18704 // proper register mask.
18705 const uint32_t *RegMask = F->getTarget()
18706 .getSubtargetImpl()
18707 ->getRegisterInfo()
18708 ->getCallPreservedMask(CallingConv::C);
18709 if (Subtarget->is64Bit()) {
18710 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18711 TII->get(X86::MOV64rm), X86::RDI)
18713 .addImm(0).addReg(0)
18714 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18715 MI->getOperand(3).getTargetFlags())
18717 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18718 addDirectMem(MIB, X86::RDI);
18719 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18720 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18721 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18722 TII->get(X86::MOV32rm), X86::EAX)
18724 .addImm(0).addReg(0)
18725 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18726 MI->getOperand(3).getTargetFlags())
18728 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18729 addDirectMem(MIB, X86::EAX);
18730 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18732 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18733 TII->get(X86::MOV32rm), X86::EAX)
18734 .addReg(TII->getGlobalBaseReg(F))
18735 .addImm(0).addReg(0)
18736 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18737 MI->getOperand(3).getTargetFlags())
18739 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18740 addDirectMem(MIB, X86::EAX);
18741 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18744 MI->eraseFromParent(); // The pseudo instruction is gone now.
18748 MachineBasicBlock *
18749 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18750 MachineBasicBlock *MBB) const {
18751 DebugLoc DL = MI->getDebugLoc();
18752 MachineFunction *MF = MBB->getParent();
18753 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18754 MachineRegisterInfo &MRI = MF->getRegInfo();
18756 const BasicBlock *BB = MBB->getBasicBlock();
18757 MachineFunction::iterator I = MBB;
18760 // Memory Reference
18761 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18762 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18765 unsigned MemOpndSlot = 0;
18767 unsigned CurOp = 0;
18769 DstReg = MI->getOperand(CurOp++).getReg();
18770 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18771 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18772 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18773 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18775 MemOpndSlot = CurOp;
18777 MVT PVT = getPointerTy();
18778 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18779 "Invalid Pointer Size!");
18781 // For v = setjmp(buf), we generate
18784 // buf[LabelOffset] = restoreMBB
18785 // SjLjSetup restoreMBB
18791 // v = phi(main, restore)
18796 MachineBasicBlock *thisMBB = MBB;
18797 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18798 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18799 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18800 MF->insert(I, mainMBB);
18801 MF->insert(I, sinkMBB);
18802 MF->push_back(restoreMBB);
18804 MachineInstrBuilder MIB;
18806 // Transfer the remainder of BB and its successor edges to sinkMBB.
18807 sinkMBB->splice(sinkMBB->begin(), MBB,
18808 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18809 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18812 unsigned PtrStoreOpc = 0;
18813 unsigned LabelReg = 0;
18814 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18815 Reloc::Model RM = MF->getTarget().getRelocationModel();
18816 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18817 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18819 // Prepare IP either in reg or imm.
18820 if (!UseImmLabel) {
18821 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18822 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18823 LabelReg = MRI.createVirtualRegister(PtrRC);
18824 if (Subtarget->is64Bit()) {
18825 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18829 .addMBB(restoreMBB)
18832 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18833 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18834 .addReg(XII->getGlobalBaseReg(MF))
18837 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18841 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18843 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18844 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18845 if (i == X86::AddrDisp)
18846 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18848 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18851 MIB.addReg(LabelReg);
18853 MIB.addMBB(restoreMBB);
18854 MIB.setMemRefs(MMOBegin, MMOEnd);
18856 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18857 .addMBB(restoreMBB);
18859 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18860 MF->getSubtarget().getRegisterInfo());
18861 MIB.addRegMask(RegInfo->getNoPreservedMask());
18862 thisMBB->addSuccessor(mainMBB);
18863 thisMBB->addSuccessor(restoreMBB);
18867 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18868 mainMBB->addSuccessor(sinkMBB);
18871 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18872 TII->get(X86::PHI), DstReg)
18873 .addReg(mainDstReg).addMBB(mainMBB)
18874 .addReg(restoreDstReg).addMBB(restoreMBB);
18877 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18878 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18879 restoreMBB->addSuccessor(sinkMBB);
18881 MI->eraseFromParent();
18885 MachineBasicBlock *
18886 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18887 MachineBasicBlock *MBB) const {
18888 DebugLoc DL = MI->getDebugLoc();
18889 MachineFunction *MF = MBB->getParent();
18890 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18891 MachineRegisterInfo &MRI = MF->getRegInfo();
18893 // Memory Reference
18894 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18895 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18897 MVT PVT = getPointerTy();
18898 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18899 "Invalid Pointer Size!");
18901 const TargetRegisterClass *RC =
18902 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18903 unsigned Tmp = MRI.createVirtualRegister(RC);
18904 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18905 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18906 MF->getSubtarget().getRegisterInfo());
18907 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18908 unsigned SP = RegInfo->getStackRegister();
18910 MachineInstrBuilder MIB;
18912 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18913 const int64_t SPOffset = 2 * PVT.getStoreSize();
18915 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18916 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18919 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18920 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18921 MIB.addOperand(MI->getOperand(i));
18922 MIB.setMemRefs(MMOBegin, MMOEnd);
18924 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18925 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18926 if (i == X86::AddrDisp)
18927 MIB.addDisp(MI->getOperand(i), LabelOffset);
18929 MIB.addOperand(MI->getOperand(i));
18931 MIB.setMemRefs(MMOBegin, MMOEnd);
18933 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18934 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18935 if (i == X86::AddrDisp)
18936 MIB.addDisp(MI->getOperand(i), SPOffset);
18938 MIB.addOperand(MI->getOperand(i));
18940 MIB.setMemRefs(MMOBegin, MMOEnd);
18942 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18944 MI->eraseFromParent();
18948 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18949 // accumulator loops. Writing back to the accumulator allows the coalescer
18950 // to remove extra copies in the loop.
18951 MachineBasicBlock *
18952 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18953 MachineBasicBlock *MBB) const {
18954 MachineOperand &AddendOp = MI->getOperand(3);
18956 // Bail out early if the addend isn't a register - we can't switch these.
18957 if (!AddendOp.isReg())
18960 MachineFunction &MF = *MBB->getParent();
18961 MachineRegisterInfo &MRI = MF.getRegInfo();
18963 // Check whether the addend is defined by a PHI:
18964 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18965 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18966 if (!AddendDef.isPHI())
18969 // Look for the following pattern:
18971 // %addend = phi [%entry, 0], [%loop, %result]
18973 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18977 // %addend = phi [%entry, 0], [%loop, %result]
18979 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18981 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18982 assert(AddendDef.getOperand(i).isReg());
18983 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18984 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18985 if (&PHISrcInst == MI) {
18986 // Found a matching instruction.
18987 unsigned NewFMAOpc = 0;
18988 switch (MI->getOpcode()) {
18989 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18990 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18991 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18992 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18993 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18994 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18995 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18996 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18997 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18998 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18999 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19000 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19001 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19002 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19003 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19004 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19005 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19006 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19007 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19008 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19009 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19010 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19011 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19012 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19013 default: llvm_unreachable("Unrecognized FMA variant.");
19016 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
19017 MachineInstrBuilder MIB =
19018 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19019 .addOperand(MI->getOperand(0))
19020 .addOperand(MI->getOperand(3))
19021 .addOperand(MI->getOperand(2))
19022 .addOperand(MI->getOperand(1));
19023 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19024 MI->eraseFromParent();
19031 MachineBasicBlock *
19032 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19033 MachineBasicBlock *BB) const {
19034 switch (MI->getOpcode()) {
19035 default: llvm_unreachable("Unexpected instr type to insert");
19036 case X86::TAILJMPd64:
19037 case X86::TAILJMPr64:
19038 case X86::TAILJMPm64:
19039 llvm_unreachable("TAILJMP64 would not be touched here.");
19040 case X86::TCRETURNdi64:
19041 case X86::TCRETURNri64:
19042 case X86::TCRETURNmi64:
19044 case X86::WIN_ALLOCA:
19045 return EmitLoweredWinAlloca(MI, BB);
19046 case X86::SEG_ALLOCA_32:
19047 return EmitLoweredSegAlloca(MI, BB, false);
19048 case X86::SEG_ALLOCA_64:
19049 return EmitLoweredSegAlloca(MI, BB, true);
19050 case X86::TLSCall_32:
19051 case X86::TLSCall_64:
19052 return EmitLoweredTLSCall(MI, BB);
19053 case X86::CMOV_GR8:
19054 case X86::CMOV_FR32:
19055 case X86::CMOV_FR64:
19056 case X86::CMOV_V4F32:
19057 case X86::CMOV_V2F64:
19058 case X86::CMOV_V2I64:
19059 case X86::CMOV_V8F32:
19060 case X86::CMOV_V4F64:
19061 case X86::CMOV_V4I64:
19062 case X86::CMOV_V16F32:
19063 case X86::CMOV_V8F64:
19064 case X86::CMOV_V8I64:
19065 case X86::CMOV_GR16:
19066 case X86::CMOV_GR32:
19067 case X86::CMOV_RFP32:
19068 case X86::CMOV_RFP64:
19069 case X86::CMOV_RFP80:
19070 return EmitLoweredSelect(MI, BB);
19072 case X86::FP32_TO_INT16_IN_MEM:
19073 case X86::FP32_TO_INT32_IN_MEM:
19074 case X86::FP32_TO_INT64_IN_MEM:
19075 case X86::FP64_TO_INT16_IN_MEM:
19076 case X86::FP64_TO_INT32_IN_MEM:
19077 case X86::FP64_TO_INT64_IN_MEM:
19078 case X86::FP80_TO_INT16_IN_MEM:
19079 case X86::FP80_TO_INT32_IN_MEM:
19080 case X86::FP80_TO_INT64_IN_MEM: {
19081 MachineFunction *F = BB->getParent();
19082 const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
19083 DebugLoc DL = MI->getDebugLoc();
19085 // Change the floating point control register to use "round towards zero"
19086 // mode when truncating to an integer value.
19087 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19088 addFrameReference(BuildMI(*BB, MI, DL,
19089 TII->get(X86::FNSTCW16m)), CWFrameIdx);
19091 // Load the old value of the high byte of the control word...
19093 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19094 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19097 // Set the high part to be round to zero...
19098 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19101 // Reload the modified control word now...
19102 addFrameReference(BuildMI(*BB, MI, DL,
19103 TII->get(X86::FLDCW16m)), CWFrameIdx);
19105 // Restore the memory image of control word to original value
19106 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19109 // Get the X86 opcode to use.
19111 switch (MI->getOpcode()) {
19112 default: llvm_unreachable("illegal opcode!");
19113 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19114 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19115 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19116 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19117 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19118 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19119 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19120 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19121 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19125 MachineOperand &Op = MI->getOperand(0);
19127 AM.BaseType = X86AddressMode::RegBase;
19128 AM.Base.Reg = Op.getReg();
19130 AM.BaseType = X86AddressMode::FrameIndexBase;
19131 AM.Base.FrameIndex = Op.getIndex();
19133 Op = MI->getOperand(1);
19135 AM.Scale = Op.getImm();
19136 Op = MI->getOperand(2);
19138 AM.IndexReg = Op.getImm();
19139 Op = MI->getOperand(3);
19140 if (Op.isGlobal()) {
19141 AM.GV = Op.getGlobal();
19143 AM.Disp = Op.getImm();
19145 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19146 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19148 // Reload the original control word now.
19149 addFrameReference(BuildMI(*BB, MI, DL,
19150 TII->get(X86::FLDCW16m)), CWFrameIdx);
19152 MI->eraseFromParent(); // The pseudo instruction is gone now.
19155 // String/text processing lowering.
19156 case X86::PCMPISTRM128REG:
19157 case X86::VPCMPISTRM128REG:
19158 case X86::PCMPISTRM128MEM:
19159 case X86::VPCMPISTRM128MEM:
19160 case X86::PCMPESTRM128REG:
19161 case X86::VPCMPESTRM128REG:
19162 case X86::PCMPESTRM128MEM:
19163 case X86::VPCMPESTRM128MEM:
19164 assert(Subtarget->hasSSE42() &&
19165 "Target must have SSE4.2 or AVX features enabled");
19166 return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19168 // String/text processing lowering.
19169 case X86::PCMPISTRIREG:
19170 case X86::VPCMPISTRIREG:
19171 case X86::PCMPISTRIMEM:
19172 case X86::VPCMPISTRIMEM:
19173 case X86::PCMPESTRIREG:
19174 case X86::VPCMPESTRIREG:
19175 case X86::PCMPESTRIMEM:
19176 case X86::VPCMPESTRIMEM:
19177 assert(Subtarget->hasSSE42() &&
19178 "Target must have SSE4.2 or AVX features enabled");
19179 return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19181 // Thread synchronization.
19183 return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
19188 return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19190 case X86::VASTART_SAVE_XMM_REGS:
19191 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19193 case X86::VAARG_64:
19194 return EmitVAARG64WithCustomInserter(MI, BB);
19196 case X86::EH_SjLj_SetJmp32:
19197 case X86::EH_SjLj_SetJmp64:
19198 return emitEHSjLjSetJmp(MI, BB);
19200 case X86::EH_SjLj_LongJmp32:
19201 case X86::EH_SjLj_LongJmp64:
19202 return emitEHSjLjLongJmp(MI, BB);
19204 case TargetOpcode::STACKMAP:
19205 case TargetOpcode::PATCHPOINT:
19206 return emitPatchPoint(MI, BB);
19208 case X86::VFMADDPDr213r:
19209 case X86::VFMADDPSr213r:
19210 case X86::VFMADDSDr213r:
19211 case X86::VFMADDSSr213r:
19212 case X86::VFMSUBPDr213r:
19213 case X86::VFMSUBPSr213r:
19214 case X86::VFMSUBSDr213r:
19215 case X86::VFMSUBSSr213r:
19216 case X86::VFNMADDPDr213r:
19217 case X86::VFNMADDPSr213r:
19218 case X86::VFNMADDSDr213r:
19219 case X86::VFNMADDSSr213r:
19220 case X86::VFNMSUBPDr213r:
19221 case X86::VFNMSUBPSr213r:
19222 case X86::VFNMSUBSDr213r:
19223 case X86::VFNMSUBSSr213r:
19224 case X86::VFMADDPDr213rY:
19225 case X86::VFMADDPSr213rY:
19226 case X86::VFMSUBPDr213rY:
19227 case X86::VFMSUBPSr213rY:
19228 case X86::VFNMADDPDr213rY:
19229 case X86::VFNMADDPSr213rY:
19230 case X86::VFNMSUBPDr213rY:
19231 case X86::VFNMSUBPSr213rY:
19232 return emitFMA3Instr(MI, BB);
19236 //===----------------------------------------------------------------------===//
19237 // X86 Optimization Hooks
19238 //===----------------------------------------------------------------------===//
19240 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19243 const SelectionDAG &DAG,
19244 unsigned Depth) const {
19245 unsigned BitWidth = KnownZero.getBitWidth();
19246 unsigned Opc = Op.getOpcode();
19247 assert((Opc >= ISD::BUILTIN_OP_END ||
19248 Opc == ISD::INTRINSIC_WO_CHAIN ||
19249 Opc == ISD::INTRINSIC_W_CHAIN ||
19250 Opc == ISD::INTRINSIC_VOID) &&
19251 "Should use MaskedValueIsZero if you don't know whether Op"
19252 " is a target node!");
19254 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
19268 // These nodes' second result is a boolean.
19269 if (Op.getResNo() == 0)
19272 case X86ISD::SETCC:
19273 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19275 case ISD::INTRINSIC_WO_CHAIN: {
19276 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19277 unsigned NumLoBits = 0;
19280 case Intrinsic::x86_sse_movmsk_ps:
19281 case Intrinsic::x86_avx_movmsk_ps_256:
19282 case Intrinsic::x86_sse2_movmsk_pd:
19283 case Intrinsic::x86_avx_movmsk_pd_256:
19284 case Intrinsic::x86_mmx_pmovmskb:
19285 case Intrinsic::x86_sse2_pmovmskb_128:
19286 case Intrinsic::x86_avx2_pmovmskb: {
19287 // High bits of movmskp{s|d}, pmovmskb are known zero.
19289 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
19290 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
19291 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
19292 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
19293 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
19294 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
19295 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
19296 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
19298 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19307 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19309 const SelectionDAG &,
19310 unsigned Depth) const {
19311 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19312 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19313 return Op.getValueType().getScalarType().getSizeInBits();
19319 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19320 /// node is a GlobalAddress + offset.
19321 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19322 const GlobalValue* &GA,
19323 int64_t &Offset) const {
19324 if (N->getOpcode() == X86ISD::Wrapper) {
19325 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19326 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19327 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19331 return TargetLowering::isGAPlusOffset(N, GA, Offset);
19334 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19335 /// same as extracting the high 128-bit part of 256-bit vector and then
19336 /// inserting the result into the low part of a new 256-bit vector
19337 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19338 EVT VT = SVOp->getValueType(0);
19339 unsigned NumElems = VT.getVectorNumElements();
19341 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19342 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19343 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19344 SVOp->getMaskElt(j) >= 0)
19350 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19351 /// same as extracting the low 128-bit part of 256-bit vector and then
19352 /// inserting the result into the high part of a new 256-bit vector
19353 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19354 EVT VT = SVOp->getValueType(0);
19355 unsigned NumElems = VT.getVectorNumElements();
19357 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19358 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19359 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19360 SVOp->getMaskElt(j) >= 0)
19366 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19367 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19368 TargetLowering::DAGCombinerInfo &DCI,
19369 const X86Subtarget* Subtarget) {
19371 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19372 SDValue V1 = SVOp->getOperand(0);
19373 SDValue V2 = SVOp->getOperand(1);
19374 EVT VT = SVOp->getValueType(0);
19375 unsigned NumElems = VT.getVectorNumElements();
19377 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19378 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19382 // V UNDEF BUILD_VECTOR UNDEF
19384 // CONCAT_VECTOR CONCAT_VECTOR
19387 // RESULT: V + zero extended
19389 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19390 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19391 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19394 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19397 // To match the shuffle mask, the first half of the mask should
19398 // be exactly the first vector, and all the rest a splat with the
19399 // first element of the second one.
19400 for (unsigned i = 0; i != NumElems/2; ++i)
19401 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19402 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19405 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19406 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19407 if (Ld->hasNUsesOfValue(1, 0)) {
19408 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19409 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19411 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19413 Ld->getPointerInfo(),
19414 Ld->getAlignment(),
19415 false/*isVolatile*/, true/*ReadMem*/,
19416 false/*WriteMem*/);
19418 // Make sure the newly-created LOAD is in the same position as Ld in
19419 // terms of dependency. We create a TokenFactor for Ld and ResNode,
19420 // and update uses of Ld's output chain to use the TokenFactor.
19421 if (Ld->hasAnyUseOfValue(1)) {
19422 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19423 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19424 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19425 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19426 SDValue(ResNode.getNode(), 1));
19429 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19433 // Emit a zeroed vector and insert the desired subvector on its
19435 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19436 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19437 return DCI.CombineTo(N, InsV);
19440 //===--------------------------------------------------------------------===//
19441 // Combine some shuffles into subvector extracts and inserts:
19444 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19445 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19446 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19447 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19448 return DCI.CombineTo(N, InsV);
19451 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19452 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19453 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19454 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19455 return DCI.CombineTo(N, InsV);
19461 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19464 /// This is the leaf of the recursive combinine below. When we have found some
19465 /// chain of single-use x86 shuffle instructions and accumulated the combined
19466 /// shuffle mask represented by them, this will try to pattern match that mask
19467 /// into either a single instruction if there is a special purpose instruction
19468 /// for this operation, or into a PSHUFB instruction which is a fully general
19469 /// instruction but should only be used to replace chains over a certain depth.
19470 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19471 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19472 TargetLowering::DAGCombinerInfo &DCI,
19473 const X86Subtarget *Subtarget) {
19474 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19476 // Find the operand that enters the chain. Note that multiple uses are OK
19477 // here, we're not going to remove the operand we find.
19478 SDValue Input = Op.getOperand(0);
19479 while (Input.getOpcode() == ISD::BITCAST)
19480 Input = Input.getOperand(0);
19482 MVT VT = Input.getSimpleValueType();
19483 MVT RootVT = Root.getSimpleValueType();
19486 // Just remove no-op shuffle masks.
19487 if (Mask.size() == 1) {
19488 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19493 // Use the float domain if the operand type is a floating point type.
19494 bool FloatDomain = VT.isFloatingPoint();
19496 // If we don't have access to VEX encodings, the generic PSHUF instructions
19497 // are preferable to some of the specialized forms despite requiring one more
19498 // byte to encode because they can implicitly copy.
19500 // IF we *do* have VEX encodings, than we can use shorter, more specific
19501 // shuffle instructions freely as they can copy due to the extra register
19503 if (Subtarget->hasAVX()) {
19504 // We have both floating point and integer variants of shuffles that dup
19505 // either the low or high half of the vector.
19506 if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19507 bool Lo = Mask.equals(0, 0);
19508 unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
19509 : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19510 if (Depth == 1 && Root->getOpcode() == Shuffle)
19511 return false; // Nothing to do!
19512 MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19513 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19514 DCI.AddToWorklist(Op.getNode());
19515 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19516 DCI.AddToWorklist(Op.getNode());
19517 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19522 // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19524 // For the integer domain we have specialized instructions for duplicating
19525 // any element size from the low or high half.
19526 if (!FloatDomain &&
19527 (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19528 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19529 Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19530 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19531 Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19533 bool Lo = Mask[0] == 0;
19534 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19535 if (Depth == 1 && Root->getOpcode() == Shuffle)
19536 return false; // Nothing to do!
19538 switch (Mask.size()) {
19539 case 4: ShuffleVT = MVT::v4i32; break;
19540 case 8: ShuffleVT = MVT::v8i16; break;
19541 case 16: ShuffleVT = MVT::v16i8; break;
19543 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19544 DCI.AddToWorklist(Op.getNode());
19545 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19546 DCI.AddToWorklist(Op.getNode());
19547 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19553 // Don't try to re-form single instruction chains under any circumstances now
19554 // that we've done encoding canonicalization for them.
19558 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19559 // can replace them with a single PSHUFB instruction profitably. Intel's
19560 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19561 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19562 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19563 SmallVector<SDValue, 16> PSHUFBMask;
19564 assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19565 int Ratio = 16 / Mask.size();
19566 for (unsigned i = 0; i < 16; ++i) {
19567 int M = Mask[i / Ratio] != SM_SentinelZero
19568 ? Ratio * Mask[i / Ratio] + i % Ratio
19570 PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19572 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19573 DCI.AddToWorklist(Op.getNode());
19574 SDValue PSHUFBMaskOp =
19575 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19576 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19577 Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19578 DCI.AddToWorklist(Op.getNode());
19579 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19584 // Failed to find any combines.
19588 /// \brief Fully generic combining of x86 shuffle instructions.
19590 /// This should be the last combine run over the x86 shuffle instructions. Once
19591 /// they have been fully optimized, this will recursively consider all chains
19592 /// of single-use shuffle instructions, build a generic model of the cumulative
19593 /// shuffle operation, and check for simpler instructions which implement this
19594 /// operation. We use this primarily for two purposes:
19596 /// 1) Collapse generic shuffles to specialized single instructions when
19597 /// equivalent. In most cases, this is just an encoding size win, but
19598 /// sometimes we will collapse multiple generic shuffles into a single
19599 /// special-purpose shuffle.
19600 /// 2) Look for sequences of shuffle instructions with 3 or more total
19601 /// instructions, and replace them with the slightly more expensive SSSE3
19602 /// PSHUFB instruction if available. We do this as the last combining step
19603 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
19604 /// a suitable short sequence of other instructions. The PHUFB will either
19605 /// use a register or have to read from memory and so is slightly (but only
19606 /// slightly) more expensive than the other shuffle instructions.
19608 /// Because this is inherently a quadratic operation (for each shuffle in
19609 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19610 /// This should never be an issue in practice as the shuffle lowering doesn't
19611 /// produce sequences of more than 8 instructions.
19613 /// FIXME: We will currently miss some cases where the redundant shuffling
19614 /// would simplify under the threshold for PSHUFB formation because of
19615 /// combine-ordering. To fix this, we should do the redundant instruction
19616 /// combining in this recursive walk.
19617 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19618 ArrayRef<int> RootMask,
19619 int Depth, bool HasPSHUFB,
19621 TargetLowering::DAGCombinerInfo &DCI,
19622 const X86Subtarget *Subtarget) {
19623 // Bound the depth of our recursive combine because this is ultimately
19624 // quadratic in nature.
19628 // Directly rip through bitcasts to find the underlying operand.
19629 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19630 Op = Op.getOperand(0);
19632 MVT VT = Op.getSimpleValueType();
19633 if (!VT.isVector())
19634 return false; // Bail if we hit a non-vector.
19635 // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19636 // version should be added.
19637 if (VT.getSizeInBits() != 128)
19640 assert(Root.getSimpleValueType().isVector() &&
19641 "Shuffles operate on vector types!");
19642 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19643 "Can only combine shuffles of the same vector register size.");
19645 if (!isTargetShuffle(Op.getOpcode()))
19647 SmallVector<int, 16> OpMask;
19649 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19650 // We only can combine unary shuffles which we can decode the mask for.
19651 if (!HaveMask || !IsUnary)
19654 assert(VT.getVectorNumElements() == OpMask.size() &&
19655 "Different mask size from vector size!");
19656 assert(((RootMask.size() > OpMask.size() &&
19657 RootMask.size() % OpMask.size() == 0) ||
19658 (OpMask.size() > RootMask.size() &&
19659 OpMask.size() % RootMask.size() == 0) ||
19660 OpMask.size() == RootMask.size()) &&
19661 "The smaller number of elements must divide the larger.");
19662 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19663 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19664 assert(((RootRatio == 1 && OpRatio == 1) ||
19665 (RootRatio == 1) != (OpRatio == 1)) &&
19666 "Must not have a ratio for both incoming and op masks!");
19668 SmallVector<int, 16> Mask;
19669 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19671 // Merge this shuffle operation's mask into our accumulated mask. Note that
19672 // this shuffle's mask will be the first applied to the input, followed by the
19673 // root mask to get us all the way to the root value arrangement. The reason
19674 // for this order is that we are recursing up the operation chain.
19675 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19676 int RootIdx = i / RootRatio;
19677 if (RootMask[RootIdx] == SM_SentinelZero) {
19678 // This is a zero-ed lane, we're done.
19679 Mask.push_back(SM_SentinelZero);
19683 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19684 int OpIdx = RootMaskedIdx / OpRatio;
19685 if (OpMask[OpIdx] == SM_SentinelZero) {
19686 // The incoming lanes are zero, it doesn't matter which ones we are using.
19687 Mask.push_back(SM_SentinelZero);
19691 // Ok, we have non-zero lanes, map them through.
19692 Mask.push_back(OpMask[OpIdx] * OpRatio +
19693 RootMaskedIdx % OpRatio);
19696 // See if we can recurse into the operand to combine more things.
19697 switch (Op.getOpcode()) {
19698 case X86ISD::PSHUFB:
19700 case X86ISD::PSHUFD:
19701 case X86ISD::PSHUFHW:
19702 case X86ISD::PSHUFLW:
19703 if (Op.getOperand(0).hasOneUse() &&
19704 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19705 HasPSHUFB, DAG, DCI, Subtarget))
19709 case X86ISD::UNPCKL:
19710 case X86ISD::UNPCKH:
19711 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19712 // We can't check for single use, we have to check that this shuffle is the only user.
19713 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19714 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19715 HasPSHUFB, DAG, DCI, Subtarget))
19720 // Minor canonicalization of the accumulated shuffle mask to make it easier
19721 // to match below. All this does is detect masks with squential pairs of
19722 // elements, and shrink them to the half-width mask. It does this in a loop
19723 // so it will reduce the size of the mask to the minimal width mask which
19724 // performs an equivalent shuffle.
19725 while (Mask.size() > 1 && canWidenShuffleElements(Mask)) {
19726 for (int i = 0, e = Mask.size() / 2; i < e; ++i)
19727 Mask[i] = Mask[2 * i] / 2;
19728 Mask.resize(Mask.size() / 2);
19731 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19735 /// \brief Get the PSHUF-style mask from PSHUF node.
19737 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19738 /// PSHUF-style masks that can be reused with such instructions.
19739 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19740 SmallVector<int, 4> Mask;
19742 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19746 switch (N.getOpcode()) {
19747 case X86ISD::PSHUFD:
19749 case X86ISD::PSHUFLW:
19752 case X86ISD::PSHUFHW:
19753 Mask.erase(Mask.begin(), Mask.begin() + 4);
19754 for (int &M : Mask)
19758 llvm_unreachable("No valid shuffle instruction found!");
19762 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19764 /// We walk up the chain and look for a combinable shuffle, skipping over
19765 /// shuffles that we could hoist this shuffle's transformation past without
19766 /// altering anything.
19768 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19770 TargetLowering::DAGCombinerInfo &DCI) {
19771 assert(N.getOpcode() == X86ISD::PSHUFD &&
19772 "Called with something other than an x86 128-bit half shuffle!");
19775 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19776 // of the shuffles in the chain so that we can form a fresh chain to replace
19778 SmallVector<SDValue, 8> Chain;
19779 SDValue V = N.getOperand(0);
19780 for (; V.hasOneUse(); V = V.getOperand(0)) {
19781 switch (V.getOpcode()) {
19783 return SDValue(); // Nothing combined!
19786 // Skip bitcasts as we always know the type for the target specific
19790 case X86ISD::PSHUFD:
19791 // Found another dword shuffle.
19794 case X86ISD::PSHUFLW:
19795 // Check that the low words (being shuffled) are the identity in the
19796 // dword shuffle, and the high words are self-contained.
19797 if (Mask[0] != 0 || Mask[1] != 1 ||
19798 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19801 Chain.push_back(V);
19804 case X86ISD::PSHUFHW:
19805 // Check that the high words (being shuffled) are the identity in the
19806 // dword shuffle, and the low words are self-contained.
19807 if (Mask[2] != 2 || Mask[3] != 3 ||
19808 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19811 Chain.push_back(V);
19814 case X86ISD::UNPCKL:
19815 case X86ISD::UNPCKH:
19816 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19817 // shuffle into a preceding word shuffle.
19818 if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19821 // Search for a half-shuffle which we can combine with.
19822 unsigned CombineOp =
19823 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19824 if (V.getOperand(0) != V.getOperand(1) ||
19825 !V->isOnlyUserOf(V.getOperand(0).getNode()))
19827 Chain.push_back(V);
19828 V = V.getOperand(0);
19830 switch (V.getOpcode()) {
19832 return SDValue(); // Nothing to combine.
19834 case X86ISD::PSHUFLW:
19835 case X86ISD::PSHUFHW:
19836 if (V.getOpcode() == CombineOp)
19839 Chain.push_back(V);
19843 V = V.getOperand(0);
19847 } while (V.hasOneUse());
19850 // Break out of the loop if we break out of the switch.
19854 if (!V.hasOneUse())
19855 // We fell out of the loop without finding a viable combining instruction.
19858 // Merge this node's mask and our incoming mask.
19859 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19860 for (int &M : Mask)
19862 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19863 getV4X86ShuffleImm8ForMask(Mask, DAG));
19865 // Rebuild the chain around this new shuffle.
19866 while (!Chain.empty()) {
19867 SDValue W = Chain.pop_back_val();
19869 if (V.getValueType() != W.getOperand(0).getValueType())
19870 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19872 switch (W.getOpcode()) {
19874 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19876 case X86ISD::UNPCKL:
19877 case X86ISD::UNPCKH:
19878 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19880 case X86ISD::PSHUFD:
19881 case X86ISD::PSHUFLW:
19882 case X86ISD::PSHUFHW:
19883 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19886 if (V.getValueType() != N.getValueType())
19887 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19889 // Return the new chain to replace N.
19893 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19895 /// We walk up the chain, skipping shuffles of the other half and looking
19896 /// through shuffles which switch halves trying to find a shuffle of the same
19897 /// pair of dwords.
19898 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19900 TargetLowering::DAGCombinerInfo &DCI) {
19902 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19903 "Called with something other than an x86 128-bit half shuffle!");
19905 unsigned CombineOpcode = N.getOpcode();
19907 // Walk up a single-use chain looking for a combinable shuffle.
19908 SDValue V = N.getOperand(0);
19909 for (; V.hasOneUse(); V = V.getOperand(0)) {
19910 switch (V.getOpcode()) {
19912 return false; // Nothing combined!
19915 // Skip bitcasts as we always know the type for the target specific
19919 case X86ISD::PSHUFLW:
19920 case X86ISD::PSHUFHW:
19921 if (V.getOpcode() == CombineOpcode)
19924 // Other-half shuffles are no-ops.
19927 // Break out of the loop if we break out of the switch.
19931 if (!V.hasOneUse())
19932 // We fell out of the loop without finding a viable combining instruction.
19935 // Combine away the bottom node as its shuffle will be accumulated into
19936 // a preceding shuffle.
19937 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19939 // Record the old value.
19942 // Merge this node's mask and our incoming mask (adjusted to account for all
19943 // the pshufd instructions encountered).
19944 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19945 for (int &M : Mask)
19947 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19948 getV4X86ShuffleImm8ForMask(Mask, DAG));
19950 // Check that the shuffles didn't cancel each other out. If not, we need to
19951 // combine to the new one.
19953 // Replace the combinable shuffle with the combined one, updating all users
19954 // so that we re-evaluate the chain here.
19955 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19960 /// \brief Try to combine x86 target specific shuffles.
19961 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19962 TargetLowering::DAGCombinerInfo &DCI,
19963 const X86Subtarget *Subtarget) {
19965 MVT VT = N.getSimpleValueType();
19966 SmallVector<int, 4> Mask;
19968 switch (N.getOpcode()) {
19969 case X86ISD::PSHUFD:
19970 case X86ISD::PSHUFLW:
19971 case X86ISD::PSHUFHW:
19972 Mask = getPSHUFShuffleMask(N);
19973 assert(Mask.size() == 4);
19979 // Nuke no-op shuffles that show up after combining.
19980 if (isNoopShuffleMask(Mask))
19981 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19983 // Look for simplifications involving one or two shuffle instructions.
19984 SDValue V = N.getOperand(0);
19985 switch (N.getOpcode()) {
19988 case X86ISD::PSHUFLW:
19989 case X86ISD::PSHUFHW:
19990 assert(VT == MVT::v8i16);
19993 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19994 return SDValue(); // We combined away this shuffle, so we're done.
19996 // See if this reduces to a PSHUFD which is no more expensive and can
19997 // combine with more operations.
19998 if (canWidenShuffleElements(Mask)) {
19999 int DMask[] = {-1, -1, -1, -1};
20000 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20001 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
20002 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
20003 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
20004 DCI.AddToWorklist(V.getNode());
20005 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
20006 getV4X86ShuffleImm8ForMask(DMask, DAG));
20007 DCI.AddToWorklist(V.getNode());
20008 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
20011 // Look for shuffle patterns which can be implemented as a single unpack.
20012 // FIXME: This doesn't handle the location of the PSHUFD generically, and
20013 // only works when we have a PSHUFD followed by two half-shuffles.
20014 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20015 (V.getOpcode() == X86ISD::PSHUFLW ||
20016 V.getOpcode() == X86ISD::PSHUFHW) &&
20017 V.getOpcode() != N.getOpcode() &&
20019 SDValue D = V.getOperand(0);
20020 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20021 D = D.getOperand(0);
20022 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20023 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20024 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20025 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20026 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20028 for (int i = 0; i < 4; ++i) {
20029 WordMask[i + NOffset] = Mask[i] + NOffset;
20030 WordMask[i + VOffset] = VMask[i] + VOffset;
20032 // Map the word mask through the DWord mask.
20034 for (int i = 0; i < 8; ++i)
20035 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20036 const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
20037 const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
20038 if (std::equal(std::begin(MappedMask), std::end(MappedMask),
20039 std::begin(UnpackLoMask)) ||
20040 std::equal(std::begin(MappedMask), std::end(MappedMask),
20041 std::begin(UnpackHiMask))) {
20042 // We can replace all three shuffles with an unpack.
20043 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
20044 DCI.AddToWorklist(V.getNode());
20045 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20047 DL, MVT::v8i16, V, V);
20054 case X86ISD::PSHUFD:
20055 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20064 /// PerformShuffleCombine - Performs several different shuffle combines.
20065 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20066 TargetLowering::DAGCombinerInfo &DCI,
20067 const X86Subtarget *Subtarget) {
20069 SDValue N0 = N->getOperand(0);
20070 SDValue N1 = N->getOperand(1);
20071 EVT VT = N->getValueType(0);
20073 // Don't create instructions with illegal types after legalize types has run.
20074 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20075 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20078 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20079 if (Subtarget->hasFp256() && VT.is256BitVector() &&
20080 N->getOpcode() == ISD::VECTOR_SHUFFLE)
20081 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20083 // During Type Legalization, when promoting illegal vector types,
20084 // the backend might introduce new shuffle dag nodes and bitcasts.
20086 // This code performs the following transformation:
20087 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20088 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20090 // We do this only if both the bitcast and the BINOP dag nodes have
20091 // one use. Also, perform this transformation only if the new binary
20092 // operation is legal. This is to avoid introducing dag nodes that
20093 // potentially need to be further expanded (or custom lowered) into a
20094 // less optimal sequence of dag nodes.
20095 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20096 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20097 N0.getOpcode() == ISD::BITCAST) {
20098 SDValue BC0 = N0.getOperand(0);
20099 EVT SVT = BC0.getValueType();
20100 unsigned Opcode = BC0.getOpcode();
20101 unsigned NumElts = VT.getVectorNumElements();
20103 if (BC0.hasOneUse() && SVT.isVector() &&
20104 SVT.getVectorNumElements() * 2 == NumElts &&
20105 TLI.isOperationLegal(Opcode, VT)) {
20106 bool CanFold = false;
20118 unsigned SVTNumElts = SVT.getVectorNumElements();
20119 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20120 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20121 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20122 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20123 CanFold = SVOp->getMaskElt(i) < 0;
20126 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20127 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20128 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20129 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20134 // Only handle 128 wide vector from here on.
20135 if (!VT.is128BitVector())
20138 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20139 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20140 // consecutive, non-overlapping, and in the right order.
20141 SmallVector<SDValue, 16> Elts;
20142 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20143 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20145 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20149 if (isTargetShuffle(N->getOpcode())) {
20151 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20152 if (Shuffle.getNode())
20155 // Try recursively combining arbitrary sequences of x86 shuffle
20156 // instructions into higher-order shuffles. We do this after combining
20157 // specific PSHUF instruction sequences into their minimal form so that we
20158 // can evaluate how many specialized shuffle instructions are involved in
20159 // a particular chain.
20160 SmallVector<int, 1> NonceMask; // Just a placeholder.
20161 NonceMask.push_back(0);
20162 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20163 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20165 return SDValue(); // This routine will use CombineTo to replace N.
20171 /// PerformTruncateCombine - Converts truncate operation to
20172 /// a sequence of vector shuffle operations.
20173 /// It is possible when we truncate 256-bit vector to 128-bit vector
20174 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20175 TargetLowering::DAGCombinerInfo &DCI,
20176 const X86Subtarget *Subtarget) {
20180 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20181 /// specific shuffle of a load can be folded into a single element load.
20182 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20183 /// shuffles have been customed lowered so we need to handle those here.
20184 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20185 TargetLowering::DAGCombinerInfo &DCI) {
20186 if (DCI.isBeforeLegalizeOps())
20189 SDValue InVec = N->getOperand(0);
20190 SDValue EltNo = N->getOperand(1);
20192 if (!isa<ConstantSDNode>(EltNo))
20195 EVT VT = InVec.getValueType();
20197 bool HasShuffleIntoBitcast = false;
20198 if (InVec.getOpcode() == ISD::BITCAST) {
20199 // Don't duplicate a load with other uses.
20200 if (!InVec.hasOneUse())
20202 EVT BCVT = InVec.getOperand(0).getValueType();
20203 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
20205 InVec = InVec.getOperand(0);
20206 HasShuffleIntoBitcast = true;
20209 if (!isTargetShuffle(InVec.getOpcode()))
20212 // Don't duplicate a load with other uses.
20213 if (!InVec.hasOneUse())
20216 SmallVector<int, 16> ShuffleMask;
20218 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
20222 // Select the input vector, guarding against out of range extract vector.
20223 unsigned NumElems = VT.getVectorNumElements();
20224 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20225 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20226 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20227 : InVec.getOperand(1);
20229 // If inputs to shuffle are the same for both ops, then allow 2 uses
20230 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20232 if (LdNode.getOpcode() == ISD::BITCAST) {
20233 // Don't duplicate a load with other uses.
20234 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20237 AllowedUses = 1; // only allow 1 load use if we have a bitcast
20238 LdNode = LdNode.getOperand(0);
20241 if (!ISD::isNormalLoad(LdNode.getNode()))
20244 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20246 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20249 if (HasShuffleIntoBitcast) {
20250 // If there's a bitcast before the shuffle, check if the load type and
20251 // alignment is valid.
20252 unsigned Align = LN0->getAlignment();
20253 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20254 unsigned NewAlign = TLI.getDataLayout()->
20255 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
20257 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
20261 // All checks match so transform back to vector_shuffle so that DAG combiner
20262 // can finish the job
20265 // Create shuffle node taking into account the case that its a unary shuffle
20266 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
20267 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
20268 InVec.getOperand(0), Shuffle,
20270 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
20271 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20275 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20276 /// generation and convert it from being a bunch of shuffles and extracts
20277 /// to a simple store and scalar loads to extract the elements.
20278 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20279 TargetLowering::DAGCombinerInfo &DCI) {
20280 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20281 if (NewOp.getNode())
20284 SDValue InputVector = N->getOperand(0);
20286 // Detect whether we are trying to convert from mmx to i32 and the bitcast
20287 // from mmx to v2i32 has a single usage.
20288 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
20289 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
20290 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
20291 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20292 N->getValueType(0),
20293 InputVector.getNode()->getOperand(0));
20295 // Only operate on vectors of 4 elements, where the alternative shuffling
20296 // gets to be more expensive.
20297 if (InputVector.getValueType() != MVT::v4i32)
20300 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20301 // single use which is a sign-extend or zero-extend, and all elements are
20303 SmallVector<SDNode *, 4> Uses;
20304 unsigned ExtractedElements = 0;
20305 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20306 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20307 if (UI.getUse().getResNo() != InputVector.getResNo())
20310 SDNode *Extract = *UI;
20311 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20314 if (Extract->getValueType(0) != MVT::i32)
20316 if (!Extract->hasOneUse())
20318 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20319 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20321 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20324 // Record which element was extracted.
20325 ExtractedElements |=
20326 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20328 Uses.push_back(Extract);
20331 // If not all the elements were used, this may not be worthwhile.
20332 if (ExtractedElements != 15)
20335 // Ok, we've now decided to do the transformation.
20336 SDLoc dl(InputVector);
20338 // Store the value to a temporary stack slot.
20339 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20340 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20341 MachinePointerInfo(), false, false, 0);
20343 // Replace each use (extract) with a load of the appropriate element.
20344 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20345 UE = Uses.end(); UI != UE; ++UI) {
20346 SDNode *Extract = *UI;
20348 // cOMpute the element's address.
20349 SDValue Idx = Extract->getOperand(1);
20351 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
20352 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
20353 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20354 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20356 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20357 StackPtr, OffsetVal);
20359 // Load the scalar.
20360 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
20361 ScalarAddr, MachinePointerInfo(),
20362 false, false, false, 0);
20364 // Replace the exact with the load.
20365 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
20368 // The replacement was made in place; don't return anything.
20372 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20373 static std::pair<unsigned, bool>
20374 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20375 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20376 if (!VT.isVector())
20377 return std::make_pair(0, false);
20379 bool NeedSplit = false;
20380 switch (VT.getSimpleVT().SimpleTy) {
20381 default: return std::make_pair(0, false);
20385 if (!Subtarget->hasAVX2())
20387 if (!Subtarget->hasAVX())
20388 return std::make_pair(0, false);
20393 if (!Subtarget->hasSSE2())
20394 return std::make_pair(0, false);
20397 // SSE2 has only a small subset of the operations.
20398 bool hasUnsigned = Subtarget->hasSSE41() ||
20399 (Subtarget->hasSSE2() && VT == MVT::v16i8);
20400 bool hasSigned = Subtarget->hasSSE41() ||
20401 (Subtarget->hasSSE2() && VT == MVT::v8i16);
20403 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20406 // Check for x CC y ? x : y.
20407 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20408 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20413 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20416 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20419 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20422 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20424 // Check for x CC y ? y : x -- a min/max with reversed arms.
20425 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20426 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20431 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20434 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20437 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20440 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20444 return std::make_pair(Opc, NeedSplit);
20448 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20449 const X86Subtarget *Subtarget) {
20451 SDValue Cond = N->getOperand(0);
20452 SDValue LHS = N->getOperand(1);
20453 SDValue RHS = N->getOperand(2);
20455 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20456 SDValue CondSrc = Cond->getOperand(0);
20457 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20458 Cond = CondSrc->getOperand(0);
20461 MVT VT = N->getSimpleValueType(0);
20462 MVT EltVT = VT.getVectorElementType();
20463 unsigned NumElems = VT.getVectorNumElements();
20464 // There is no blend with immediate in AVX-512.
20465 if (VT.is512BitVector())
20468 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
20470 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
20473 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20476 // A vselect where all conditions and data are constants can be optimized into
20477 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20478 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20479 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20482 unsigned MaskValue = 0;
20483 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20486 SmallVector<int, 8> ShuffleMask(NumElems, -1);
20487 for (unsigned i = 0; i < NumElems; ++i) {
20488 // Be sure we emit undef where we can.
20489 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20490 ShuffleMask[i] = -1;
20492 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20495 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20498 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20500 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20501 TargetLowering::DAGCombinerInfo &DCI,
20502 const X86Subtarget *Subtarget) {
20504 SDValue Cond = N->getOperand(0);
20505 // Get the LHS/RHS of the select.
20506 SDValue LHS = N->getOperand(1);
20507 SDValue RHS = N->getOperand(2);
20508 EVT VT = LHS.getValueType();
20509 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20511 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20512 // instructions match the semantics of the common C idiom x<y?x:y but not
20513 // x<=y?x:y, because of how they handle negative zero (which can be
20514 // ignored in unsafe-math mode).
20515 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20516 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20517 (Subtarget->hasSSE2() ||
20518 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20519 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20521 unsigned Opcode = 0;
20522 // Check for x CC y ? x : y.
20523 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20524 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20528 // Converting this to a min would handle NaNs incorrectly, and swapping
20529 // the operands would cause it to handle comparisons between positive
20530 // and negative zero incorrectly.
20531 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20532 if (!DAG.getTarget().Options.UnsafeFPMath &&
20533 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20535 std::swap(LHS, RHS);
20537 Opcode = X86ISD::FMIN;
20540 // Converting this to a min would handle comparisons between positive
20541 // and negative zero incorrectly.
20542 if (!DAG.getTarget().Options.UnsafeFPMath &&
20543 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20545 Opcode = X86ISD::FMIN;
20548 // Converting this to a min would handle both negative zeros and NaNs
20549 // incorrectly, but we can swap the operands to fix both.
20550 std::swap(LHS, RHS);
20554 Opcode = X86ISD::FMIN;
20558 // Converting this to a max would handle comparisons between positive
20559 // and negative zero incorrectly.
20560 if (!DAG.getTarget().Options.UnsafeFPMath &&
20561 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20563 Opcode = X86ISD::FMAX;
20566 // Converting this to a max would handle NaNs incorrectly, and swapping
20567 // the operands would cause it to handle comparisons between positive
20568 // and negative zero incorrectly.
20569 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20570 if (!DAG.getTarget().Options.UnsafeFPMath &&
20571 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20573 std::swap(LHS, RHS);
20575 Opcode = X86ISD::FMAX;
20578 // Converting this to a max would handle both negative zeros and NaNs
20579 // incorrectly, but we can swap the operands to fix both.
20580 std::swap(LHS, RHS);
20584 Opcode = X86ISD::FMAX;
20587 // Check for x CC y ? y : x -- a min/max with reversed arms.
20588 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20589 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20593 // Converting this to a min would handle comparisons between positive
20594 // and negative zero incorrectly, and swapping the operands would
20595 // cause it to handle NaNs incorrectly.
20596 if (!DAG.getTarget().Options.UnsafeFPMath &&
20597 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20598 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20600 std::swap(LHS, RHS);
20602 Opcode = X86ISD::FMIN;
20605 // Converting this to a min would handle NaNs incorrectly.
20606 if (!DAG.getTarget().Options.UnsafeFPMath &&
20607 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20609 Opcode = X86ISD::FMIN;
20612 // Converting this to a min would handle both negative zeros and NaNs
20613 // incorrectly, but we can swap the operands to fix both.
20614 std::swap(LHS, RHS);
20618 Opcode = X86ISD::FMIN;
20622 // Converting this to a max would handle NaNs incorrectly.
20623 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20625 Opcode = X86ISD::FMAX;
20628 // Converting this to a max would handle comparisons between positive
20629 // and negative zero incorrectly, and swapping the operands would
20630 // cause it to handle NaNs incorrectly.
20631 if (!DAG.getTarget().Options.UnsafeFPMath &&
20632 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20633 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20635 std::swap(LHS, RHS);
20637 Opcode = X86ISD::FMAX;
20640 // Converting this to a max would handle both negative zeros and NaNs
20641 // incorrectly, but we can swap the operands to fix both.
20642 std::swap(LHS, RHS);
20646 Opcode = X86ISD::FMAX;
20652 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20655 EVT CondVT = Cond.getValueType();
20656 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20657 CondVT.getVectorElementType() == MVT::i1) {
20658 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20659 // lowering on AVX-512. In this case we convert it to
20660 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20661 // The same situation for all 128 and 256-bit vectors of i8 and i16
20662 EVT OpVT = LHS.getValueType();
20663 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20664 (OpVT.getVectorElementType() == MVT::i8 ||
20665 OpVT.getVectorElementType() == MVT::i16)) {
20666 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20667 DCI.AddToWorklist(Cond.getNode());
20668 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20671 // If this is a select between two integer constants, try to do some
20673 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20674 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20675 // Don't do this for crazy integer types.
20676 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20677 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20678 // so that TrueC (the true value) is larger than FalseC.
20679 bool NeedsCondInvert = false;
20681 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20682 // Efficiently invertible.
20683 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
20684 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
20685 isa<ConstantSDNode>(Cond.getOperand(1))))) {
20686 NeedsCondInvert = true;
20687 std::swap(TrueC, FalseC);
20690 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
20691 if (FalseC->getAPIntValue() == 0 &&
20692 TrueC->getAPIntValue().isPowerOf2()) {
20693 if (NeedsCondInvert) // Invert the condition if needed.
20694 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20695 DAG.getConstant(1, Cond.getValueType()));
20697 // Zero extend the condition if needed.
20698 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20700 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20701 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20702 DAG.getConstant(ShAmt, MVT::i8));
20705 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20706 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20707 if (NeedsCondInvert) // Invert the condition if needed.
20708 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20709 DAG.getConstant(1, Cond.getValueType()));
20711 // Zero extend the condition if needed.
20712 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20713 FalseC->getValueType(0), Cond);
20714 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20715 SDValue(FalseC, 0));
20718 // Optimize cases that will turn into an LEA instruction. This requires
20719 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20720 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20721 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20722 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20724 bool isFastMultiplier = false;
20726 switch ((unsigned char)Diff) {
20728 case 1: // result = add base, cond
20729 case 2: // result = lea base( , cond*2)
20730 case 3: // result = lea base(cond, cond*2)
20731 case 4: // result = lea base( , cond*4)
20732 case 5: // result = lea base(cond, cond*4)
20733 case 8: // result = lea base( , cond*8)
20734 case 9: // result = lea base(cond, cond*8)
20735 isFastMultiplier = true;
20740 if (isFastMultiplier) {
20741 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20742 if (NeedsCondInvert) // Invert the condition if needed.
20743 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20744 DAG.getConstant(1, Cond.getValueType()));
20746 // Zero extend the condition if needed.
20747 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20749 // Scale the condition by the difference.
20751 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20752 DAG.getConstant(Diff, Cond.getValueType()));
20754 // Add the base if non-zero.
20755 if (FalseC->getAPIntValue() != 0)
20756 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20757 SDValue(FalseC, 0));
20764 // Canonicalize max and min:
20765 // (x > y) ? x : y -> (x >= y) ? x : y
20766 // (x < y) ? x : y -> (x <= y) ? x : y
20767 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20768 // the need for an extra compare
20769 // against zero. e.g.
20770 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20772 // testl %edi, %edi
20774 // cmovgl %edi, %eax
20778 // cmovsl %eax, %edi
20779 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20780 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20781 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20782 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20787 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20788 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20789 Cond.getOperand(0), Cond.getOperand(1), NewCC);
20790 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20795 // Early exit check
20796 if (!TLI.isTypeLegal(VT))
20799 // Match VSELECTs into subs with unsigned saturation.
20800 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20801 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20802 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20803 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20804 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20806 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20807 // left side invert the predicate to simplify logic below.
20809 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20811 CC = ISD::getSetCCInverse(CC, true);
20812 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20816 if (Other.getNode() && Other->getNumOperands() == 2 &&
20817 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20818 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20819 SDValue CondRHS = Cond->getOperand(1);
20821 // Look for a general sub with unsigned saturation first.
20822 // x >= y ? x-y : 0 --> subus x, y
20823 // x > y ? x-y : 0 --> subus x, y
20824 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20825 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20826 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20828 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20829 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20830 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20831 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20832 // If the RHS is a constant we have to reverse the const
20833 // canonicalization.
20834 // x > C-1 ? x+-C : 0 --> subus x, C
20835 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20836 CondRHSConst->getAPIntValue() ==
20837 (-OpRHSConst->getAPIntValue() - 1))
20838 return DAG.getNode(
20839 X86ISD::SUBUS, DL, VT, OpLHS,
20840 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20842 // Another special case: If C was a sign bit, the sub has been
20843 // canonicalized into a xor.
20844 // FIXME: Would it be better to use computeKnownBits to determine
20845 // whether it's safe to decanonicalize the xor?
20846 // x s< 0 ? x^C : 0 --> subus x, C
20847 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20848 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20849 OpRHSConst->getAPIntValue().isSignBit())
20850 // Note that we have to rebuild the RHS constant here to ensure we
20851 // don't rely on particular values of undef lanes.
20852 return DAG.getNode(
20853 X86ISD::SUBUS, DL, VT, OpLHS,
20854 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20859 // Try to match a min/max vector operation.
20860 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20861 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20862 unsigned Opc = ret.first;
20863 bool NeedSplit = ret.second;
20865 if (Opc && NeedSplit) {
20866 unsigned NumElems = VT.getVectorNumElements();
20867 // Extract the LHS vectors
20868 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20869 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20871 // Extract the RHS vectors
20872 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20873 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20875 // Create min/max for each subvector
20876 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20877 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20879 // Merge the result
20880 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20882 return DAG.getNode(Opc, DL, VT, LHS, RHS);
20885 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20886 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20887 // Check if SETCC has already been promoted
20888 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20889 // Check that condition value type matches vselect operand type
20892 assert(Cond.getValueType().isVector() &&
20893 "vector select expects a vector selector!");
20895 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20896 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20898 if (!TValIsAllOnes && !FValIsAllZeros) {
20899 // Try invert the condition if true value is not all 1s and false value
20901 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20902 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20904 if (TValIsAllZeros || FValIsAllOnes) {
20905 SDValue CC = Cond.getOperand(2);
20906 ISD::CondCode NewCC =
20907 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20908 Cond.getOperand(0).getValueType().isInteger());
20909 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20910 std::swap(LHS, RHS);
20911 TValIsAllOnes = FValIsAllOnes;
20912 FValIsAllZeros = TValIsAllZeros;
20916 if (TValIsAllOnes || FValIsAllZeros) {
20919 if (TValIsAllOnes && FValIsAllZeros)
20921 else if (TValIsAllOnes)
20922 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20923 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20924 else if (FValIsAllZeros)
20925 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20926 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20928 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20932 // Try to fold this VSELECT into a MOVSS/MOVSD
20933 if (N->getOpcode() == ISD::VSELECT &&
20934 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20935 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20936 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20937 bool CanFold = false;
20938 unsigned NumElems = Cond.getNumOperands();
20942 if (isZero(Cond.getOperand(0))) {
20945 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20946 // fold (vselect <0,-1> -> (movsd A, B)
20947 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20948 CanFold = isAllOnes(Cond.getOperand(i));
20949 } else if (isAllOnes(Cond.getOperand(0))) {
20953 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20954 // fold (vselect <-1,0> -> (movsd B, A)
20955 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20956 CanFold = isZero(Cond.getOperand(i));
20960 if (VT == MVT::v4i32 || VT == MVT::v4f32)
20961 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20962 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20965 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20966 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20967 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20968 // (v2i64 (bitcast B)))))
20970 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20971 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20972 // (v2f64 (bitcast B)))))
20974 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20975 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20976 // (v2i64 (bitcast A)))))
20978 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20979 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20980 // (v2f64 (bitcast A)))))
20982 CanFold = (isZero(Cond.getOperand(0)) &&
20983 isZero(Cond.getOperand(1)) &&
20984 isAllOnes(Cond.getOperand(2)) &&
20985 isAllOnes(Cond.getOperand(3)));
20987 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20988 isAllOnes(Cond.getOperand(1)) &&
20989 isZero(Cond.getOperand(2)) &&
20990 isZero(Cond.getOperand(3))) {
20992 std::swap(LHS, RHS);
20996 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20997 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20998 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20999 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
21001 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
21007 // If we know that this node is legal then we know that it is going to be
21008 // matched by one of the SSE/AVX BLEND instructions. These instructions only
21009 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
21010 // to simplify previous instructions.
21011 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21012 !DCI.isBeforeLegalize() &&
21013 // We explicitly check against v8i16 and v16i16 because, although
21014 // they're marked as Custom, they might only be legal when Cond is a
21015 // build_vector of constants. This will be taken care in a later
21017 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
21018 VT != MVT::v8i16)) {
21019 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21021 // Don't optimize vector selects that map to mask-registers.
21025 // Check all uses of that condition operand to check whether it will be
21026 // consumed by non-BLEND instructions, which may depend on all bits are set
21028 for (SDNode::use_iterator I = Cond->use_begin(),
21029 E = Cond->use_end(); I != E; ++I)
21030 if (I->getOpcode() != ISD::VSELECT)
21031 // TODO: Add other opcodes eventually lowered into BLEND.
21034 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21035 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21037 APInt KnownZero, KnownOne;
21038 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21039 DCI.isBeforeLegalizeOps());
21040 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21041 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
21042 DCI.CommitTargetLoweringOpt(TLO);
21045 // We should generate an X86ISD::BLENDI from a vselect if its argument
21046 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21047 // constants. This specific pattern gets generated when we split a
21048 // selector for a 512 bit vector in a machine without AVX512 (but with
21049 // 256-bit vectors), during legalization:
21051 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21053 // Iff we find this pattern and the build_vectors are built from
21054 // constants, we translate the vselect into a shuffle_vector that we
21055 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21056 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
21057 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21058 if (Shuffle.getNode())
21065 // Check whether a boolean test is testing a boolean value generated by
21066 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21069 // Simplify the following patterns:
21070 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21071 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21072 // to (Op EFLAGS Cond)
21074 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21075 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21076 // to (Op EFLAGS !Cond)
21078 // where Op could be BRCOND or CMOV.
21080 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21081 // Quit if not CMP and SUB with its value result used.
21082 if (Cmp.getOpcode() != X86ISD::CMP &&
21083 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21086 // Quit if not used as a boolean value.
21087 if (CC != X86::COND_E && CC != X86::COND_NE)
21090 // Check CMP operands. One of them should be 0 or 1 and the other should be
21091 // an SetCC or extended from it.
21092 SDValue Op1 = Cmp.getOperand(0);
21093 SDValue Op2 = Cmp.getOperand(1);
21096 const ConstantSDNode* C = nullptr;
21097 bool needOppositeCond = (CC == X86::COND_E);
21098 bool checkAgainstTrue = false; // Is it a comparison against 1?
21100 if ((C = dyn_cast<ConstantSDNode>(Op1)))
21102 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21104 else // Quit if all operands are not constants.
21107 if (C->getZExtValue() == 1) {
21108 needOppositeCond = !needOppositeCond;
21109 checkAgainstTrue = true;
21110 } else if (C->getZExtValue() != 0)
21111 // Quit if the constant is neither 0 or 1.
21114 bool truncatedToBoolWithAnd = false;
21115 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21116 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21117 SetCC.getOpcode() == ISD::TRUNCATE ||
21118 SetCC.getOpcode() == ISD::AND) {
21119 if (SetCC.getOpcode() == ISD::AND) {
21121 ConstantSDNode *CS;
21122 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21123 CS->getZExtValue() == 1)
21125 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21126 CS->getZExtValue() == 1)
21130 SetCC = SetCC.getOperand(OpIdx);
21131 truncatedToBoolWithAnd = true;
21133 SetCC = SetCC.getOperand(0);
21136 switch (SetCC.getOpcode()) {
21137 case X86ISD::SETCC_CARRY:
21138 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21139 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21140 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21141 // truncated to i1 using 'and'.
21142 if (checkAgainstTrue && !truncatedToBoolWithAnd)
21144 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21145 "Invalid use of SETCC_CARRY!");
21147 case X86ISD::SETCC:
21148 // Set the condition code or opposite one if necessary.
21149 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21150 if (needOppositeCond)
21151 CC = X86::GetOppositeBranchCondition(CC);
21152 return SetCC.getOperand(1);
21153 case X86ISD::CMOV: {
21154 // Check whether false/true value has canonical one, i.e. 0 or 1.
21155 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21156 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21157 // Quit if true value is not a constant.
21160 // Quit if false value is not a constant.
21162 SDValue Op = SetCC.getOperand(0);
21163 // Skip 'zext' or 'trunc' node.
21164 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21165 Op.getOpcode() == ISD::TRUNCATE)
21166 Op = Op.getOperand(0);
21167 // A special case for rdrand/rdseed, where 0 is set if false cond is
21169 if ((Op.getOpcode() != X86ISD::RDRAND &&
21170 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21173 // Quit if false value is not the constant 0 or 1.
21174 bool FValIsFalse = true;
21175 if (FVal && FVal->getZExtValue() != 0) {
21176 if (FVal->getZExtValue() != 1)
21178 // If FVal is 1, opposite cond is needed.
21179 needOppositeCond = !needOppositeCond;
21180 FValIsFalse = false;
21182 // Quit if TVal is not the constant opposite of FVal.
21183 if (FValIsFalse && TVal->getZExtValue() != 1)
21185 if (!FValIsFalse && TVal->getZExtValue() != 0)
21187 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21188 if (needOppositeCond)
21189 CC = X86::GetOppositeBranchCondition(CC);
21190 return SetCC.getOperand(3);
21197 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21198 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21199 TargetLowering::DAGCombinerInfo &DCI,
21200 const X86Subtarget *Subtarget) {
21203 // If the flag operand isn't dead, don't touch this CMOV.
21204 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21207 SDValue FalseOp = N->getOperand(0);
21208 SDValue TrueOp = N->getOperand(1);
21209 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21210 SDValue Cond = N->getOperand(3);
21212 if (CC == X86::COND_E || CC == X86::COND_NE) {
21213 switch (Cond.getOpcode()) {
21217 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21218 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21219 return (CC == X86::COND_E) ? FalseOp : TrueOp;
21225 Flags = checkBoolTestSetCCCombine(Cond, CC);
21226 if (Flags.getNode() &&
21227 // Extra check as FCMOV only supports a subset of X86 cond.
21228 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21229 SDValue Ops[] = { FalseOp, TrueOp,
21230 DAG.getConstant(CC, MVT::i8), Flags };
21231 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21234 // If this is a select between two integer constants, try to do some
21235 // optimizations. Note that the operands are ordered the opposite of SELECT
21237 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21238 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21239 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21240 // larger than FalseC (the false value).
21241 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21242 CC = X86::GetOppositeBranchCondition(CC);
21243 std::swap(TrueC, FalseC);
21244 std::swap(TrueOp, FalseOp);
21247 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
21248 // This is efficient for any integer data type (including i8/i16) and
21250 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21251 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21252 DAG.getConstant(CC, MVT::i8), Cond);
21254 // Zero extend the condition if needed.
21255 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21257 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21258 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21259 DAG.getConstant(ShAmt, MVT::i8));
21260 if (N->getNumValues() == 2) // Dead flag value?
21261 return DCI.CombineTo(N, Cond, SDValue());
21265 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
21266 // for any integer data type, including i8/i16.
21267 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21268 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21269 DAG.getConstant(CC, MVT::i8), Cond);
21271 // Zero extend the condition if needed.
21272 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21273 FalseC->getValueType(0), Cond);
21274 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21275 SDValue(FalseC, 0));
21277 if (N->getNumValues() == 2) // Dead flag value?
21278 return DCI.CombineTo(N, Cond, SDValue());
21282 // Optimize cases that will turn into an LEA instruction. This requires
21283 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21284 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21285 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21286 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21288 bool isFastMultiplier = false;
21290 switch ((unsigned char)Diff) {
21292 case 1: // result = add base, cond
21293 case 2: // result = lea base( , cond*2)
21294 case 3: // result = lea base(cond, cond*2)
21295 case 4: // result = lea base( , cond*4)
21296 case 5: // result = lea base(cond, cond*4)
21297 case 8: // result = lea base( , cond*8)
21298 case 9: // result = lea base(cond, cond*8)
21299 isFastMultiplier = true;
21304 if (isFastMultiplier) {
21305 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21306 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21307 DAG.getConstant(CC, MVT::i8), Cond);
21308 // Zero extend the condition if needed.
21309 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21311 // Scale the condition by the difference.
21313 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21314 DAG.getConstant(Diff, Cond.getValueType()));
21316 // Add the base if non-zero.
21317 if (FalseC->getAPIntValue() != 0)
21318 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21319 SDValue(FalseC, 0));
21320 if (N->getNumValues() == 2) // Dead flag value?
21321 return DCI.CombineTo(N, Cond, SDValue());
21328 // Handle these cases:
21329 // (select (x != c), e, c) -> select (x != c), e, x),
21330 // (select (x == c), c, e) -> select (x == c), x, e)
21331 // where the c is an integer constant, and the "select" is the combination
21332 // of CMOV and CMP.
21334 // The rationale for this change is that the conditional-move from a constant
21335 // needs two instructions, however, conditional-move from a register needs
21336 // only one instruction.
21338 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21339 // some instruction-combining opportunities. This opt needs to be
21340 // postponed as late as possible.
21342 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21343 // the DCI.xxxx conditions are provided to postpone the optimization as
21344 // late as possible.
21346 ConstantSDNode *CmpAgainst = nullptr;
21347 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21348 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21349 !isa<ConstantSDNode>(Cond.getOperand(0))) {
21351 if (CC == X86::COND_NE &&
21352 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21353 CC = X86::GetOppositeBranchCondition(CC);
21354 std::swap(TrueOp, FalseOp);
21357 if (CC == X86::COND_E &&
21358 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21359 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21360 DAG.getConstant(CC, MVT::i8), Cond };
21361 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21369 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21370 const X86Subtarget *Subtarget) {
21371 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21373 default: return SDValue();
21374 // SSE/AVX/AVX2 blend intrinsics.
21375 case Intrinsic::x86_avx2_pblendvb:
21376 case Intrinsic::x86_avx2_pblendw:
21377 case Intrinsic::x86_avx2_pblendd_128:
21378 case Intrinsic::x86_avx2_pblendd_256:
21379 // Don't try to simplify this intrinsic if we don't have AVX2.
21380 if (!Subtarget->hasAVX2())
21383 case Intrinsic::x86_avx_blend_pd_256:
21384 case Intrinsic::x86_avx_blend_ps_256:
21385 case Intrinsic::x86_avx_blendv_pd_256:
21386 case Intrinsic::x86_avx_blendv_ps_256:
21387 // Don't try to simplify this intrinsic if we don't have AVX.
21388 if (!Subtarget->hasAVX())
21391 case Intrinsic::x86_sse41_pblendw:
21392 case Intrinsic::x86_sse41_blendpd:
21393 case Intrinsic::x86_sse41_blendps:
21394 case Intrinsic::x86_sse41_blendvps:
21395 case Intrinsic::x86_sse41_blendvpd:
21396 case Intrinsic::x86_sse41_pblendvb: {
21397 SDValue Op0 = N->getOperand(1);
21398 SDValue Op1 = N->getOperand(2);
21399 SDValue Mask = N->getOperand(3);
21401 // Don't try to simplify this intrinsic if we don't have SSE4.1.
21402 if (!Subtarget->hasSSE41())
21405 // fold (blend A, A, Mask) -> A
21408 // fold (blend A, B, allZeros) -> A
21409 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21411 // fold (blend A, B, allOnes) -> B
21412 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21415 // Simplify the case where the mask is a constant i32 value.
21416 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21417 if (C->isNullValue())
21419 if (C->isAllOnesValue())
21426 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21427 case Intrinsic::x86_sse2_psrai_w:
21428 case Intrinsic::x86_sse2_psrai_d:
21429 case Intrinsic::x86_avx2_psrai_w:
21430 case Intrinsic::x86_avx2_psrai_d:
21431 case Intrinsic::x86_sse2_psra_w:
21432 case Intrinsic::x86_sse2_psra_d:
21433 case Intrinsic::x86_avx2_psra_w:
21434 case Intrinsic::x86_avx2_psra_d: {
21435 SDValue Op0 = N->getOperand(1);
21436 SDValue Op1 = N->getOperand(2);
21437 EVT VT = Op0.getValueType();
21438 assert(VT.isVector() && "Expected a vector type!");
21440 if (isa<BuildVectorSDNode>(Op1))
21441 Op1 = Op1.getOperand(0);
21443 if (!isa<ConstantSDNode>(Op1))
21446 EVT SVT = VT.getVectorElementType();
21447 unsigned SVTBits = SVT.getSizeInBits();
21449 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21450 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21451 uint64_t ShAmt = C.getZExtValue();
21453 // Don't try to convert this shift into a ISD::SRA if the shift
21454 // count is bigger than or equal to the element size.
21455 if (ShAmt >= SVTBits)
21458 // Trivial case: if the shift count is zero, then fold this
21459 // into the first operand.
21463 // Replace this packed shift intrinsic with a target independent
21465 SDValue Splat = DAG.getConstant(C, VT);
21466 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21471 /// PerformMulCombine - Optimize a single multiply with constant into two
21472 /// in order to implement it with two cheaper instructions, e.g.
21473 /// LEA + SHL, LEA + LEA.
21474 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21475 TargetLowering::DAGCombinerInfo &DCI) {
21476 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21479 EVT VT = N->getValueType(0);
21480 if (VT != MVT::i64)
21483 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21486 uint64_t MulAmt = C->getZExtValue();
21487 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21490 uint64_t MulAmt1 = 0;
21491 uint64_t MulAmt2 = 0;
21492 if ((MulAmt % 9) == 0) {
21494 MulAmt2 = MulAmt / 9;
21495 } else if ((MulAmt % 5) == 0) {
21497 MulAmt2 = MulAmt / 5;
21498 } else if ((MulAmt % 3) == 0) {
21500 MulAmt2 = MulAmt / 3;
21503 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21506 if (isPowerOf2_64(MulAmt2) &&
21507 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21508 // If second multiplifer is pow2, issue it first. We want the multiply by
21509 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21511 std::swap(MulAmt1, MulAmt2);
21514 if (isPowerOf2_64(MulAmt1))
21515 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21516 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21518 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21519 DAG.getConstant(MulAmt1, VT));
21521 if (isPowerOf2_64(MulAmt2))
21522 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21523 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21525 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21526 DAG.getConstant(MulAmt2, VT));
21528 // Do not add new nodes to DAG combiner worklist.
21529 DCI.CombineTo(N, NewMul, false);
21534 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21535 SDValue N0 = N->getOperand(0);
21536 SDValue N1 = N->getOperand(1);
21537 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21538 EVT VT = N0.getValueType();
21540 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21541 // since the result of setcc_c is all zero's or all ones.
21542 if (VT.isInteger() && !VT.isVector() &&
21543 N1C && N0.getOpcode() == ISD::AND &&
21544 N0.getOperand(1).getOpcode() == ISD::Constant) {
21545 SDValue N00 = N0.getOperand(0);
21546 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21547 ((N00.getOpcode() == ISD::ANY_EXTEND ||
21548 N00.getOpcode() == ISD::ZERO_EXTEND) &&
21549 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21550 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21551 APInt ShAmt = N1C->getAPIntValue();
21552 Mask = Mask.shl(ShAmt);
21554 return DAG.getNode(ISD::AND, SDLoc(N), VT,
21555 N00, DAG.getConstant(Mask, VT));
21559 // Hardware support for vector shifts is sparse which makes us scalarize the
21560 // vector operations in many cases. Also, on sandybridge ADD is faster than
21562 // (shl V, 1) -> add V,V
21563 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21564 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21565 assert(N0.getValueType().isVector() && "Invalid vector shift type");
21566 // We shift all of the values by one. In many cases we do not have
21567 // hardware support for this operation. This is better expressed as an ADD
21569 if (N1SplatC->getZExtValue() == 1)
21570 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21576 /// \brief Returns a vector of 0s if the node in input is a vector logical
21577 /// shift by a constant amount which is known to be bigger than or equal
21578 /// to the vector element size in bits.
21579 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21580 const X86Subtarget *Subtarget) {
21581 EVT VT = N->getValueType(0);
21583 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21584 (!Subtarget->hasInt256() ||
21585 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21588 SDValue Amt = N->getOperand(1);
21590 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21591 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21592 APInt ShiftAmt = AmtSplat->getAPIntValue();
21593 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21595 // SSE2/AVX2 logical shifts always return a vector of 0s
21596 // if the shift amount is bigger than or equal to
21597 // the element size. The constant shift amount will be
21598 // encoded as a 8-bit immediate.
21599 if (ShiftAmt.trunc(8).uge(MaxAmount))
21600 return getZeroVector(VT, Subtarget, DAG, DL);
21606 /// PerformShiftCombine - Combine shifts.
21607 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21608 TargetLowering::DAGCombinerInfo &DCI,
21609 const X86Subtarget *Subtarget) {
21610 if (N->getOpcode() == ISD::SHL) {
21611 SDValue V = PerformSHLCombine(N, DAG);
21612 if (V.getNode()) return V;
21615 if (N->getOpcode() != ISD::SRA) {
21616 // Try to fold this logical shift into a zero vector.
21617 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21618 if (V.getNode()) return V;
21624 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
21625 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21626 // and friends. Likewise for OR -> CMPNEQSS.
21627 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21628 TargetLowering::DAGCombinerInfo &DCI,
21629 const X86Subtarget *Subtarget) {
21632 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21633 // we're requiring SSE2 for both.
21634 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21635 SDValue N0 = N->getOperand(0);
21636 SDValue N1 = N->getOperand(1);
21637 SDValue CMP0 = N0->getOperand(1);
21638 SDValue CMP1 = N1->getOperand(1);
21641 // The SETCCs should both refer to the same CMP.
21642 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21645 SDValue CMP00 = CMP0->getOperand(0);
21646 SDValue CMP01 = CMP0->getOperand(1);
21647 EVT VT = CMP00.getValueType();
21649 if (VT == MVT::f32 || VT == MVT::f64) {
21650 bool ExpectingFlags = false;
21651 // Check for any users that want flags:
21652 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21653 !ExpectingFlags && UI != UE; ++UI)
21654 switch (UI->getOpcode()) {
21659 ExpectingFlags = true;
21661 case ISD::CopyToReg:
21662 case ISD::SIGN_EXTEND:
21663 case ISD::ZERO_EXTEND:
21664 case ISD::ANY_EXTEND:
21668 if (!ExpectingFlags) {
21669 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21670 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21672 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21673 X86::CondCode tmp = cc0;
21678 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
21679 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21680 // FIXME: need symbolic constants for these magic numbers.
21681 // See X86ATTInstPrinter.cpp:printSSECC().
21682 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21683 if (Subtarget->hasAVX512()) {
21684 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21685 CMP01, DAG.getConstant(x86cc, MVT::i8));
21686 if (N->getValueType(0) != MVT::i1)
21687 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21691 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21692 CMP00.getValueType(), CMP00, CMP01,
21693 DAG.getConstant(x86cc, MVT::i8));
21695 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21696 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21698 if (is64BitFP && !Subtarget->is64Bit()) {
21699 // On a 32-bit target, we cannot bitcast the 64-bit float to a
21700 // 64-bit integer, since that's not a legal type. Since
21701 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21702 // bits, but can do this little dance to extract the lowest 32 bits
21703 // and work with those going forward.
21704 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21706 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21708 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21709 Vector32, DAG.getIntPtrConstant(0));
21713 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21714 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21715 DAG.getConstant(1, IntVT));
21716 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21717 return OneBitOfTruth;
21725 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21726 /// so it can be folded inside ANDNP.
21727 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21728 EVT VT = N->getValueType(0);
21730 // Match direct AllOnes for 128 and 256-bit vectors
21731 if (ISD::isBuildVectorAllOnes(N))
21734 // Look through a bit convert.
21735 if (N->getOpcode() == ISD::BITCAST)
21736 N = N->getOperand(0).getNode();
21738 // Sometimes the operand may come from a insert_subvector building a 256-bit
21740 if (VT.is256BitVector() &&
21741 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21742 SDValue V1 = N->getOperand(0);
21743 SDValue V2 = N->getOperand(1);
21745 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21746 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21747 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21748 ISD::isBuildVectorAllOnes(V2.getNode()))
21755 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21756 // register. In most cases we actually compare or select YMM-sized registers
21757 // and mixing the two types creates horrible code. This method optimizes
21758 // some of the transition sequences.
21759 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21760 TargetLowering::DAGCombinerInfo &DCI,
21761 const X86Subtarget *Subtarget) {
21762 EVT VT = N->getValueType(0);
21763 if (!VT.is256BitVector())
21766 assert((N->getOpcode() == ISD::ANY_EXTEND ||
21767 N->getOpcode() == ISD::ZERO_EXTEND ||
21768 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21770 SDValue Narrow = N->getOperand(0);
21771 EVT NarrowVT = Narrow->getValueType(0);
21772 if (!NarrowVT.is128BitVector())
21775 if (Narrow->getOpcode() != ISD::XOR &&
21776 Narrow->getOpcode() != ISD::AND &&
21777 Narrow->getOpcode() != ISD::OR)
21780 SDValue N0 = Narrow->getOperand(0);
21781 SDValue N1 = Narrow->getOperand(1);
21784 // The Left side has to be a trunc.
21785 if (N0.getOpcode() != ISD::TRUNCATE)
21788 // The type of the truncated inputs.
21789 EVT WideVT = N0->getOperand(0)->getValueType(0);
21793 // The right side has to be a 'trunc' or a constant vector.
21794 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21795 ConstantSDNode *RHSConstSplat = nullptr;
21796 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21797 RHSConstSplat = RHSBV->getConstantSplatNode();
21798 if (!RHSTrunc && !RHSConstSplat)
21801 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21803 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21806 // Set N0 and N1 to hold the inputs to the new wide operation.
21807 N0 = N0->getOperand(0);
21808 if (RHSConstSplat) {
21809 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21810 SDValue(RHSConstSplat, 0));
21811 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21812 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21813 } else if (RHSTrunc) {
21814 N1 = N1->getOperand(0);
21817 // Generate the wide operation.
21818 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21819 unsigned Opcode = N->getOpcode();
21821 case ISD::ANY_EXTEND:
21823 case ISD::ZERO_EXTEND: {
21824 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21825 APInt Mask = APInt::getAllOnesValue(InBits);
21826 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21827 return DAG.getNode(ISD::AND, DL, VT,
21828 Op, DAG.getConstant(Mask, VT));
21830 case ISD::SIGN_EXTEND:
21831 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21832 Op, DAG.getValueType(NarrowVT));
21834 llvm_unreachable("Unexpected opcode");
21838 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21839 TargetLowering::DAGCombinerInfo &DCI,
21840 const X86Subtarget *Subtarget) {
21841 EVT VT = N->getValueType(0);
21842 if (DCI.isBeforeLegalizeOps())
21845 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21849 // Create BEXTR instructions
21850 // BEXTR is ((X >> imm) & (2**size-1))
21851 if (VT == MVT::i32 || VT == MVT::i64) {
21852 SDValue N0 = N->getOperand(0);
21853 SDValue N1 = N->getOperand(1);
21856 // Check for BEXTR.
21857 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21858 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21859 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21860 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21861 if (MaskNode && ShiftNode) {
21862 uint64_t Mask = MaskNode->getZExtValue();
21863 uint64_t Shift = ShiftNode->getZExtValue();
21864 if (isMask_64(Mask)) {
21865 uint64_t MaskSize = CountPopulation_64(Mask);
21866 if (Shift + MaskSize <= VT.getSizeInBits())
21867 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21868 DAG.getConstant(Shift | (MaskSize << 8), VT));
21876 // Want to form ANDNP nodes:
21877 // 1) In the hopes of then easily combining them with OR and AND nodes
21878 // to form PBLEND/PSIGN.
21879 // 2) To match ANDN packed intrinsics
21880 if (VT != MVT::v2i64 && VT != MVT::v4i64)
21883 SDValue N0 = N->getOperand(0);
21884 SDValue N1 = N->getOperand(1);
21887 // Check LHS for vnot
21888 if (N0.getOpcode() == ISD::XOR &&
21889 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21890 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21891 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21893 // Check RHS for vnot
21894 if (N1.getOpcode() == ISD::XOR &&
21895 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21896 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21897 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21902 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21903 TargetLowering::DAGCombinerInfo &DCI,
21904 const X86Subtarget *Subtarget) {
21905 if (DCI.isBeforeLegalizeOps())
21908 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21912 SDValue N0 = N->getOperand(0);
21913 SDValue N1 = N->getOperand(1);
21914 EVT VT = N->getValueType(0);
21916 // look for psign/blend
21917 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21918 if (!Subtarget->hasSSSE3() ||
21919 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21922 // Canonicalize pandn to RHS
21923 if (N0.getOpcode() == X86ISD::ANDNP)
21925 // or (and (m, y), (pandn m, x))
21926 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21927 SDValue Mask = N1.getOperand(0);
21928 SDValue X = N1.getOperand(1);
21930 if (N0.getOperand(0) == Mask)
21931 Y = N0.getOperand(1);
21932 if (N0.getOperand(1) == Mask)
21933 Y = N0.getOperand(0);
21935 // Check to see if the mask appeared in both the AND and ANDNP and
21939 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21940 // Look through mask bitcast.
21941 if (Mask.getOpcode() == ISD::BITCAST)
21942 Mask = Mask.getOperand(0);
21943 if (X.getOpcode() == ISD::BITCAST)
21944 X = X.getOperand(0);
21945 if (Y.getOpcode() == ISD::BITCAST)
21946 Y = Y.getOperand(0);
21948 EVT MaskVT = Mask.getValueType();
21950 // Validate that the Mask operand is a vector sra node.
21951 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21952 // there is no psrai.b
21953 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21954 unsigned SraAmt = ~0;
21955 if (Mask.getOpcode() == ISD::SRA) {
21956 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21957 if (auto *AmtConst = AmtBV->getConstantSplatNode())
21958 SraAmt = AmtConst->getZExtValue();
21959 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21960 SDValue SraC = Mask.getOperand(1);
21961 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
21963 if ((SraAmt + 1) != EltBits)
21968 // Now we know we at least have a plendvb with the mask val. See if
21969 // we can form a psignb/w/d.
21970 // psign = x.type == y.type == mask.type && y = sub(0, x);
21971 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21972 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21973 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21974 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21975 "Unsupported VT for PSIGN");
21976 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21977 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21979 // PBLENDVB only available on SSE 4.1
21980 if (!Subtarget->hasSSE41())
21983 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21985 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21986 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21987 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21988 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21989 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21993 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21996 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21997 MachineFunction &MF = DAG.getMachineFunction();
21998 bool OptForSize = MF.getFunction()->getAttributes().
21999 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
22001 // SHLD/SHRD instructions have lower register pressure, but on some
22002 // platforms they have higher latency than the equivalent
22003 // series of shifts/or that would otherwise be generated.
22004 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22005 // have higher latencies and we are not optimizing for size.
22006 if (!OptForSize && Subtarget->isSHLDSlow())
22009 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22011 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22013 if (!N0.hasOneUse() || !N1.hasOneUse())
22016 SDValue ShAmt0 = N0.getOperand(1);
22017 if (ShAmt0.getValueType() != MVT::i8)
22019 SDValue ShAmt1 = N1.getOperand(1);
22020 if (ShAmt1.getValueType() != MVT::i8)
22022 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22023 ShAmt0 = ShAmt0.getOperand(0);
22024 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22025 ShAmt1 = ShAmt1.getOperand(0);
22028 unsigned Opc = X86ISD::SHLD;
22029 SDValue Op0 = N0.getOperand(0);
22030 SDValue Op1 = N1.getOperand(0);
22031 if (ShAmt0.getOpcode() == ISD::SUB) {
22032 Opc = X86ISD::SHRD;
22033 std::swap(Op0, Op1);
22034 std::swap(ShAmt0, ShAmt1);
22037 unsigned Bits = VT.getSizeInBits();
22038 if (ShAmt1.getOpcode() == ISD::SUB) {
22039 SDValue Sum = ShAmt1.getOperand(0);
22040 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22041 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22042 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22043 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22044 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22045 return DAG.getNode(Opc, DL, VT,
22047 DAG.getNode(ISD::TRUNCATE, DL,
22050 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22051 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22053 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22054 return DAG.getNode(Opc, DL, VT,
22055 N0.getOperand(0), N1.getOperand(0),
22056 DAG.getNode(ISD::TRUNCATE, DL,
22063 // Generate NEG and CMOV for integer abs.
22064 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22065 EVT VT = N->getValueType(0);
22067 // Since X86 does not have CMOV for 8-bit integer, we don't convert
22068 // 8-bit integer abs to NEG and CMOV.
22069 if (VT.isInteger() && VT.getSizeInBits() == 8)
22072 SDValue N0 = N->getOperand(0);
22073 SDValue N1 = N->getOperand(1);
22076 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22077 // and change it to SUB and CMOV.
22078 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22079 N0.getOpcode() == ISD::ADD &&
22080 N0.getOperand(1) == N1 &&
22081 N1.getOpcode() == ISD::SRA &&
22082 N1.getOperand(0) == N0.getOperand(0))
22083 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22084 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22085 // Generate SUB & CMOV.
22086 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22087 DAG.getConstant(0, VT), N0.getOperand(0));
22089 SDValue Ops[] = { N0.getOperand(0), Neg,
22090 DAG.getConstant(X86::COND_GE, MVT::i8),
22091 SDValue(Neg.getNode(), 1) };
22092 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22097 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22098 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22099 TargetLowering::DAGCombinerInfo &DCI,
22100 const X86Subtarget *Subtarget) {
22101 if (DCI.isBeforeLegalizeOps())
22104 if (Subtarget->hasCMov()) {
22105 SDValue RV = performIntegerAbsCombine(N, DAG);
22113 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22114 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22115 TargetLowering::DAGCombinerInfo &DCI,
22116 const X86Subtarget *Subtarget) {
22117 LoadSDNode *Ld = cast<LoadSDNode>(N);
22118 EVT RegVT = Ld->getValueType(0);
22119 EVT MemVT = Ld->getMemoryVT();
22121 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22123 // On Sandybridge unaligned 256bit loads are inefficient.
22124 ISD::LoadExtType Ext = Ld->getExtensionType();
22125 unsigned Alignment = Ld->getAlignment();
22126 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22127 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
22128 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22129 unsigned NumElems = RegVT.getVectorNumElements();
22133 SDValue Ptr = Ld->getBasePtr();
22134 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22136 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22138 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22139 Ld->getPointerInfo(), Ld->isVolatile(),
22140 Ld->isNonTemporal(), Ld->isInvariant(),
22142 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22143 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22144 Ld->getPointerInfo(), Ld->isVolatile(),
22145 Ld->isNonTemporal(), Ld->isInvariant(),
22146 std::min(16U, Alignment));
22147 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22149 Load2.getValue(1));
22151 SDValue NewVec = DAG.getUNDEF(RegVT);
22152 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22153 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22154 return DCI.CombineTo(N, NewVec, TF, true);
22160 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22161 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22162 const X86Subtarget *Subtarget) {
22163 StoreSDNode *St = cast<StoreSDNode>(N);
22164 EVT VT = St->getValue().getValueType();
22165 EVT StVT = St->getMemoryVT();
22167 SDValue StoredVal = St->getOperand(1);
22168 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22170 // If we are saving a concatenation of two XMM registers, perform two stores.
22171 // On Sandy Bridge, 256-bit memory operations are executed by two
22172 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
22173 // memory operation.
22174 unsigned Alignment = St->getAlignment();
22175 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22176 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
22177 StVT == VT && !IsAligned) {
22178 unsigned NumElems = VT.getVectorNumElements();
22182 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22183 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22185 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22186 SDValue Ptr0 = St->getBasePtr();
22187 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22189 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22190 St->getPointerInfo(), St->isVolatile(),
22191 St->isNonTemporal(), Alignment);
22192 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22193 St->getPointerInfo(), St->isVolatile(),
22194 St->isNonTemporal(),
22195 std::min(16U, Alignment));
22196 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22199 // Optimize trunc store (of multiple scalars) to shuffle and store.
22200 // First, pack all of the elements in one place. Next, store to memory
22201 // in fewer chunks.
22202 if (St->isTruncatingStore() && VT.isVector()) {
22203 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22204 unsigned NumElems = VT.getVectorNumElements();
22205 assert(StVT != VT && "Cannot truncate to the same type");
22206 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22207 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22209 // From, To sizes and ElemCount must be pow of two
22210 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22211 // We are going to use the original vector elt for storing.
22212 // Accumulated smaller vector elements must be a multiple of the store size.
22213 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22215 unsigned SizeRatio = FromSz / ToSz;
22217 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22219 // Create a type on which we perform the shuffle
22220 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22221 StVT.getScalarType(), NumElems*SizeRatio);
22223 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22225 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22226 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22227 for (unsigned i = 0; i != NumElems; ++i)
22228 ShuffleVec[i] = i * SizeRatio;
22230 // Can't shuffle using an illegal type.
22231 if (!TLI.isTypeLegal(WideVecVT))
22234 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22235 DAG.getUNDEF(WideVecVT),
22237 // At this point all of the data is stored at the bottom of the
22238 // register. We now need to save it to mem.
22240 // Find the largest store unit
22241 MVT StoreType = MVT::i8;
22242 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
22243 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
22244 MVT Tp = (MVT::SimpleValueType)tp;
22245 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22249 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22250 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22251 (64 <= NumElems * ToSz))
22252 StoreType = MVT::f64;
22254 // Bitcast the original vector into a vector of store-size units
22255 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22256 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22257 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22258 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22259 SmallVector<SDValue, 8> Chains;
22260 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22261 TLI.getPointerTy());
22262 SDValue Ptr = St->getBasePtr();
22264 // Perform one or more big stores into memory.
22265 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22266 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22267 StoreType, ShuffWide,
22268 DAG.getIntPtrConstant(i));
22269 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22270 St->getPointerInfo(), St->isVolatile(),
22271 St->isNonTemporal(), St->getAlignment());
22272 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22273 Chains.push_back(Ch);
22276 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22279 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
22280 // the FP state in cases where an emms may be missing.
22281 // A preferable solution to the general problem is to figure out the right
22282 // places to insert EMMS. This qualifies as a quick hack.
22284 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22285 if (VT.getSizeInBits() != 64)
22288 const Function *F = DAG.getMachineFunction().getFunction();
22289 bool NoImplicitFloatOps = F->getAttributes().
22290 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
22291 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22292 && Subtarget->hasSSE2();
22293 if ((VT.isVector() ||
22294 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22295 isa<LoadSDNode>(St->getValue()) &&
22296 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22297 St->getChain().hasOneUse() && !St->isVolatile()) {
22298 SDNode* LdVal = St->getValue().getNode();
22299 LoadSDNode *Ld = nullptr;
22300 int TokenFactorIndex = -1;
22301 SmallVector<SDValue, 8> Ops;
22302 SDNode* ChainVal = St->getChain().getNode();
22303 // Must be a store of a load. We currently handle two cases: the load
22304 // is a direct child, and it's under an intervening TokenFactor. It is
22305 // possible to dig deeper under nested TokenFactors.
22306 if (ChainVal == LdVal)
22307 Ld = cast<LoadSDNode>(St->getChain());
22308 else if (St->getValue().hasOneUse() &&
22309 ChainVal->getOpcode() == ISD::TokenFactor) {
22310 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22311 if (ChainVal->getOperand(i).getNode() == LdVal) {
22312 TokenFactorIndex = i;
22313 Ld = cast<LoadSDNode>(St->getValue());
22315 Ops.push_back(ChainVal->getOperand(i));
22319 if (!Ld || !ISD::isNormalLoad(Ld))
22322 // If this is not the MMX case, i.e. we are just turning i64 load/store
22323 // into f64 load/store, avoid the transformation if there are multiple
22324 // uses of the loaded value.
22325 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22330 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22331 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22333 if (Subtarget->is64Bit() || F64IsLegal) {
22334 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22335 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22336 Ld->getPointerInfo(), Ld->isVolatile(),
22337 Ld->isNonTemporal(), Ld->isInvariant(),
22338 Ld->getAlignment());
22339 SDValue NewChain = NewLd.getValue(1);
22340 if (TokenFactorIndex != -1) {
22341 Ops.push_back(NewChain);
22342 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22344 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22345 St->getPointerInfo(),
22346 St->isVolatile(), St->isNonTemporal(),
22347 St->getAlignment());
22350 // Otherwise, lower to two pairs of 32-bit loads / stores.
22351 SDValue LoAddr = Ld->getBasePtr();
22352 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22353 DAG.getConstant(4, MVT::i32));
22355 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22356 Ld->getPointerInfo(),
22357 Ld->isVolatile(), Ld->isNonTemporal(),
22358 Ld->isInvariant(), Ld->getAlignment());
22359 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22360 Ld->getPointerInfo().getWithOffset(4),
22361 Ld->isVolatile(), Ld->isNonTemporal(),
22363 MinAlign(Ld->getAlignment(), 4));
22365 SDValue NewChain = LoLd.getValue(1);
22366 if (TokenFactorIndex != -1) {
22367 Ops.push_back(LoLd);
22368 Ops.push_back(HiLd);
22369 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22372 LoAddr = St->getBasePtr();
22373 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22374 DAG.getConstant(4, MVT::i32));
22376 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22377 St->getPointerInfo(),
22378 St->isVolatile(), St->isNonTemporal(),
22379 St->getAlignment());
22380 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22381 St->getPointerInfo().getWithOffset(4),
22383 St->isNonTemporal(),
22384 MinAlign(St->getAlignment(), 4));
22385 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22390 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
22391 /// and return the operands for the horizontal operation in LHS and RHS. A
22392 /// horizontal operation performs the binary operation on successive elements
22393 /// of its first operand, then on successive elements of its second operand,
22394 /// returning the resulting values in a vector. For example, if
22395 /// A = < float a0, float a1, float a2, float a3 >
22397 /// B = < float b0, float b1, float b2, float b3 >
22398 /// then the result of doing a horizontal operation on A and B is
22399 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22400 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22401 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22402 /// set to A, RHS to B, and the routine returns 'true'.
22403 /// Note that the binary operation should have the property that if one of the
22404 /// operands is UNDEF then the result is UNDEF.
22405 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22406 // Look for the following pattern: if
22407 // A = < float a0, float a1, float a2, float a3 >
22408 // B = < float b0, float b1, float b2, float b3 >
22410 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22411 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22412 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22413 // which is A horizontal-op B.
22415 // At least one of the operands should be a vector shuffle.
22416 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22417 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22420 MVT VT = LHS.getSimpleValueType();
22422 assert((VT.is128BitVector() || VT.is256BitVector()) &&
22423 "Unsupported vector type for horizontal add/sub");
22425 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22426 // operate independently on 128-bit lanes.
22427 unsigned NumElts = VT.getVectorNumElements();
22428 unsigned NumLanes = VT.getSizeInBits()/128;
22429 unsigned NumLaneElts = NumElts / NumLanes;
22430 assert((NumLaneElts % 2 == 0) &&
22431 "Vector type should have an even number of elements in each lane");
22432 unsigned HalfLaneElts = NumLaneElts/2;
22434 // View LHS in the form
22435 // LHS = VECTOR_SHUFFLE A, B, LMask
22436 // If LHS is not a shuffle then pretend it is the shuffle
22437 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22438 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22441 SmallVector<int, 16> LMask(NumElts);
22442 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22443 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22444 A = LHS.getOperand(0);
22445 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22446 B = LHS.getOperand(1);
22447 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22448 std::copy(Mask.begin(), Mask.end(), LMask.begin());
22450 if (LHS.getOpcode() != ISD::UNDEF)
22452 for (unsigned i = 0; i != NumElts; ++i)
22456 // Likewise, view RHS in the form
22457 // RHS = VECTOR_SHUFFLE C, D, RMask
22459 SmallVector<int, 16> RMask(NumElts);
22460 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22461 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22462 C = RHS.getOperand(0);
22463 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22464 D = RHS.getOperand(1);
22465 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22466 std::copy(Mask.begin(), Mask.end(), RMask.begin());
22468 if (RHS.getOpcode() != ISD::UNDEF)
22470 for (unsigned i = 0; i != NumElts; ++i)
22474 // Check that the shuffles are both shuffling the same vectors.
22475 if (!(A == C && B == D) && !(A == D && B == C))
22478 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22479 if (!A.getNode() && !B.getNode())
22482 // If A and B occur in reverse order in RHS, then "swap" them (which means
22483 // rewriting the mask).
22485 CommuteVectorShuffleMask(RMask, NumElts);
22487 // At this point LHS and RHS are equivalent to
22488 // LHS = VECTOR_SHUFFLE A, B, LMask
22489 // RHS = VECTOR_SHUFFLE A, B, RMask
22490 // Check that the masks correspond to performing a horizontal operation.
22491 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22492 for (unsigned i = 0; i != NumLaneElts; ++i) {
22493 int LIdx = LMask[i+l], RIdx = RMask[i+l];
22495 // Ignore any UNDEF components.
22496 if (LIdx < 0 || RIdx < 0 ||
22497 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22498 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22501 // Check that successive elements are being operated on. If not, this is
22502 // not a horizontal operation.
22503 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22504 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22505 if (!(LIdx == Index && RIdx == Index + 1) &&
22506 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22511 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22512 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22516 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22517 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22518 const X86Subtarget *Subtarget) {
22519 EVT VT = N->getValueType(0);
22520 SDValue LHS = N->getOperand(0);
22521 SDValue RHS = N->getOperand(1);
22523 // Try to synthesize horizontal adds from adds of shuffles.
22524 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22525 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22526 isHorizontalBinOp(LHS, RHS, true))
22527 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22531 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22532 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22533 const X86Subtarget *Subtarget) {
22534 EVT VT = N->getValueType(0);
22535 SDValue LHS = N->getOperand(0);
22536 SDValue RHS = N->getOperand(1);
22538 // Try to synthesize horizontal subs from subs of shuffles.
22539 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22540 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22541 isHorizontalBinOp(LHS, RHS, false))
22542 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22546 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22547 /// X86ISD::FXOR nodes.
22548 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22549 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22550 // F[X]OR(0.0, x) -> x
22551 // F[X]OR(x, 0.0) -> x
22552 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22553 if (C->getValueAPF().isPosZero())
22554 return N->getOperand(1);
22555 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22556 if (C->getValueAPF().isPosZero())
22557 return N->getOperand(0);
22561 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22562 /// X86ISD::FMAX nodes.
22563 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22564 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22566 // Only perform optimizations if UnsafeMath is used.
22567 if (!DAG.getTarget().Options.UnsafeFPMath)
22570 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22571 // into FMINC and FMAXC, which are Commutative operations.
22572 unsigned NewOp = 0;
22573 switch (N->getOpcode()) {
22574 default: llvm_unreachable("unknown opcode");
22575 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
22576 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
22579 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22580 N->getOperand(0), N->getOperand(1));
22583 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22584 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22585 // FAND(0.0, x) -> 0.0
22586 // FAND(x, 0.0) -> 0.0
22587 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22588 if (C->getValueAPF().isPosZero())
22589 return N->getOperand(0);
22590 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22591 if (C->getValueAPF().isPosZero())
22592 return N->getOperand(1);
22596 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22597 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22598 // FANDN(x, 0.0) -> 0.0
22599 // FANDN(0.0, x) -> x
22600 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22601 if (C->getValueAPF().isPosZero())
22602 return N->getOperand(1);
22603 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22604 if (C->getValueAPF().isPosZero())
22605 return N->getOperand(1);
22609 static SDValue PerformBTCombine(SDNode *N,
22611 TargetLowering::DAGCombinerInfo &DCI) {
22612 // BT ignores high bits in the bit index operand.
22613 SDValue Op1 = N->getOperand(1);
22614 if (Op1.hasOneUse()) {
22615 unsigned BitWidth = Op1.getValueSizeInBits();
22616 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22617 APInt KnownZero, KnownOne;
22618 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22619 !DCI.isBeforeLegalizeOps());
22620 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22621 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22622 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22623 DCI.CommitTargetLoweringOpt(TLO);
22628 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22629 SDValue Op = N->getOperand(0);
22630 if (Op.getOpcode() == ISD::BITCAST)
22631 Op = Op.getOperand(0);
22632 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22633 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22634 VT.getVectorElementType().getSizeInBits() ==
22635 OpVT.getVectorElementType().getSizeInBits()) {
22636 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22641 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22642 const X86Subtarget *Subtarget) {
22643 EVT VT = N->getValueType(0);
22644 if (!VT.isVector())
22647 SDValue N0 = N->getOperand(0);
22648 SDValue N1 = N->getOperand(1);
22649 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22652 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22653 // both SSE and AVX2 since there is no sign-extended shift right
22654 // operation on a vector with 64-bit elements.
22655 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22656 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22657 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22658 N0.getOpcode() == ISD::SIGN_EXTEND)) {
22659 SDValue N00 = N0.getOperand(0);
22661 // EXTLOAD has a better solution on AVX2,
22662 // it may be replaced with X86ISD::VSEXT node.
22663 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22664 if (!ISD::isNormalLoad(N00.getNode()))
22667 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22668 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22670 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22676 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22677 TargetLowering::DAGCombinerInfo &DCI,
22678 const X86Subtarget *Subtarget) {
22679 if (!DCI.isBeforeLegalizeOps())
22682 if (!Subtarget->hasFp256())
22685 EVT VT = N->getValueType(0);
22686 if (VT.isVector() && VT.getSizeInBits() == 256) {
22687 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22695 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22696 const X86Subtarget* Subtarget) {
22698 EVT VT = N->getValueType(0);
22700 // Let legalize expand this if it isn't a legal type yet.
22701 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22704 EVT ScalarVT = VT.getScalarType();
22705 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22706 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22709 SDValue A = N->getOperand(0);
22710 SDValue B = N->getOperand(1);
22711 SDValue C = N->getOperand(2);
22713 bool NegA = (A.getOpcode() == ISD::FNEG);
22714 bool NegB = (B.getOpcode() == ISD::FNEG);
22715 bool NegC = (C.getOpcode() == ISD::FNEG);
22717 // Negative multiplication when NegA xor NegB
22718 bool NegMul = (NegA != NegB);
22720 A = A.getOperand(0);
22722 B = B.getOperand(0);
22724 C = C.getOperand(0);
22728 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22730 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22732 return DAG.getNode(Opcode, dl, VT, A, B, C);
22735 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22736 TargetLowering::DAGCombinerInfo &DCI,
22737 const X86Subtarget *Subtarget) {
22738 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
22739 // (and (i32 x86isd::setcc_carry), 1)
22740 // This eliminates the zext. This transformation is necessary because
22741 // ISD::SETCC is always legalized to i8.
22743 SDValue N0 = N->getOperand(0);
22744 EVT VT = N->getValueType(0);
22746 if (N0.getOpcode() == ISD::AND &&
22748 N0.getOperand(0).hasOneUse()) {
22749 SDValue N00 = N0.getOperand(0);
22750 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22751 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22752 if (!C || C->getZExtValue() != 1)
22754 return DAG.getNode(ISD::AND, dl, VT,
22755 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22756 N00.getOperand(0), N00.getOperand(1)),
22757 DAG.getConstant(1, VT));
22761 if (N0.getOpcode() == ISD::TRUNCATE &&
22763 N0.getOperand(0).hasOneUse()) {
22764 SDValue N00 = N0.getOperand(0);
22765 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22766 return DAG.getNode(ISD::AND, dl, VT,
22767 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22768 N00.getOperand(0), N00.getOperand(1)),
22769 DAG.getConstant(1, VT));
22772 if (VT.is256BitVector()) {
22773 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22781 // Optimize x == -y --> x+y == 0
22782 // x != -y --> x+y != 0
22783 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22784 const X86Subtarget* Subtarget) {
22785 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22786 SDValue LHS = N->getOperand(0);
22787 SDValue RHS = N->getOperand(1);
22788 EVT VT = N->getValueType(0);
22791 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22792 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22793 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22794 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22795 LHS.getValueType(), RHS, LHS.getOperand(1));
22796 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22797 addV, DAG.getConstant(0, addV.getValueType()), CC);
22799 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22800 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22801 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22802 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22803 RHS.getValueType(), LHS, RHS.getOperand(1));
22804 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22805 addV, DAG.getConstant(0, addV.getValueType()), CC);
22808 if (VT.getScalarType() == MVT::i1) {
22809 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22810 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22811 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22812 if (!IsSEXT0 && !IsVZero0)
22814 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22815 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22816 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22818 if (!IsSEXT1 && !IsVZero1)
22821 if (IsSEXT0 && IsVZero1) {
22822 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22823 if (CC == ISD::SETEQ)
22824 return DAG.getNOT(DL, LHS.getOperand(0), VT);
22825 return LHS.getOperand(0);
22827 if (IsSEXT1 && IsVZero0) {
22828 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22829 if (CC == ISD::SETEQ)
22830 return DAG.getNOT(DL, RHS.getOperand(0), VT);
22831 return RHS.getOperand(0);
22838 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22839 const X86Subtarget *Subtarget) {
22841 MVT VT = N->getOperand(1)->getSimpleValueType(0);
22842 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22843 "X86insertps is only defined for v4x32");
22845 SDValue Ld = N->getOperand(1);
22846 if (MayFoldLoad(Ld)) {
22847 // Extract the countS bits from the immediate so we can get the proper
22848 // address when narrowing the vector load to a specific element.
22849 // When the second source op is a memory address, interps doesn't use
22850 // countS and just gets an f32 from that address.
22851 unsigned DestIndex =
22852 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22853 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22857 // Create this as a scalar to vector to match the instruction pattern.
22858 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22859 // countS bits are ignored when loading from memory on insertps, which
22860 // means we don't need to explicitly set them to 0.
22861 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22862 LoadScalarToVector, N->getOperand(2));
22865 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22866 // as "sbb reg,reg", since it can be extended without zext and produces
22867 // an all-ones bit which is more useful than 0/1 in some cases.
22868 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22871 return DAG.getNode(ISD::AND, DL, VT,
22872 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22873 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22874 DAG.getConstant(1, VT));
22875 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22876 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22877 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22878 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22881 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22882 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22883 TargetLowering::DAGCombinerInfo &DCI,
22884 const X86Subtarget *Subtarget) {
22886 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22887 SDValue EFLAGS = N->getOperand(1);
22889 if (CC == X86::COND_A) {
22890 // Try to convert COND_A into COND_B in an attempt to facilitate
22891 // materializing "setb reg".
22893 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22894 // cannot take an immediate as its first operand.
22896 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22897 EFLAGS.getValueType().isInteger() &&
22898 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22899 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22900 EFLAGS.getNode()->getVTList(),
22901 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22902 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22903 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22907 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22908 // a zext and produces an all-ones bit which is more useful than 0/1 in some
22910 if (CC == X86::COND_B)
22911 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22915 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22916 if (Flags.getNode()) {
22917 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22918 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22924 // Optimize branch condition evaluation.
22926 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22927 TargetLowering::DAGCombinerInfo &DCI,
22928 const X86Subtarget *Subtarget) {
22930 SDValue Chain = N->getOperand(0);
22931 SDValue Dest = N->getOperand(1);
22932 SDValue EFLAGS = N->getOperand(3);
22933 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22937 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22938 if (Flags.getNode()) {
22939 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22940 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22947 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22948 SelectionDAG &DAG) {
22949 // Take advantage of vector comparisons producing 0 or -1 in each lane to
22950 // optimize away operation when it's from a constant.
22952 // The general transformation is:
22953 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22954 // AND(VECTOR_CMP(x,y), constant2)
22955 // constant2 = UNARYOP(constant)
22957 // Early exit if this isn't a vector operation, the operand of the
22958 // unary operation isn't a bitwise AND, or if the sizes of the operations
22959 // aren't the same.
22960 EVT VT = N->getValueType(0);
22961 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22962 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22963 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22966 // Now check that the other operand of the AND is a constant. We could
22967 // make the transformation for non-constant splats as well, but it's unclear
22968 // that would be a benefit as it would not eliminate any operations, just
22969 // perform one more step in scalar code before moving to the vector unit.
22970 if (BuildVectorSDNode *BV =
22971 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22972 // Bail out if the vector isn't a constant.
22973 if (!BV->isConstant())
22976 // Everything checks out. Build up the new and improved node.
22978 EVT IntVT = BV->getValueType(0);
22979 // Create a new constant of the appropriate type for the transformed
22981 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22982 // The AND node needs bitcasts to/from an integer vector type around it.
22983 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22984 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22985 N->getOperand(0)->getOperand(0), MaskConst);
22986 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22993 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22994 const X86TargetLowering *XTLI) {
22995 // First try to optimize away the conversion entirely when it's
22996 // conditionally from a constant. Vectors only.
22997 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22998 if (Res != SDValue())
23001 // Now move on to more general possibilities.
23002 SDValue Op0 = N->getOperand(0);
23003 EVT InVT = Op0->getValueType(0);
23005 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23006 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23008 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23009 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23010 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23013 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23014 // a 32-bit target where SSE doesn't support i64->FP operations.
23015 if (Op0.getOpcode() == ISD::LOAD) {
23016 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23017 EVT VT = Ld->getValueType(0);
23018 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23019 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23020 !XTLI->getSubtarget()->is64Bit() &&
23022 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
23023 Ld->getChain(), Op0, DAG);
23024 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23031 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23032 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23033 X86TargetLowering::DAGCombinerInfo &DCI) {
23034 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23035 // the result is either zero or one (depending on the input carry bit).
23036 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23037 if (X86::isZeroNode(N->getOperand(0)) &&
23038 X86::isZeroNode(N->getOperand(1)) &&
23039 // We don't have a good way to replace an EFLAGS use, so only do this when
23041 SDValue(N, 1).use_empty()) {
23043 EVT VT = N->getValueType(0);
23044 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23045 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23046 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23047 DAG.getConstant(X86::COND_B,MVT::i8),
23049 DAG.getConstant(1, VT));
23050 return DCI.CombineTo(N, Res1, CarryOut);
23056 // fold (add Y, (sete X, 0)) -> adc 0, Y
23057 // (add Y, (setne X, 0)) -> sbb -1, Y
23058 // (sub (sete X, 0), Y) -> sbb 0, Y
23059 // (sub (setne X, 0), Y) -> adc -1, Y
23060 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23063 // Look through ZExts.
23064 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23065 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23068 SDValue SetCC = Ext.getOperand(0);
23069 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23072 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23073 if (CC != X86::COND_E && CC != X86::COND_NE)
23076 SDValue Cmp = SetCC.getOperand(1);
23077 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23078 !X86::isZeroNode(Cmp.getOperand(1)) ||
23079 !Cmp.getOperand(0).getValueType().isInteger())
23082 SDValue CmpOp0 = Cmp.getOperand(0);
23083 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23084 DAG.getConstant(1, CmpOp0.getValueType()));
23086 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23087 if (CC == X86::COND_NE)
23088 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23089 DL, OtherVal.getValueType(), OtherVal,
23090 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23091 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23092 DL, OtherVal.getValueType(), OtherVal,
23093 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23096 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23097 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23098 const X86Subtarget *Subtarget) {
23099 EVT VT = N->getValueType(0);
23100 SDValue Op0 = N->getOperand(0);
23101 SDValue Op1 = N->getOperand(1);
23103 // Try to synthesize horizontal adds from adds of shuffles.
23104 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23105 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23106 isHorizontalBinOp(Op0, Op1, true))
23107 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23109 return OptimizeConditionalInDecrement(N, DAG);
23112 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23113 const X86Subtarget *Subtarget) {
23114 SDValue Op0 = N->getOperand(0);
23115 SDValue Op1 = N->getOperand(1);
23117 // X86 can't encode an immediate LHS of a sub. See if we can push the
23118 // negation into a preceding instruction.
23119 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23120 // If the RHS of the sub is a XOR with one use and a constant, invert the
23121 // immediate. Then add one to the LHS of the sub so we can turn
23122 // X-Y -> X+~Y+1, saving one register.
23123 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23124 isa<ConstantSDNode>(Op1.getOperand(1))) {
23125 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23126 EVT VT = Op0.getValueType();
23127 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23129 DAG.getConstant(~XorC, VT));
23130 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23131 DAG.getConstant(C->getAPIntValue()+1, VT));
23135 // Try to synthesize horizontal adds from adds of shuffles.
23136 EVT VT = N->getValueType(0);
23137 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23138 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23139 isHorizontalBinOp(Op0, Op1, true))
23140 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23142 return OptimizeConditionalInDecrement(N, DAG);
23145 /// performVZEXTCombine - Performs build vector combines
23146 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23147 TargetLowering::DAGCombinerInfo &DCI,
23148 const X86Subtarget *Subtarget) {
23149 // (vzext (bitcast (vzext (x)) -> (vzext x)
23150 SDValue In = N->getOperand(0);
23151 while (In.getOpcode() == ISD::BITCAST)
23152 In = In.getOperand(0);
23154 if (In.getOpcode() != X86ISD::VZEXT)
23157 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
23161 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23162 DAGCombinerInfo &DCI) const {
23163 SelectionDAG &DAG = DCI.DAG;
23164 switch (N->getOpcode()) {
23166 case ISD::EXTRACT_VECTOR_ELT:
23167 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23169 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23170 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23171 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
23172 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
23173 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
23174 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
23177 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
23178 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
23179 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
23180 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
23181 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
23182 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
23183 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
23184 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
23185 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
23187 case X86ISD::FOR: return PerformFORCombine(N, DAG);
23189 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
23190 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
23191 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
23192 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
23193 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
23194 case ISD::ANY_EXTEND:
23195 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
23196 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
23197 case ISD::SIGN_EXTEND_INREG:
23198 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23199 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23200 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
23201 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23202 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23203 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
23204 case X86ISD::SHUFP: // Handle all target specific shuffles
23205 case X86ISD::PALIGNR:
23206 case X86ISD::UNPCKH:
23207 case X86ISD::UNPCKL:
23208 case X86ISD::MOVHLPS:
23209 case X86ISD::MOVLHPS:
23210 case X86ISD::PSHUFB:
23211 case X86ISD::PSHUFD:
23212 case X86ISD::PSHUFHW:
23213 case X86ISD::PSHUFLW:
23214 case X86ISD::MOVSS:
23215 case X86ISD::MOVSD:
23216 case X86ISD::VPERMILP:
23217 case X86ISD::VPERM2X128:
23218 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23219 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
23220 case ISD::INTRINSIC_WO_CHAIN:
23221 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23222 case X86ISD::INSERTPS:
23223 return PerformINSERTPSCombine(N, DAG, Subtarget);
23224 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23230 /// isTypeDesirableForOp - Return true if the target has native support for
23231 /// the specified value type and it is 'desirable' to use the type for the
23232 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23233 /// instruction encodings are longer and some i16 instructions are slow.
23234 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23235 if (!isTypeLegal(VT))
23237 if (VT != MVT::i16)
23244 case ISD::SIGN_EXTEND:
23245 case ISD::ZERO_EXTEND:
23246 case ISD::ANY_EXTEND:
23259 /// IsDesirableToPromoteOp - This method query the target whether it is
23260 /// beneficial for dag combiner to promote the specified node. If true, it
23261 /// should return the desired promotion type by reference.
23262 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23263 EVT VT = Op.getValueType();
23264 if (VT != MVT::i16)
23267 bool Promote = false;
23268 bool Commute = false;
23269 switch (Op.getOpcode()) {
23272 LoadSDNode *LD = cast<LoadSDNode>(Op);
23273 // If the non-extending load has a single use and it's not live out, then it
23274 // might be folded.
23275 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23276 Op.hasOneUse()*/) {
23277 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23278 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23279 // The only case where we'd want to promote LOAD (rather then it being
23280 // promoted as an operand is when it's only use is liveout.
23281 if (UI->getOpcode() != ISD::CopyToReg)
23288 case ISD::SIGN_EXTEND:
23289 case ISD::ZERO_EXTEND:
23290 case ISD::ANY_EXTEND:
23295 SDValue N0 = Op.getOperand(0);
23296 // Look out for (store (shl (load), x)).
23297 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23310 SDValue N0 = Op.getOperand(0);
23311 SDValue N1 = Op.getOperand(1);
23312 if (!Commute && MayFoldLoad(N1))
23314 // Avoid disabling potential load folding opportunities.
23315 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23317 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23327 //===----------------------------------------------------------------------===//
23328 // X86 Inline Assembly Support
23329 //===----------------------------------------------------------------------===//
23332 // Helper to match a string separated by whitespace.
23333 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
23334 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
23336 for (unsigned i = 0, e = args.size(); i != e; ++i) {
23337 StringRef piece(*args[i]);
23338 if (!s.startswith(piece)) // Check if the piece matches.
23341 s = s.substr(piece.size());
23342 StringRef::size_type pos = s.find_first_not_of(" \t");
23343 if (pos == 0) // We matched a prefix.
23351 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
23354 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23356 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23357 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23358 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23359 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23361 if (AsmPieces.size() == 3)
23363 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23370 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23371 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23373 std::string AsmStr = IA->getAsmString();
23375 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23376 if (!Ty || Ty->getBitWidth() % 16 != 0)
23379 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23380 SmallVector<StringRef, 4> AsmPieces;
23381 SplitString(AsmStr, AsmPieces, ";\n");
23383 switch (AsmPieces.size()) {
23384 default: return false;
23386 // FIXME: this should verify that we are targeting a 486 or better. If not,
23387 // we will turn this bswap into something that will be lowered to logical
23388 // ops instead of emitting the bswap asm. For now, we don't support 486 or
23389 // lower so don't worry about this.
23391 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
23392 matchAsm(AsmPieces[0], "bswapl", "$0") ||
23393 matchAsm(AsmPieces[0], "bswapq", "$0") ||
23394 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
23395 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
23396 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
23397 // No need to check constraints, nothing other than the equivalent of
23398 // "=r,0" would be valid here.
23399 return IntrinsicLowering::LowerToByteSwap(CI);
23402 // rorw $$8, ${0:w} --> llvm.bswap.i16
23403 if (CI->getType()->isIntegerTy(16) &&
23404 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23405 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
23406 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
23408 const std::string &ConstraintsStr = IA->getConstraintString();
23409 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23410 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23411 if (clobbersFlagRegisters(AsmPieces))
23412 return IntrinsicLowering::LowerToByteSwap(CI);
23416 if (CI->getType()->isIntegerTy(32) &&
23417 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23418 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
23419 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
23420 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
23422 const std::string &ConstraintsStr = IA->getConstraintString();
23423 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23424 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23425 if (clobbersFlagRegisters(AsmPieces))
23426 return IntrinsicLowering::LowerToByteSwap(CI);
23429 if (CI->getType()->isIntegerTy(64)) {
23430 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23431 if (Constraints.size() >= 2 &&
23432 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23433 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23434 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
23435 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
23436 matchAsm(AsmPieces[1], "bswap", "%edx") &&
23437 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
23438 return IntrinsicLowering::LowerToByteSwap(CI);
23446 /// getConstraintType - Given a constraint letter, return the type of
23447 /// constraint it is for this target.
23448 X86TargetLowering::ConstraintType
23449 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23450 if (Constraint.size() == 1) {
23451 switch (Constraint[0]) {
23462 return C_RegisterClass;
23486 return TargetLowering::getConstraintType(Constraint);
23489 /// Examine constraint type and operand type and determine a weight value.
23490 /// This object must already have been set up with the operand type
23491 /// and the current alternative constraint selected.
23492 TargetLowering::ConstraintWeight
23493 X86TargetLowering::getSingleConstraintMatchWeight(
23494 AsmOperandInfo &info, const char *constraint) const {
23495 ConstraintWeight weight = CW_Invalid;
23496 Value *CallOperandVal = info.CallOperandVal;
23497 // If we don't have a value, we can't do a match,
23498 // but allow it at the lowest weight.
23499 if (!CallOperandVal)
23501 Type *type = CallOperandVal->getType();
23502 // Look at the constraint type.
23503 switch (*constraint) {
23505 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23516 if (CallOperandVal->getType()->isIntegerTy())
23517 weight = CW_SpecificReg;
23522 if (type->isFloatingPointTy())
23523 weight = CW_SpecificReg;
23526 if (type->isX86_MMXTy() && Subtarget->hasMMX())
23527 weight = CW_SpecificReg;
23531 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23532 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23533 weight = CW_Register;
23536 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23537 if (C->getZExtValue() <= 31)
23538 weight = CW_Constant;
23542 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23543 if (C->getZExtValue() <= 63)
23544 weight = CW_Constant;
23548 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23549 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23550 weight = CW_Constant;
23554 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23555 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23556 weight = CW_Constant;
23560 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23561 if (C->getZExtValue() <= 3)
23562 weight = CW_Constant;
23566 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23567 if (C->getZExtValue() <= 0xff)
23568 weight = CW_Constant;
23573 if (dyn_cast<ConstantFP>(CallOperandVal)) {
23574 weight = CW_Constant;
23578 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23579 if ((C->getSExtValue() >= -0x80000000LL) &&
23580 (C->getSExtValue() <= 0x7fffffffLL))
23581 weight = CW_Constant;
23585 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23586 if (C->getZExtValue() <= 0xffffffff)
23587 weight = CW_Constant;
23594 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23595 /// with another that has more specific requirements based on the type of the
23596 /// corresponding operand.
23597 const char *X86TargetLowering::
23598 LowerXConstraint(EVT ConstraintVT) const {
23599 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23600 // 'f' like normal targets.
23601 if (ConstraintVT.isFloatingPoint()) {
23602 if (Subtarget->hasSSE2())
23604 if (Subtarget->hasSSE1())
23608 return TargetLowering::LowerXConstraint(ConstraintVT);
23611 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23612 /// vector. If it is invalid, don't add anything to Ops.
23613 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23614 std::string &Constraint,
23615 std::vector<SDValue>&Ops,
23616 SelectionDAG &DAG) const {
23619 // Only support length 1 constraints for now.
23620 if (Constraint.length() > 1) return;
23622 char ConstraintLetter = Constraint[0];
23623 switch (ConstraintLetter) {
23626 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23627 if (C->getZExtValue() <= 31) {
23628 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23634 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23635 if (C->getZExtValue() <= 63) {
23636 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23642 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23643 if (isInt<8>(C->getSExtValue())) {
23644 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23650 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23651 if (C->getZExtValue() <= 255) {
23652 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23658 // 32-bit signed value
23659 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23660 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23661 C->getSExtValue())) {
23662 // Widen to 64 bits here to get it sign extended.
23663 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23666 // FIXME gcc accepts some relocatable values here too, but only in certain
23667 // memory models; it's complicated.
23672 // 32-bit unsigned value
23673 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23674 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23675 C->getZExtValue())) {
23676 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23680 // FIXME gcc accepts some relocatable values here too, but only in certain
23681 // memory models; it's complicated.
23685 // Literal immediates are always ok.
23686 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23687 // Widen to 64 bits here to get it sign extended.
23688 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23692 // In any sort of PIC mode addresses need to be computed at runtime by
23693 // adding in a register or some sort of table lookup. These can't
23694 // be used as immediates.
23695 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23698 // If we are in non-pic codegen mode, we allow the address of a global (with
23699 // an optional displacement) to be used with 'i'.
23700 GlobalAddressSDNode *GA = nullptr;
23701 int64_t Offset = 0;
23703 // Match either (GA), (GA+C), (GA+C1+C2), etc.
23705 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23706 Offset += GA->getOffset();
23708 } else if (Op.getOpcode() == ISD::ADD) {
23709 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23710 Offset += C->getZExtValue();
23711 Op = Op.getOperand(0);
23714 } else if (Op.getOpcode() == ISD::SUB) {
23715 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23716 Offset += -C->getZExtValue();
23717 Op = Op.getOperand(0);
23722 // Otherwise, this isn't something we can handle, reject it.
23726 const GlobalValue *GV = GA->getGlobal();
23727 // If we require an extra load to get this address, as in PIC mode, we
23728 // can't accept it.
23729 if (isGlobalStubReference(
23730 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23733 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23734 GA->getValueType(0), Offset);
23739 if (Result.getNode()) {
23740 Ops.push_back(Result);
23743 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23746 std::pair<unsigned, const TargetRegisterClass*>
23747 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23749 // First, see if this is a constraint that directly corresponds to an LLVM
23751 if (Constraint.size() == 1) {
23752 // GCC Constraint Letters
23753 switch (Constraint[0]) {
23755 // TODO: Slight differences here in allocation order and leaving
23756 // RIP in the class. Do they matter any more here than they do
23757 // in the normal allocation?
23758 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23759 if (Subtarget->is64Bit()) {
23760 if (VT == MVT::i32 || VT == MVT::f32)
23761 return std::make_pair(0U, &X86::GR32RegClass);
23762 if (VT == MVT::i16)
23763 return std::make_pair(0U, &X86::GR16RegClass);
23764 if (VT == MVT::i8 || VT == MVT::i1)
23765 return std::make_pair(0U, &X86::GR8RegClass);
23766 if (VT == MVT::i64 || VT == MVT::f64)
23767 return std::make_pair(0U, &X86::GR64RegClass);
23770 // 32-bit fallthrough
23771 case 'Q': // Q_REGS
23772 if (VT == MVT::i32 || VT == MVT::f32)
23773 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23774 if (VT == MVT::i16)
23775 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23776 if (VT == MVT::i8 || VT == MVT::i1)
23777 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23778 if (VT == MVT::i64)
23779 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23781 case 'r': // GENERAL_REGS
23782 case 'l': // INDEX_REGS
23783 if (VT == MVT::i8 || VT == MVT::i1)
23784 return std::make_pair(0U, &X86::GR8RegClass);
23785 if (VT == MVT::i16)
23786 return std::make_pair(0U, &X86::GR16RegClass);
23787 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23788 return std::make_pair(0U, &X86::GR32RegClass);
23789 return std::make_pair(0U, &X86::GR64RegClass);
23790 case 'R': // LEGACY_REGS
23791 if (VT == MVT::i8 || VT == MVT::i1)
23792 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23793 if (VT == MVT::i16)
23794 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23795 if (VT == MVT::i32 || !Subtarget->is64Bit())
23796 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23797 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23798 case 'f': // FP Stack registers.
23799 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23800 // value to the correct fpstack register class.
23801 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23802 return std::make_pair(0U, &X86::RFP32RegClass);
23803 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23804 return std::make_pair(0U, &X86::RFP64RegClass);
23805 return std::make_pair(0U, &X86::RFP80RegClass);
23806 case 'y': // MMX_REGS if MMX allowed.
23807 if (!Subtarget->hasMMX()) break;
23808 return std::make_pair(0U, &X86::VR64RegClass);
23809 case 'Y': // SSE_REGS if SSE2 allowed
23810 if (!Subtarget->hasSSE2()) break;
23812 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23813 if (!Subtarget->hasSSE1()) break;
23815 switch (VT.SimpleTy) {
23817 // Scalar SSE types.
23820 return std::make_pair(0U, &X86::FR32RegClass);
23823 return std::make_pair(0U, &X86::FR64RegClass);
23831 return std::make_pair(0U, &X86::VR128RegClass);
23839 return std::make_pair(0U, &X86::VR256RegClass);
23844 return std::make_pair(0U, &X86::VR512RegClass);
23850 // Use the default implementation in TargetLowering to convert the register
23851 // constraint into a member of a register class.
23852 std::pair<unsigned, const TargetRegisterClass*> Res;
23853 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23855 // Not found as a standard register?
23857 // Map st(0) -> st(7) -> ST0
23858 if (Constraint.size() == 7 && Constraint[0] == '{' &&
23859 tolower(Constraint[1]) == 's' &&
23860 tolower(Constraint[2]) == 't' &&
23861 Constraint[3] == '(' &&
23862 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23863 Constraint[5] == ')' &&
23864 Constraint[6] == '}') {
23866 Res.first = X86::FP0+Constraint[4]-'0';
23867 Res.second = &X86::RFP80RegClass;
23871 // GCC allows "st(0)" to be called just plain "st".
23872 if (StringRef("{st}").equals_lower(Constraint)) {
23873 Res.first = X86::FP0;
23874 Res.second = &X86::RFP80RegClass;
23879 if (StringRef("{flags}").equals_lower(Constraint)) {
23880 Res.first = X86::EFLAGS;
23881 Res.second = &X86::CCRRegClass;
23885 // 'A' means EAX + EDX.
23886 if (Constraint == "A") {
23887 Res.first = X86::EAX;
23888 Res.second = &X86::GR32_ADRegClass;
23894 // Otherwise, check to see if this is a register class of the wrong value
23895 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23896 // turn into {ax},{dx}.
23897 if (Res.second->hasType(VT))
23898 return Res; // Correct type already, nothing to do.
23900 // All of the single-register GCC register classes map their values onto
23901 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
23902 // really want an 8-bit or 32-bit register, map to the appropriate register
23903 // class and return the appropriate register.
23904 if (Res.second == &X86::GR16RegClass) {
23905 if (VT == MVT::i8 || VT == MVT::i1) {
23906 unsigned DestReg = 0;
23907 switch (Res.first) {
23909 case X86::AX: DestReg = X86::AL; break;
23910 case X86::DX: DestReg = X86::DL; break;
23911 case X86::CX: DestReg = X86::CL; break;
23912 case X86::BX: DestReg = X86::BL; break;
23915 Res.first = DestReg;
23916 Res.second = &X86::GR8RegClass;
23918 } else if (VT == MVT::i32 || VT == MVT::f32) {
23919 unsigned DestReg = 0;
23920 switch (Res.first) {
23922 case X86::AX: DestReg = X86::EAX; break;
23923 case X86::DX: DestReg = X86::EDX; break;
23924 case X86::CX: DestReg = X86::ECX; break;
23925 case X86::BX: DestReg = X86::EBX; break;
23926 case X86::SI: DestReg = X86::ESI; break;
23927 case X86::DI: DestReg = X86::EDI; break;
23928 case X86::BP: DestReg = X86::EBP; break;
23929 case X86::SP: DestReg = X86::ESP; break;
23932 Res.first = DestReg;
23933 Res.second = &X86::GR32RegClass;
23935 } else if (VT == MVT::i64 || VT == MVT::f64) {
23936 unsigned DestReg = 0;
23937 switch (Res.first) {
23939 case X86::AX: DestReg = X86::RAX; break;
23940 case X86::DX: DestReg = X86::RDX; break;
23941 case X86::CX: DestReg = X86::RCX; break;
23942 case X86::BX: DestReg = X86::RBX; break;
23943 case X86::SI: DestReg = X86::RSI; break;
23944 case X86::DI: DestReg = X86::RDI; break;
23945 case X86::BP: DestReg = X86::RBP; break;
23946 case X86::SP: DestReg = X86::RSP; break;
23949 Res.first = DestReg;
23950 Res.second = &X86::GR64RegClass;
23953 } else if (Res.second == &X86::FR32RegClass ||
23954 Res.second == &X86::FR64RegClass ||
23955 Res.second == &X86::VR128RegClass ||
23956 Res.second == &X86::VR256RegClass ||
23957 Res.second == &X86::FR32XRegClass ||
23958 Res.second == &X86::FR64XRegClass ||
23959 Res.second == &X86::VR128XRegClass ||
23960 Res.second == &X86::VR256XRegClass ||
23961 Res.second == &X86::VR512RegClass) {
23962 // Handle references to XMM physical registers that got mapped into the
23963 // wrong class. This can happen with constraints like {xmm0} where the
23964 // target independent register mapper will just pick the first match it can
23965 // find, ignoring the required type.
23967 if (VT == MVT::f32 || VT == MVT::i32)
23968 Res.second = &X86::FR32RegClass;
23969 else if (VT == MVT::f64 || VT == MVT::i64)
23970 Res.second = &X86::FR64RegClass;
23971 else if (X86::VR128RegClass.hasType(VT))
23972 Res.second = &X86::VR128RegClass;
23973 else if (X86::VR256RegClass.hasType(VT))
23974 Res.second = &X86::VR256RegClass;
23975 else if (X86::VR512RegClass.hasType(VT))
23976 Res.second = &X86::VR512RegClass;
23982 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23984 // Scaling factors are not free at all.
23985 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23986 // will take 2 allocations in the out of order engine instead of 1
23987 // for plain addressing mode, i.e. inst (reg1).
23989 // vaddps (%rsi,%drx), %ymm0, %ymm1
23990 // Requires two allocations (one for the load, one for the computation)
23992 // vaddps (%rsi), %ymm0, %ymm1
23993 // Requires just 1 allocation, i.e., freeing allocations for other operations
23994 // and having less micro operations to execute.
23996 // For some X86 architectures, this is even worse because for instance for
23997 // stores, the complex addressing mode forces the instruction to use the
23998 // "load" ports instead of the dedicated "store" port.
23999 // E.g., on Haswell:
24000 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24001 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
24002 if (isLegalAddressingMode(AM, Ty))
24003 // Scale represents reg2 * scale, thus account for 1
24004 // as soon as we use a second register.
24005 return AM.Scale != 0;
24009 bool X86TargetLowering::isTargetFTOL() const {
24010 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();