1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "x86-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62 "x86-experimental-vector-widening-legalization", cl::init(false),
63 cl::desc("Enable an experimental vector type legalization through widening "
64 "rather than promotion."),
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68 "x86-experimental-vector-shuffle-lowering", cl::init(false),
69 cl::desc("Enable an experimental vector shuffle lowering code path."),
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77 SelectionDAG &DAG, SDLoc dl,
78 unsigned vectorWidth) {
79 assert((vectorWidth == 128 || vectorWidth == 256) &&
80 "Unsupported vector width");
81 EVT VT = Vec.getValueType();
82 EVT ElVT = VT.getVectorElementType();
83 unsigned Factor = VT.getSizeInBits()/vectorWidth;
84 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85 VT.getVectorNumElements()/Factor);
87 // Extract from UNDEF is UNDEF.
88 if (Vec.getOpcode() == ISD::UNDEF)
89 return DAG.getUNDEF(ResultVT);
91 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
92 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
94 // This is the index of the first element of the vectorWidth-bit chunk
96 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
99 // If the input is a buildvector just emit a smaller one.
100 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
105 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119 SelectionDAG &DAG, SDLoc dl) {
120 assert((Vec.getValueType().is256BitVector() ||
121 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127 SelectionDAG &DAG, SDLoc dl) {
128 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133 unsigned IdxVal, SelectionDAG &DAG,
134 SDLoc dl, unsigned vectorWidth) {
135 assert((vectorWidth == 128 || vectorWidth == 256) &&
136 "Unsupported vector width");
137 // Inserting UNDEF is Result
138 if (Vec.getOpcode() == ISD::UNDEF)
140 EVT VT = Vec.getValueType();
141 EVT ElVT = VT.getVectorElementType();
142 EVT ResultVT = Result.getValueType();
144 // Insert the relevant vectorWidth bits.
145 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
147 // This is the index of the first element of the vectorWidth-bit chunk
149 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
152 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
156 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference. Idx is an index in the 128 bits
160 /// we want. It need not be aligned to a 128-bit bounday. That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163 unsigned IdxVal, SelectionDAG &DAG,
165 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170 unsigned IdxVal, SelectionDAG &DAG,
172 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181 unsigned NumElems, SelectionDAG &DAG,
183 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188 unsigned NumElems, SelectionDAG &DAG,
190 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195 if (TT.isOSBinFormatMachO()) {
196 if (TT.getArch() == Triple::x86_64)
197 return new X86_64MachoTargetObjectFile();
198 return new TargetLoweringObjectFileMachO();
202 return new X86LinuxTargetObjectFile();
203 if (TT.isOSBinFormatELF())
204 return new TargetLoweringObjectFileELF();
205 if (TT.isKnownWindowsMSVCEnvironment())
206 return new X86WindowsTargetObjectFile();
207 if (TT.isOSBinFormatCOFF())
208 return new TargetLoweringObjectFileCOFF();
209 llvm_unreachable("unknown subtarget type");
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216 Subtarget = &TM.getSubtarget<X86Subtarget>();
217 X86ScalarSSEf64 = Subtarget->hasSSE2();
218 X86ScalarSSEf32 = Subtarget->hasSSE1();
219 TD = getDataLayout();
221 resetOperationActions();
224 void X86TargetLowering::resetOperationActions() {
225 const TargetMachine &TM = getTargetMachine();
226 static bool FirstTimeThrough = true;
228 // If none of the target options have changed, then we don't need to reset the
229 // operation actions.
230 if (!FirstTimeThrough && TO == TM.Options) return;
232 if (!FirstTimeThrough) {
233 // Reinitialize the actions.
235 FirstTimeThrough = false;
240 // Set up the TargetLowering object.
241 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
243 // X86 is weird, it always uses i8 for shift amounts and setcc results.
244 setBooleanContents(ZeroOrOneBooleanContent);
245 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
248 // For 64-bit since we have so many registers use the ILP scheduler, for
249 // 32-bit code use the register pressure specific scheduling.
250 // For Atom, always use ILP scheduling.
251 if (Subtarget->isAtom())
252 setSchedulingPreference(Sched::ILP);
253 else if (Subtarget->is64Bit())
254 setSchedulingPreference(Sched::ILP);
256 setSchedulingPreference(Sched::RegPressure);
257 const X86RegisterInfo *RegInfo =
258 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
259 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
261 // Bypass expensive divides on Atom when compiling with O2
262 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263 addBypassSlowDiv(32, 8);
264 if (Subtarget->is64Bit())
265 addBypassSlowDiv(64, 16);
268 if (Subtarget->isTargetKnownWindowsMSVC()) {
269 // Setup Windows compiler runtime calls.
270 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272 setLibcallName(RTLIB::SREM_I64, "_allrem");
273 setLibcallName(RTLIB::UREM_I64, "_aullrem");
274 setLibcallName(RTLIB::MUL_I64, "_allmul");
275 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
281 // The _ftol2 runtime function has an unusual calling conv, which
282 // is modeled by a special pseudo-instruction.
283 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
289 if (Subtarget->isTargetDarwin()) {
290 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291 setUseUnderscoreSetJmp(false);
292 setUseUnderscoreLongJmp(false);
293 } else if (Subtarget->isTargetWindowsGNU()) {
294 // MS runtime is weird: it exports _setjmp, but longjmp!
295 setUseUnderscoreSetJmp(true);
296 setUseUnderscoreLongJmp(false);
298 setUseUnderscoreSetJmp(true);
299 setUseUnderscoreLongJmp(true);
302 // Set up the register classes.
303 addRegisterClass(MVT::i8, &X86::GR8RegClass);
304 addRegisterClass(MVT::i16, &X86::GR16RegClass);
305 addRegisterClass(MVT::i32, &X86::GR32RegClass);
306 if (Subtarget->is64Bit())
307 addRegisterClass(MVT::i64, &X86::GR64RegClass);
309 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
311 // We don't accept any truncstore of integer registers.
312 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
319 // SETOEQ and SETUNE require checking two conditions.
320 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
327 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
329 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
330 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
331 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
333 if (Subtarget->is64Bit()) {
334 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
335 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
336 } else if (!TM.Options.UseSoftFloat) {
337 // We have an algorithm for SSE2->double, and we turn this into a
338 // 64-bit FILD followed by conditional FADD for other targets.
339 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
340 // We have an algorithm for SSE2, and we turn this into a 64-bit
341 // FILD for other targets.
342 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
345 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
347 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
348 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
350 if (!TM.Options.UseSoftFloat) {
351 // SSE has no i16 to fp conversion, only i32
352 if (X86ScalarSSEf32) {
353 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
354 // f32 and f64 cases are Legal, f80 case is not
355 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
357 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
358 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
361 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
362 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
365 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
366 // are Legal, f80 is custom lowered.
367 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
368 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
370 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
372 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
373 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
375 if (X86ScalarSSEf32) {
376 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
377 // f32 and f64 cases are Legal, f80 case is not
378 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
380 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
381 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
384 // Handle FP_TO_UINT by promoting the destination to a larger signed
386 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
387 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
388 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
390 if (Subtarget->is64Bit()) {
391 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
392 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
393 } else if (!TM.Options.UseSoftFloat) {
394 // Since AVX is a superset of SSE3, only check for SSE here.
395 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396 // Expand FP_TO_UINT into a select.
397 // FIXME: We would like to use a Custom expander here eventually to do
398 // the optimal thing for SSE vs. the default expansion in the legalizer.
399 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
401 // With SSE3 we can use fisttpll to convert to a signed i64; without
402 // SSE, we're stuck with a fistpll.
403 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
406 if (isTargetFTOL()) {
407 // Use the _ftol2 runtime function, which has a pseudo-instruction
408 // to handle its weird calling convention.
409 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
412 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413 if (!X86ScalarSSEf64) {
414 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
415 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
416 if (Subtarget->is64Bit()) {
417 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
418 // Without SSE, i64->f64 goes through memory.
419 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
423 // Scalar integer divide and remainder are lowered to use operations that
424 // produce two results, to match the available instructions. This exposes
425 // the two-result form to trivial CSE, which is able to combine x/y and x%y
426 // into a single instruction.
428 // Scalar integer multiply-high is also lowered to use two-result
429 // operations, to match the available instructions. However, plain multiply
430 // (low) operations are left as Legal, as there are single-result
431 // instructions for this in x86. Using the two-result multiply instructions
432 // when both high and low results are needed must be arranged by dagcombine.
433 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
435 setOperationAction(ISD::MULHS, VT, Expand);
436 setOperationAction(ISD::MULHU, VT, Expand);
437 setOperationAction(ISD::SDIV, VT, Expand);
438 setOperationAction(ISD::UDIV, VT, Expand);
439 setOperationAction(ISD::SREM, VT, Expand);
440 setOperationAction(ISD::UREM, VT, Expand);
442 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443 setOperationAction(ISD::ADDC, VT, Custom);
444 setOperationAction(ISD::ADDE, VT, Custom);
445 setOperationAction(ISD::SUBC, VT, Custom);
446 setOperationAction(ISD::SUBE, VT, Custom);
449 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
450 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
451 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
452 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
453 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
454 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
455 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
456 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
457 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
458 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
459 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
460 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
461 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
462 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
463 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
464 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
465 if (Subtarget->is64Bit())
466 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
468 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
469 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
470 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
471 setOperationAction(ISD::FREM , MVT::f32 , Expand);
472 setOperationAction(ISD::FREM , MVT::f64 , Expand);
473 setOperationAction(ISD::FREM , MVT::f80 , Expand);
474 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
476 // Promote the i8 variants and force them on up to i32 which has a shorter
478 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
479 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
480 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
481 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
482 if (Subtarget->hasBMI()) {
483 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
484 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
485 if (Subtarget->is64Bit())
486 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
488 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
489 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
490 if (Subtarget->is64Bit())
491 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
494 if (Subtarget->hasLZCNT()) {
495 // When promoting the i8 variants, force them to i32 for a shorter
497 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
498 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
499 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
500 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
501 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
502 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
503 if (Subtarget->is64Bit())
504 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
506 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
507 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
508 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
509 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
510 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
511 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
512 if (Subtarget->is64Bit()) {
513 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
514 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
518 // Special handling for half-precision floating point conversions.
519 // If we don't have F16C support, then lower half float conversions
520 // into library calls.
521 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
526 // There's never any support for operations beyond MVT::f32.
527 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
532 if (Subtarget->hasPOPCNT()) {
533 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
535 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
536 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
537 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
538 if (Subtarget->is64Bit())
539 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
542 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
544 if (!Subtarget->hasMOVBE())
545 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
547 // These should be promoted to a larger select which is supported.
548 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
549 // X86 wants to expand cmov itself.
550 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
551 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
552 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
553 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
554 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
555 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
556 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
557 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
558 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
559 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
560 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
561 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
562 if (Subtarget->is64Bit()) {
563 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
564 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
566 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
567 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
568 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
569 // support continuation, user-level threading, and etc.. As a result, no
570 // other SjLj exception interfaces are implemented and please don't build
571 // your own exception handling based on them.
572 // LLVM/Clang supports zero-cost DWARF exception handling.
573 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
574 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
577 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
578 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
579 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
580 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
581 if (Subtarget->is64Bit())
582 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
583 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
584 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
585 if (Subtarget->is64Bit()) {
586 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
587 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
588 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
589 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
590 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
592 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
593 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
594 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
595 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
596 if (Subtarget->is64Bit()) {
597 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
598 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
599 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
602 if (Subtarget->hasSSE1())
603 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
605 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
607 // Expand certain atomics
608 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
610 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
611 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
612 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
615 if (Subtarget->hasCmpxchg16b()) {
616 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
619 // FIXME - use subtarget debug flags
620 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
621 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
622 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
625 if (Subtarget->is64Bit()) {
626 setExceptionPointerRegister(X86::RAX);
627 setExceptionSelectorRegister(X86::RDX);
629 setExceptionPointerRegister(X86::EAX);
630 setExceptionSelectorRegister(X86::EDX);
632 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
633 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
635 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
636 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
638 setOperationAction(ISD::TRAP, MVT::Other, Legal);
639 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
641 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
642 setOperationAction(ISD::VASTART , MVT::Other, Custom);
643 setOperationAction(ISD::VAEND , MVT::Other, Expand);
644 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
645 // TargetInfo::X86_64ABIBuiltinVaList
646 setOperationAction(ISD::VAARG , MVT::Other, Custom);
647 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
649 // TargetInfo::CharPtrBuiltinVaList
650 setOperationAction(ISD::VAARG , MVT::Other, Expand);
651 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
654 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
655 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
657 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
658 MVT::i64 : MVT::i32, Custom);
660 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
661 // f32 and f64 use SSE.
662 // Set up the FP register classes.
663 addRegisterClass(MVT::f32, &X86::FR32RegClass);
664 addRegisterClass(MVT::f64, &X86::FR64RegClass);
666 // Use ANDPD to simulate FABS.
667 setOperationAction(ISD::FABS , MVT::f64, Custom);
668 setOperationAction(ISD::FABS , MVT::f32, Custom);
670 // Use XORP to simulate FNEG.
671 setOperationAction(ISD::FNEG , MVT::f64, Custom);
672 setOperationAction(ISD::FNEG , MVT::f32, Custom);
674 // Use ANDPD and ORPD to simulate FCOPYSIGN.
675 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
676 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
678 // Lower this to FGETSIGNx86 plus an AND.
679 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
680 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
682 // We don't support sin/cos/fmod
683 setOperationAction(ISD::FSIN , MVT::f64, Expand);
684 setOperationAction(ISD::FCOS , MVT::f64, Expand);
685 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
686 setOperationAction(ISD::FSIN , MVT::f32, Expand);
687 setOperationAction(ISD::FCOS , MVT::f32, Expand);
688 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
690 // Expand FP immediates into loads from the stack, except for the special
692 addLegalFPImmediate(APFloat(+0.0)); // xorpd
693 addLegalFPImmediate(APFloat(+0.0f)); // xorps
694 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
695 // Use SSE for f32, x87 for f64.
696 // Set up the FP register classes.
697 addRegisterClass(MVT::f32, &X86::FR32RegClass);
698 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
700 // Use ANDPS to simulate FABS.
701 setOperationAction(ISD::FABS , MVT::f32, Custom);
703 // Use XORP to simulate FNEG.
704 setOperationAction(ISD::FNEG , MVT::f32, Custom);
706 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
708 // Use ANDPS and ORPS to simulate FCOPYSIGN.
709 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
710 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
712 // We don't support sin/cos/fmod
713 setOperationAction(ISD::FSIN , MVT::f32, Expand);
714 setOperationAction(ISD::FCOS , MVT::f32, Expand);
715 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
717 // Special cases we handle for FP constants.
718 addLegalFPImmediate(APFloat(+0.0f)); // xorps
719 addLegalFPImmediate(APFloat(+0.0)); // FLD0
720 addLegalFPImmediate(APFloat(+1.0)); // FLD1
721 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
722 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
724 if (!TM.Options.UnsafeFPMath) {
725 setOperationAction(ISD::FSIN , MVT::f64, Expand);
726 setOperationAction(ISD::FCOS , MVT::f64, Expand);
727 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
729 } else if (!TM.Options.UseSoftFloat) {
730 // f32 and f64 in x87.
731 // Set up the FP register classes.
732 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
733 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
735 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
736 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
737 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
738 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
740 if (!TM.Options.UnsafeFPMath) {
741 setOperationAction(ISD::FSIN , MVT::f64, Expand);
742 setOperationAction(ISD::FSIN , MVT::f32, Expand);
743 setOperationAction(ISD::FCOS , MVT::f64, Expand);
744 setOperationAction(ISD::FCOS , MVT::f32, Expand);
745 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
746 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
748 addLegalFPImmediate(APFloat(+0.0)); // FLD0
749 addLegalFPImmediate(APFloat(+1.0)); // FLD1
750 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
751 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
752 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
753 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
754 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
755 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
758 // We don't support FMA.
759 setOperationAction(ISD::FMA, MVT::f64, Expand);
760 setOperationAction(ISD::FMA, MVT::f32, Expand);
762 // Long double always uses X87.
763 if (!TM.Options.UseSoftFloat) {
764 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
765 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
766 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
768 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
769 addLegalFPImmediate(TmpFlt); // FLD0
771 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
774 APFloat TmpFlt2(+1.0);
775 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
777 addLegalFPImmediate(TmpFlt2); // FLD1
778 TmpFlt2.changeSign();
779 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
782 if (!TM.Options.UnsafeFPMath) {
783 setOperationAction(ISD::FSIN , MVT::f80, Expand);
784 setOperationAction(ISD::FCOS , MVT::f80, Expand);
785 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
788 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
789 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
790 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
791 setOperationAction(ISD::FRINT, MVT::f80, Expand);
792 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
793 setOperationAction(ISD::FMA, MVT::f80, Expand);
796 // Always use a library call for pow.
797 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
798 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
799 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
801 setOperationAction(ISD::FLOG, MVT::f80, Expand);
802 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
803 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
804 setOperationAction(ISD::FEXP, MVT::f80, Expand);
805 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
807 // First set operation action for all vector types to either promote
808 // (for widening) or expand (for scalarization). Then we will selectively
809 // turn on ones that can be effectively codegen'd.
810 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
811 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
812 MVT VT = (MVT::SimpleValueType)i;
813 setOperationAction(ISD::ADD , VT, Expand);
814 setOperationAction(ISD::SUB , VT, Expand);
815 setOperationAction(ISD::FADD, VT, Expand);
816 setOperationAction(ISD::FNEG, VT, Expand);
817 setOperationAction(ISD::FSUB, VT, Expand);
818 setOperationAction(ISD::MUL , VT, Expand);
819 setOperationAction(ISD::FMUL, VT, Expand);
820 setOperationAction(ISD::SDIV, VT, Expand);
821 setOperationAction(ISD::UDIV, VT, Expand);
822 setOperationAction(ISD::FDIV, VT, Expand);
823 setOperationAction(ISD::SREM, VT, Expand);
824 setOperationAction(ISD::UREM, VT, Expand);
825 setOperationAction(ISD::LOAD, VT, Expand);
826 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
827 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
828 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
829 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
830 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
831 setOperationAction(ISD::FABS, VT, Expand);
832 setOperationAction(ISD::FSIN, VT, Expand);
833 setOperationAction(ISD::FSINCOS, VT, Expand);
834 setOperationAction(ISD::FCOS, VT, Expand);
835 setOperationAction(ISD::FSINCOS, VT, Expand);
836 setOperationAction(ISD::FREM, VT, Expand);
837 setOperationAction(ISD::FMA, VT, Expand);
838 setOperationAction(ISD::FPOWI, VT, Expand);
839 setOperationAction(ISD::FSQRT, VT, Expand);
840 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
841 setOperationAction(ISD::FFLOOR, VT, Expand);
842 setOperationAction(ISD::FCEIL, VT, Expand);
843 setOperationAction(ISD::FTRUNC, VT, Expand);
844 setOperationAction(ISD::FRINT, VT, Expand);
845 setOperationAction(ISD::FNEARBYINT, VT, Expand);
846 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
847 setOperationAction(ISD::MULHS, VT, Expand);
848 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
849 setOperationAction(ISD::MULHU, VT, Expand);
850 setOperationAction(ISD::SDIVREM, VT, Expand);
851 setOperationAction(ISD::UDIVREM, VT, Expand);
852 setOperationAction(ISD::FPOW, VT, Expand);
853 setOperationAction(ISD::CTPOP, VT, Expand);
854 setOperationAction(ISD::CTTZ, VT, Expand);
855 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
856 setOperationAction(ISD::CTLZ, VT, Expand);
857 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
858 setOperationAction(ISD::SHL, VT, Expand);
859 setOperationAction(ISD::SRA, VT, Expand);
860 setOperationAction(ISD::SRL, VT, Expand);
861 setOperationAction(ISD::ROTL, VT, Expand);
862 setOperationAction(ISD::ROTR, VT, Expand);
863 setOperationAction(ISD::BSWAP, VT, Expand);
864 setOperationAction(ISD::SETCC, VT, Expand);
865 setOperationAction(ISD::FLOG, VT, Expand);
866 setOperationAction(ISD::FLOG2, VT, Expand);
867 setOperationAction(ISD::FLOG10, VT, Expand);
868 setOperationAction(ISD::FEXP, VT, Expand);
869 setOperationAction(ISD::FEXP2, VT, Expand);
870 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
871 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
872 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
873 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
874 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
875 setOperationAction(ISD::TRUNCATE, VT, Expand);
876 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
877 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
878 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
879 setOperationAction(ISD::VSELECT, VT, Expand);
880 setOperationAction(ISD::SELECT_CC, VT, Expand);
881 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
882 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
883 setTruncStoreAction(VT,
884 (MVT::SimpleValueType)InnerVT, Expand);
885 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
886 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
888 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
889 // we have to deal with them whether we ask for Expansion or not. Setting
890 // Expand causes its own optimisation problems though, so leave them legal.
891 if (VT.getVectorElementType() == MVT::i1)
892 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
895 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
896 // with -msoft-float, disable use of MMX as well.
897 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
898 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
899 // No operations on x86mmx supported, everything uses intrinsics.
902 // MMX-sized vectors (other than x86mmx) are expected to be expanded
903 // into smaller operations.
904 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
905 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
906 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
907 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
908 setOperationAction(ISD::AND, MVT::v8i8, Expand);
909 setOperationAction(ISD::AND, MVT::v4i16, Expand);
910 setOperationAction(ISD::AND, MVT::v2i32, Expand);
911 setOperationAction(ISD::AND, MVT::v1i64, Expand);
912 setOperationAction(ISD::OR, MVT::v8i8, Expand);
913 setOperationAction(ISD::OR, MVT::v4i16, Expand);
914 setOperationAction(ISD::OR, MVT::v2i32, Expand);
915 setOperationAction(ISD::OR, MVT::v1i64, Expand);
916 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
917 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
918 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
919 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
920 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
921 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
922 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
923 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
924 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
925 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
926 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
927 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
928 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
929 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
930 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
931 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
932 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
934 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
935 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
937 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
938 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
939 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
940 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
941 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
942 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
943 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
944 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
945 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
946 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
947 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
948 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
951 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
952 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
954 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
955 // registers cannot be used even for integer operations.
956 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
957 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
958 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
959 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
961 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
962 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
963 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
964 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
965 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
966 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
967 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
968 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
969 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
970 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
971 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
972 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
973 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
974 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
975 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
976 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
977 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
978 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
979 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
980 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
981 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
982 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
984 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
985 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
986 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
987 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
989 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
990 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
991 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
992 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
993 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
995 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
996 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
997 MVT VT = (MVT::SimpleValueType)i;
998 // Do not attempt to custom lower non-power-of-2 vectors
999 if (!isPowerOf2_32(VT.getVectorNumElements()))
1001 // Do not attempt to custom lower non-128-bit vectors
1002 if (!VT.is128BitVector())
1004 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1005 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1006 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1009 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1010 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1011 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1012 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1013 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1014 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1016 if (Subtarget->is64Bit()) {
1017 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1018 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1021 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1022 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1023 MVT VT = (MVT::SimpleValueType)i;
1025 // Do not attempt to promote non-128-bit vectors
1026 if (!VT.is128BitVector())
1029 setOperationAction(ISD::AND, VT, Promote);
1030 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1031 setOperationAction(ISD::OR, VT, Promote);
1032 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1033 setOperationAction(ISD::XOR, VT, Promote);
1034 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1035 setOperationAction(ISD::LOAD, VT, Promote);
1036 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1037 setOperationAction(ISD::SELECT, VT, Promote);
1038 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1041 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1043 // Custom lower v2i64 and v2f64 selects.
1044 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1045 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1046 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1047 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1049 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1050 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1052 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1053 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1054 // As there is no 64-bit GPR available, we need build a special custom
1055 // sequence to convert from v2i32 to v2f32.
1056 if (!Subtarget->is64Bit())
1057 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1059 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1060 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1062 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1064 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1065 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1066 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1069 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1070 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1071 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1072 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1073 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1074 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1075 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1076 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1077 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1078 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1079 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1081 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1082 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1083 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1084 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1085 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1086 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1087 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1088 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1089 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1090 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1092 // FIXME: Do we need to handle scalar-to-vector here?
1093 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1095 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1096 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1097 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1098 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1099 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1100 // There is no BLENDI for byte vectors. We don't need to custom lower
1101 // some vselects for now.
1102 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1104 // i8 and i16 vectors are custom , because the source register and source
1105 // source memory operand types are not the same width. f32 vectors are
1106 // custom since the immediate controlling the insert encodes additional
1108 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1109 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1110 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1111 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1113 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1114 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1115 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1116 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1118 // FIXME: these should be Legal but thats only for the case where
1119 // the index is constant. For now custom expand to deal with that.
1120 if (Subtarget->is64Bit()) {
1121 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1122 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1126 if (Subtarget->hasSSE2()) {
1127 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1128 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1130 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1131 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1133 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1134 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1136 // In the customized shift lowering, the legal cases in AVX2 will be
1138 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1139 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1141 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1142 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1144 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1147 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1148 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1149 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1150 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1151 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1152 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1153 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1155 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1156 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1157 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1159 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1160 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1161 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1162 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1163 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1164 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1165 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1166 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1167 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1168 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1169 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1170 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1172 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1173 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1174 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1175 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1176 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1177 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1178 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1179 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1180 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1181 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1182 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1183 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1185 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1186 // even though v8i16 is a legal type.
1187 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1188 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1189 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1191 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1192 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1193 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1195 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1196 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1198 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1200 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1201 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1203 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1204 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1206 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1207 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1209 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1210 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1211 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1212 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1214 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1215 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1216 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1218 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1219 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1220 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1221 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1223 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1224 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1225 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1226 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1227 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1228 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1229 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1230 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1231 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1232 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1233 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1234 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1236 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1237 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1238 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1239 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1240 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1241 setOperationAction(ISD::FMA, MVT::f32, Legal);
1242 setOperationAction(ISD::FMA, MVT::f64, Legal);
1245 if (Subtarget->hasInt256()) {
1246 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1247 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1248 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1249 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1251 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1252 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1253 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1254 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1256 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1257 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1258 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1259 // Don't lower v32i8 because there is no 128-bit byte mul
1261 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1262 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1263 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1264 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1266 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1267 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1269 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1270 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1271 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1272 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1274 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1275 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1276 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1277 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1279 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1280 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1281 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1282 // Don't lower v32i8 because there is no 128-bit byte mul
1285 // In the customized shift lowering, the legal cases in AVX2 will be
1287 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1288 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1290 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1291 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1293 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1295 // Custom lower several nodes for 256-bit types.
1296 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1297 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1298 MVT VT = (MVT::SimpleValueType)i;
1300 // Extract subvector is special because the value type
1301 // (result) is 128-bit but the source is 256-bit wide.
1302 if (VT.is128BitVector())
1303 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1305 // Do not attempt to custom lower other non-256-bit vectors
1306 if (!VT.is256BitVector())
1309 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1310 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1311 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1312 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1313 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1314 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1315 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1318 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1319 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1320 MVT VT = (MVT::SimpleValueType)i;
1322 // Do not attempt to promote non-256-bit vectors
1323 if (!VT.is256BitVector())
1326 setOperationAction(ISD::AND, VT, Promote);
1327 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1328 setOperationAction(ISD::OR, VT, Promote);
1329 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1330 setOperationAction(ISD::XOR, VT, Promote);
1331 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1332 setOperationAction(ISD::LOAD, VT, Promote);
1333 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1334 setOperationAction(ISD::SELECT, VT, Promote);
1335 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1339 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1340 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1341 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1342 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1343 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1345 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1346 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1347 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1349 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1350 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1351 setOperationAction(ISD::XOR, MVT::i1, Legal);
1352 setOperationAction(ISD::OR, MVT::i1, Legal);
1353 setOperationAction(ISD::AND, MVT::i1, Legal);
1354 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1355 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1356 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1357 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1358 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1359 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1361 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1362 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1363 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1364 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1365 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1366 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1368 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1369 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1370 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1371 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1372 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1373 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1374 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1375 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1377 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1378 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1379 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1380 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1381 if (Subtarget->is64Bit()) {
1382 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1383 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1384 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1385 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1387 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1388 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1389 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1390 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1391 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1392 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1393 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1394 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1395 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1396 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1398 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1399 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1400 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1401 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1402 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1403 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1404 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1405 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1406 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1407 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1408 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1409 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1410 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1412 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1413 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1414 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1415 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1416 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1417 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1419 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1420 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1422 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1424 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1425 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1426 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1427 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1428 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1429 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1430 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1431 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1432 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1434 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1435 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1437 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1438 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1440 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1442 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1443 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1445 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1446 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1448 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1449 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1451 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1452 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1453 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1454 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1455 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1456 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1458 if (Subtarget->hasCDI()) {
1459 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1460 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1463 // Custom lower several nodes.
1464 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1465 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1466 MVT VT = (MVT::SimpleValueType)i;
1468 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1469 // Extract subvector is special because the value type
1470 // (result) is 256/128-bit but the source is 512-bit wide.
1471 if (VT.is128BitVector() || VT.is256BitVector())
1472 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1474 if (VT.getVectorElementType() == MVT::i1)
1475 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1477 // Do not attempt to custom lower other non-512-bit vectors
1478 if (!VT.is512BitVector())
1481 if ( EltSize >= 32) {
1482 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1483 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1484 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1485 setOperationAction(ISD::VSELECT, VT, Legal);
1486 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1487 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1488 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1491 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1492 MVT VT = (MVT::SimpleValueType)i;
1494 // Do not attempt to promote non-256-bit vectors
1495 if (!VT.is512BitVector())
1498 setOperationAction(ISD::SELECT, VT, Promote);
1499 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1503 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1504 // of this type with custom code.
1505 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1506 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1507 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1511 // We want to custom lower some of our intrinsics.
1512 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1513 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1514 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1515 if (!Subtarget->is64Bit())
1516 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1518 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1519 // handle type legalization for these operations here.
1521 // FIXME: We really should do custom legalization for addition and
1522 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1523 // than generic legalization for 64-bit multiplication-with-overflow, though.
1524 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1525 // Add/Sub/Mul with overflow operations are custom lowered.
1527 setOperationAction(ISD::SADDO, VT, Custom);
1528 setOperationAction(ISD::UADDO, VT, Custom);
1529 setOperationAction(ISD::SSUBO, VT, Custom);
1530 setOperationAction(ISD::USUBO, VT, Custom);
1531 setOperationAction(ISD::SMULO, VT, Custom);
1532 setOperationAction(ISD::UMULO, VT, Custom);
1535 // There are no 8-bit 3-address imul/mul instructions
1536 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1537 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1539 if (!Subtarget->is64Bit()) {
1540 // These libcalls are not available in 32-bit.
1541 setLibcallName(RTLIB::SHL_I128, nullptr);
1542 setLibcallName(RTLIB::SRL_I128, nullptr);
1543 setLibcallName(RTLIB::SRA_I128, nullptr);
1546 // Combine sin / cos into one node or libcall if possible.
1547 if (Subtarget->hasSinCos()) {
1548 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1549 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1550 if (Subtarget->isTargetDarwin()) {
1551 // For MacOSX, we don't want to the normal expansion of a libcall to
1552 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1554 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1555 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1559 if (Subtarget->isTargetWin64()) {
1560 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1561 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1562 setOperationAction(ISD::SREM, MVT::i128, Custom);
1563 setOperationAction(ISD::UREM, MVT::i128, Custom);
1564 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1565 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1568 // We have target-specific dag combine patterns for the following nodes:
1569 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1570 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1571 setTargetDAGCombine(ISD::VSELECT);
1572 setTargetDAGCombine(ISD::SELECT);
1573 setTargetDAGCombine(ISD::SHL);
1574 setTargetDAGCombine(ISD::SRA);
1575 setTargetDAGCombine(ISD::SRL);
1576 setTargetDAGCombine(ISD::OR);
1577 setTargetDAGCombine(ISD::AND);
1578 setTargetDAGCombine(ISD::ADD);
1579 setTargetDAGCombine(ISD::FADD);
1580 setTargetDAGCombine(ISD::FSUB);
1581 setTargetDAGCombine(ISD::FMA);
1582 setTargetDAGCombine(ISD::SUB);
1583 setTargetDAGCombine(ISD::LOAD);
1584 setTargetDAGCombine(ISD::STORE);
1585 setTargetDAGCombine(ISD::ZERO_EXTEND);
1586 setTargetDAGCombine(ISD::ANY_EXTEND);
1587 setTargetDAGCombine(ISD::SIGN_EXTEND);
1588 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1589 setTargetDAGCombine(ISD::TRUNCATE);
1590 setTargetDAGCombine(ISD::SINT_TO_FP);
1591 setTargetDAGCombine(ISD::SETCC);
1592 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1593 setTargetDAGCombine(ISD::BUILD_VECTOR);
1594 if (Subtarget->is64Bit())
1595 setTargetDAGCombine(ISD::MUL);
1596 setTargetDAGCombine(ISD::XOR);
1598 computeRegisterProperties();
1600 // On Darwin, -Os means optimize for size without hurting performance,
1601 // do not reduce the limit.
1602 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1603 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1604 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1605 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1606 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1607 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1608 setPrefLoopAlignment(4); // 2^4 bytes.
1610 // Predictable cmov don't hurt on atom because it's in-order.
1611 PredictableSelectIsExpensive = !Subtarget->isAtom();
1613 setPrefFunctionAlignment(4); // 2^4 bytes.
1616 TargetLoweringBase::LegalizeTypeAction
1617 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1618 if (ExperimentalVectorWideningLegalization &&
1619 VT.getVectorNumElements() != 1 &&
1620 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1621 return TypeWidenVector;
1623 return TargetLoweringBase::getPreferredVectorAction(VT);
1626 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1628 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1630 if (Subtarget->hasAVX512())
1631 switch(VT.getVectorNumElements()) {
1632 case 8: return MVT::v8i1;
1633 case 16: return MVT::v16i1;
1636 return VT.changeVectorElementTypeToInteger();
1639 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1640 /// the desired ByVal argument alignment.
1641 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1644 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1645 if (VTy->getBitWidth() == 128)
1647 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1648 unsigned EltAlign = 0;
1649 getMaxByValAlign(ATy->getElementType(), EltAlign);
1650 if (EltAlign > MaxAlign)
1651 MaxAlign = EltAlign;
1652 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1653 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1654 unsigned EltAlign = 0;
1655 getMaxByValAlign(STy->getElementType(i), EltAlign);
1656 if (EltAlign > MaxAlign)
1657 MaxAlign = EltAlign;
1664 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1665 /// function arguments in the caller parameter area. For X86, aggregates
1666 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1667 /// are at 4-byte boundaries.
1668 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1669 if (Subtarget->is64Bit()) {
1670 // Max of 8 and alignment of type.
1671 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1678 if (Subtarget->hasSSE1())
1679 getMaxByValAlign(Ty, Align);
1683 /// getOptimalMemOpType - Returns the target specific optimal type for load
1684 /// and store operations as a result of memset, memcpy, and memmove
1685 /// lowering. If DstAlign is zero that means it's safe to destination
1686 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1687 /// means there isn't a need to check it against alignment requirement,
1688 /// probably because the source does not need to be loaded. If 'IsMemset' is
1689 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1690 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1691 /// source is constant so it does not need to be loaded.
1692 /// It returns EVT::Other if the type should be determined using generic
1693 /// target-independent logic.
1695 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1696 unsigned DstAlign, unsigned SrcAlign,
1697 bool IsMemset, bool ZeroMemset,
1699 MachineFunction &MF) const {
1700 const Function *F = MF.getFunction();
1701 if ((!IsMemset || ZeroMemset) &&
1702 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1703 Attribute::NoImplicitFloat)) {
1705 (Subtarget->isUnalignedMemAccessFast() ||
1706 ((DstAlign == 0 || DstAlign >= 16) &&
1707 (SrcAlign == 0 || SrcAlign >= 16)))) {
1709 if (Subtarget->hasInt256())
1711 if (Subtarget->hasFp256())
1714 if (Subtarget->hasSSE2())
1716 if (Subtarget->hasSSE1())
1718 } else if (!MemcpyStrSrc && Size >= 8 &&
1719 !Subtarget->is64Bit() &&
1720 Subtarget->hasSSE2()) {
1721 // Do not use f64 to lower memcpy if source is string constant. It's
1722 // better to use i32 to avoid the loads.
1726 if (Subtarget->is64Bit() && Size >= 8)
1731 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1733 return X86ScalarSSEf32;
1734 else if (VT == MVT::f64)
1735 return X86ScalarSSEf64;
1740 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1744 *Fast = Subtarget->isUnalignedMemAccessFast();
1748 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1749 /// current function. The returned value is a member of the
1750 /// MachineJumpTableInfo::JTEntryKind enum.
1751 unsigned X86TargetLowering::getJumpTableEncoding() const {
1752 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1754 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1755 Subtarget->isPICStyleGOT())
1756 return MachineJumpTableInfo::EK_Custom32;
1758 // Otherwise, use the normal jump table encoding heuristics.
1759 return TargetLowering::getJumpTableEncoding();
1763 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1764 const MachineBasicBlock *MBB,
1765 unsigned uid,MCContext &Ctx) const{
1766 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1767 Subtarget->isPICStyleGOT());
1768 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1770 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1771 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1774 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1776 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1777 SelectionDAG &DAG) const {
1778 if (!Subtarget->is64Bit())
1779 // This doesn't have SDLoc associated with it, but is not really the
1780 // same as a Register.
1781 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1785 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1786 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1788 const MCExpr *X86TargetLowering::
1789 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1790 MCContext &Ctx) const {
1791 // X86-64 uses RIP relative addressing based on the jump table label.
1792 if (Subtarget->isPICStyleRIPRel())
1793 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1795 // Otherwise, the reference is relative to the PIC base.
1796 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1799 // FIXME: Why this routine is here? Move to RegInfo!
1800 std::pair<const TargetRegisterClass*, uint8_t>
1801 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1802 const TargetRegisterClass *RRC = nullptr;
1804 switch (VT.SimpleTy) {
1806 return TargetLowering::findRepresentativeClass(VT);
1807 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1808 RRC = Subtarget->is64Bit() ?
1809 (const TargetRegisterClass*)&X86::GR64RegClass :
1810 (const TargetRegisterClass*)&X86::GR32RegClass;
1813 RRC = &X86::VR64RegClass;
1815 case MVT::f32: case MVT::f64:
1816 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1817 case MVT::v4f32: case MVT::v2f64:
1818 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1820 RRC = &X86::VR128RegClass;
1823 return std::make_pair(RRC, Cost);
1826 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1827 unsigned &Offset) const {
1828 if (!Subtarget->isTargetLinux())
1831 if (Subtarget->is64Bit()) {
1832 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1834 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1846 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1847 unsigned DestAS) const {
1848 assert(SrcAS != DestAS && "Expected different address spaces!");
1850 return SrcAS < 256 && DestAS < 256;
1853 //===----------------------------------------------------------------------===//
1854 // Return Value Calling Convention Implementation
1855 //===----------------------------------------------------------------------===//
1857 #include "X86GenCallingConv.inc"
1860 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1861 MachineFunction &MF, bool isVarArg,
1862 const SmallVectorImpl<ISD::OutputArg> &Outs,
1863 LLVMContext &Context) const {
1864 SmallVector<CCValAssign, 16> RVLocs;
1865 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1867 return CCInfo.CheckReturn(Outs, RetCC_X86);
1870 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1871 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1876 X86TargetLowering::LowerReturn(SDValue Chain,
1877 CallingConv::ID CallConv, bool isVarArg,
1878 const SmallVectorImpl<ISD::OutputArg> &Outs,
1879 const SmallVectorImpl<SDValue> &OutVals,
1880 SDLoc dl, SelectionDAG &DAG) const {
1881 MachineFunction &MF = DAG.getMachineFunction();
1882 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1884 SmallVector<CCValAssign, 16> RVLocs;
1885 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1886 RVLocs, *DAG.getContext());
1887 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1890 SmallVector<SDValue, 6> RetOps;
1891 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1892 // Operand #1 = Bytes To Pop
1893 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1896 // Copy the result values into the output registers.
1897 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1898 CCValAssign &VA = RVLocs[i];
1899 assert(VA.isRegLoc() && "Can only return in registers!");
1900 SDValue ValToCopy = OutVals[i];
1901 EVT ValVT = ValToCopy.getValueType();
1903 // Promote values to the appropriate types
1904 if (VA.getLocInfo() == CCValAssign::SExt)
1905 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1906 else if (VA.getLocInfo() == CCValAssign::ZExt)
1907 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1908 else if (VA.getLocInfo() == CCValAssign::AExt)
1909 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1910 else if (VA.getLocInfo() == CCValAssign::BCvt)
1911 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1913 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1914 "Unexpected FP-extend for return value.");
1916 // If this is x86-64, and we disabled SSE, we can't return FP values,
1917 // or SSE or MMX vectors.
1918 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1919 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1920 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1921 report_fatal_error("SSE register return with SSE disabled");
1923 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1924 // llvm-gcc has never done it right and no one has noticed, so this
1925 // should be OK for now.
1926 if (ValVT == MVT::f64 &&
1927 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1928 report_fatal_error("SSE2 register return with SSE2 disabled");
1930 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1931 // the RET instruction and handled by the FP Stackifier.
1932 if (VA.getLocReg() == X86::ST0 ||
1933 VA.getLocReg() == X86::ST1) {
1934 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1935 // change the value to the FP stack register class.
1936 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1937 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1938 RetOps.push_back(ValToCopy);
1939 // Don't emit a copytoreg.
1943 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1944 // which is returned in RAX / RDX.
1945 if (Subtarget->is64Bit()) {
1946 if (ValVT == MVT::x86mmx) {
1947 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1948 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1949 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1951 // If we don't have SSE2 available, convert to v4f32 so the generated
1952 // register is legal.
1953 if (!Subtarget->hasSSE2())
1954 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1959 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1960 Flag = Chain.getValue(1);
1961 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1964 // The x86-64 ABIs require that for returning structs by value we copy
1965 // the sret argument into %rax/%eax (depending on ABI) for the return.
1966 // Win32 requires us to put the sret argument to %eax as well.
1967 // We saved the argument into a virtual register in the entry block,
1968 // so now we copy the value out and into %rax/%eax.
1969 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1970 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1971 MachineFunction &MF = DAG.getMachineFunction();
1972 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1973 unsigned Reg = FuncInfo->getSRetReturnReg();
1975 "SRetReturnReg should have been set in LowerFormalArguments().");
1976 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1979 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1980 X86::RAX : X86::EAX;
1981 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1982 Flag = Chain.getValue(1);
1984 // RAX/EAX now acts like a return value.
1985 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1988 RetOps[0] = Chain; // Update chain.
1990 // Add the flag if we have it.
1992 RetOps.push_back(Flag);
1994 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1997 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1998 if (N->getNumValues() != 1)
2000 if (!N->hasNUsesOfValue(1, 0))
2003 SDValue TCChain = Chain;
2004 SDNode *Copy = *N->use_begin();
2005 if (Copy->getOpcode() == ISD::CopyToReg) {
2006 // If the copy has a glue operand, we conservatively assume it isn't safe to
2007 // perform a tail call.
2008 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2010 TCChain = Copy->getOperand(0);
2011 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2014 bool HasRet = false;
2015 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2017 if (UI->getOpcode() != X86ISD::RET_FLAG)
2030 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2031 ISD::NodeType ExtendKind) const {
2033 // TODO: Is this also valid on 32-bit?
2034 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2035 ReturnMVT = MVT::i8;
2037 ReturnMVT = MVT::i32;
2039 MVT MinVT = getRegisterType(ReturnMVT);
2040 return VT.bitsLT(MinVT) ? MinVT : VT;
2043 /// LowerCallResult - Lower the result values of a call into the
2044 /// appropriate copies out of appropriate physical registers.
2047 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2048 CallingConv::ID CallConv, bool isVarArg,
2049 const SmallVectorImpl<ISD::InputArg> &Ins,
2050 SDLoc dl, SelectionDAG &DAG,
2051 SmallVectorImpl<SDValue> &InVals) const {
2053 // Assign locations to each value returned by this call.
2054 SmallVector<CCValAssign, 16> RVLocs;
2055 bool Is64Bit = Subtarget->is64Bit();
2056 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2057 DAG.getTarget(), RVLocs, *DAG.getContext());
2058 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2060 // Copy all of the result registers out of their specified physreg.
2061 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2062 CCValAssign &VA = RVLocs[i];
2063 EVT CopyVT = VA.getValVT();
2065 // If this is x86-64, and we disabled SSE, we can't return FP values
2066 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2067 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2068 report_fatal_error("SSE register return with SSE disabled");
2073 // If this is a call to a function that returns an fp value on the floating
2074 // point stack, we must guarantee the value is popped from the stack, so
2075 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2076 // if the return value is not used. We use the FpPOP_RETVAL instruction
2078 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2079 // If we prefer to use the value in xmm registers, copy it out as f80 and
2080 // use a truncate to move it from fp stack reg to xmm reg.
2081 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2082 SDValue Ops[] = { Chain, InFlag };
2083 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2084 MVT::Other, MVT::Glue, Ops), 1);
2085 Val = Chain.getValue(0);
2087 // Round the f80 to the right size, which also moves it to the appropriate
2089 if (CopyVT != VA.getValVT())
2090 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2091 // This truncation won't change the value.
2092 DAG.getIntPtrConstant(1));
2094 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2095 CopyVT, InFlag).getValue(1);
2096 Val = Chain.getValue(0);
2098 InFlag = Chain.getValue(2);
2099 InVals.push_back(Val);
2105 //===----------------------------------------------------------------------===//
2106 // C & StdCall & Fast Calling Convention implementation
2107 //===----------------------------------------------------------------------===//
2108 // StdCall calling convention seems to be standard for many Windows' API
2109 // routines and around. It differs from C calling convention just a little:
2110 // callee should clean up the stack, not caller. Symbols should be also
2111 // decorated in some fancy way :) It doesn't support any vector arguments.
2112 // For info on fast calling convention see Fast Calling Convention (tail call)
2113 // implementation LowerX86_32FastCCCallTo.
2115 /// CallIsStructReturn - Determines whether a call uses struct return
2117 enum StructReturnType {
2122 static StructReturnType
2123 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2125 return NotStructReturn;
2127 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2128 if (!Flags.isSRet())
2129 return NotStructReturn;
2130 if (Flags.isInReg())
2131 return RegStructReturn;
2132 return StackStructReturn;
2135 /// ArgsAreStructReturn - Determines whether a function uses struct
2136 /// return semantics.
2137 static StructReturnType
2138 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2140 return NotStructReturn;
2142 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2143 if (!Flags.isSRet())
2144 return NotStructReturn;
2145 if (Flags.isInReg())
2146 return RegStructReturn;
2147 return StackStructReturn;
2150 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2151 /// by "Src" to address "Dst" with size and alignment information specified by
2152 /// the specific parameter attribute. The copy will be passed as a byval
2153 /// function parameter.
2155 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2156 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2158 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2160 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2161 /*isVolatile*/false, /*AlwaysInline=*/true,
2162 MachinePointerInfo(), MachinePointerInfo());
2165 /// IsTailCallConvention - Return true if the calling convention is one that
2166 /// supports tail call optimization.
2167 static bool IsTailCallConvention(CallingConv::ID CC) {
2168 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2169 CC == CallingConv::HiPE);
2172 /// \brief Return true if the calling convention is a C calling convention.
2173 static bool IsCCallConvention(CallingConv::ID CC) {
2174 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2175 CC == CallingConv::X86_64_SysV);
2178 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2179 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2183 CallingConv::ID CalleeCC = CS.getCallingConv();
2184 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2190 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2191 /// a tailcall target by changing its ABI.
2192 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2193 bool GuaranteedTailCallOpt) {
2194 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2198 X86TargetLowering::LowerMemArgument(SDValue Chain,
2199 CallingConv::ID CallConv,
2200 const SmallVectorImpl<ISD::InputArg> &Ins,
2201 SDLoc dl, SelectionDAG &DAG,
2202 const CCValAssign &VA,
2203 MachineFrameInfo *MFI,
2205 // Create the nodes corresponding to a load from this parameter slot.
2206 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2207 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2208 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2209 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2212 // If value is passed by pointer we have address passed instead of the value
2214 if (VA.getLocInfo() == CCValAssign::Indirect)
2215 ValVT = VA.getLocVT();
2217 ValVT = VA.getValVT();
2219 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2220 // changed with more analysis.
2221 // In case of tail call optimization mark all arguments mutable. Since they
2222 // could be overwritten by lowering of arguments in case of a tail call.
2223 if (Flags.isByVal()) {
2224 unsigned Bytes = Flags.getByValSize();
2225 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2226 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2227 return DAG.getFrameIndex(FI, getPointerTy());
2229 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2230 VA.getLocMemOffset(), isImmutable);
2231 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2232 return DAG.getLoad(ValVT, dl, Chain, FIN,
2233 MachinePointerInfo::getFixedStack(FI),
2234 false, false, false, 0);
2239 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2240 CallingConv::ID CallConv,
2242 const SmallVectorImpl<ISD::InputArg> &Ins,
2245 SmallVectorImpl<SDValue> &InVals)
2247 MachineFunction &MF = DAG.getMachineFunction();
2248 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2250 const Function* Fn = MF.getFunction();
2251 if (Fn->hasExternalLinkage() &&
2252 Subtarget->isTargetCygMing() &&
2253 Fn->getName() == "main")
2254 FuncInfo->setForceFramePointer(true);
2256 MachineFrameInfo *MFI = MF.getFrameInfo();
2257 bool Is64Bit = Subtarget->is64Bit();
2258 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2260 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2261 "Var args not supported with calling convention fastcc, ghc or hipe");
2263 // Assign locations to all of the incoming arguments.
2264 SmallVector<CCValAssign, 16> ArgLocs;
2265 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2266 ArgLocs, *DAG.getContext());
2268 // Allocate shadow area for Win64
2270 CCInfo.AllocateStack(32, 8);
2272 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2274 unsigned LastVal = ~0U;
2276 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2277 CCValAssign &VA = ArgLocs[i];
2278 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2280 assert(VA.getValNo() != LastVal &&
2281 "Don't support value assigned to multiple locs yet");
2283 LastVal = VA.getValNo();
2285 if (VA.isRegLoc()) {
2286 EVT RegVT = VA.getLocVT();
2287 const TargetRegisterClass *RC;
2288 if (RegVT == MVT::i32)
2289 RC = &X86::GR32RegClass;
2290 else if (Is64Bit && RegVT == MVT::i64)
2291 RC = &X86::GR64RegClass;
2292 else if (RegVT == MVT::f32)
2293 RC = &X86::FR32RegClass;
2294 else if (RegVT == MVT::f64)
2295 RC = &X86::FR64RegClass;
2296 else if (RegVT.is512BitVector())
2297 RC = &X86::VR512RegClass;
2298 else if (RegVT.is256BitVector())
2299 RC = &X86::VR256RegClass;
2300 else if (RegVT.is128BitVector())
2301 RC = &X86::VR128RegClass;
2302 else if (RegVT == MVT::x86mmx)
2303 RC = &X86::VR64RegClass;
2304 else if (RegVT == MVT::i1)
2305 RC = &X86::VK1RegClass;
2306 else if (RegVT == MVT::v8i1)
2307 RC = &X86::VK8RegClass;
2308 else if (RegVT == MVT::v16i1)
2309 RC = &X86::VK16RegClass;
2311 llvm_unreachable("Unknown argument type!");
2313 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2314 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2316 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2317 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2319 if (VA.getLocInfo() == CCValAssign::SExt)
2320 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2321 DAG.getValueType(VA.getValVT()));
2322 else if (VA.getLocInfo() == CCValAssign::ZExt)
2323 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2324 DAG.getValueType(VA.getValVT()));
2325 else if (VA.getLocInfo() == CCValAssign::BCvt)
2326 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2328 if (VA.isExtInLoc()) {
2329 // Handle MMX values passed in XMM regs.
2330 if (RegVT.isVector())
2331 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2333 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2336 assert(VA.isMemLoc());
2337 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2340 // If value is passed via pointer - do a load.
2341 if (VA.getLocInfo() == CCValAssign::Indirect)
2342 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2343 MachinePointerInfo(), false, false, false, 0);
2345 InVals.push_back(ArgValue);
2348 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2349 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2350 // The x86-64 ABIs require that for returning structs by value we copy
2351 // the sret argument into %rax/%eax (depending on ABI) for the return.
2352 // Win32 requires us to put the sret argument to %eax as well.
2353 // Save the argument into a virtual register so that we can access it
2354 // from the return points.
2355 if (Ins[i].Flags.isSRet()) {
2356 unsigned Reg = FuncInfo->getSRetReturnReg();
2358 MVT PtrTy = getPointerTy();
2359 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2360 FuncInfo->setSRetReturnReg(Reg);
2362 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2363 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2369 unsigned StackSize = CCInfo.getNextStackOffset();
2370 // Align stack specially for tail calls.
2371 if (FuncIsMadeTailCallSafe(CallConv,
2372 MF.getTarget().Options.GuaranteedTailCallOpt))
2373 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2375 // If the function takes variable number of arguments, make a frame index for
2376 // the start of the first vararg value... for expansion of llvm.va_start.
2378 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2379 CallConv != CallingConv::X86_ThisCall)) {
2380 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2383 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2385 // FIXME: We should really autogenerate these arrays
2386 static const MCPhysReg GPR64ArgRegsWin64[] = {
2387 X86::RCX, X86::RDX, X86::R8, X86::R9
2389 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2390 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2392 static const MCPhysReg XMMArgRegs64Bit[] = {
2393 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2394 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2396 const MCPhysReg *GPR64ArgRegs;
2397 unsigned NumXMMRegs = 0;
2400 // The XMM registers which might contain var arg parameters are shadowed
2401 // in their paired GPR. So we only need to save the GPR to their home
2403 TotalNumIntRegs = 4;
2404 GPR64ArgRegs = GPR64ArgRegsWin64;
2406 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2407 GPR64ArgRegs = GPR64ArgRegs64Bit;
2409 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2412 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2415 bool NoImplicitFloatOps = Fn->getAttributes().
2416 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2417 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2418 "SSE register cannot be used when SSE is disabled!");
2419 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2420 NoImplicitFloatOps) &&
2421 "SSE register cannot be used when SSE is disabled!");
2422 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2423 !Subtarget->hasSSE1())
2424 // Kernel mode asks for SSE to be disabled, so don't push them
2426 TotalNumXMMRegs = 0;
2429 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2430 // Get to the caller-allocated home save location. Add 8 to account
2431 // for the return address.
2432 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2433 FuncInfo->setRegSaveFrameIndex(
2434 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2435 // Fixup to set vararg frame on shadow area (4 x i64).
2437 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2439 // For X86-64, if there are vararg parameters that are passed via
2440 // registers, then we must store them to their spots on the stack so
2441 // they may be loaded by deferencing the result of va_next.
2442 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2443 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2444 FuncInfo->setRegSaveFrameIndex(
2445 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2449 // Store the integer parameter registers.
2450 SmallVector<SDValue, 8> MemOps;
2451 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2453 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2454 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2455 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2456 DAG.getIntPtrConstant(Offset));
2457 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2458 &X86::GR64RegClass);
2459 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2461 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2462 MachinePointerInfo::getFixedStack(
2463 FuncInfo->getRegSaveFrameIndex(), Offset),
2465 MemOps.push_back(Store);
2469 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2470 // Now store the XMM (fp + vector) parameter registers.
2471 SmallVector<SDValue, 11> SaveXMMOps;
2472 SaveXMMOps.push_back(Chain);
2474 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2475 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2476 SaveXMMOps.push_back(ALVal);
2478 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2479 FuncInfo->getRegSaveFrameIndex()));
2480 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2481 FuncInfo->getVarArgsFPOffset()));
2483 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2484 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2485 &X86::VR128RegClass);
2486 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2487 SaveXMMOps.push_back(Val);
2489 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2490 MVT::Other, SaveXMMOps));
2493 if (!MemOps.empty())
2494 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2498 // Some CCs need callee pop.
2499 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2500 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2501 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2503 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2504 // If this is an sret function, the return should pop the hidden pointer.
2505 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2506 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2507 argsAreStructReturn(Ins) == StackStructReturn)
2508 FuncInfo->setBytesToPopOnReturn(4);
2512 // RegSaveFrameIndex is X86-64 only.
2513 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2514 if (CallConv == CallingConv::X86_FastCall ||
2515 CallConv == CallingConv::X86_ThisCall)
2516 // fastcc functions can't have varargs.
2517 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2520 FuncInfo->setArgumentStackSize(StackSize);
2526 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2527 SDValue StackPtr, SDValue Arg,
2528 SDLoc dl, SelectionDAG &DAG,
2529 const CCValAssign &VA,
2530 ISD::ArgFlagsTy Flags) const {
2531 unsigned LocMemOffset = VA.getLocMemOffset();
2532 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2533 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2534 if (Flags.isByVal())
2535 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2537 return DAG.getStore(Chain, dl, Arg, PtrOff,
2538 MachinePointerInfo::getStack(LocMemOffset),
2542 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2543 /// optimization is performed and it is required.
2545 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2546 SDValue &OutRetAddr, SDValue Chain,
2547 bool IsTailCall, bool Is64Bit,
2548 int FPDiff, SDLoc dl) const {
2549 // Adjust the Return address stack slot.
2550 EVT VT = getPointerTy();
2551 OutRetAddr = getReturnAddressFrameIndex(DAG);
2553 // Load the "old" Return address.
2554 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2555 false, false, false, 0);
2556 return SDValue(OutRetAddr.getNode(), 1);
2559 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2560 /// optimization is performed and it is required (FPDiff!=0).
2561 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2562 SDValue Chain, SDValue RetAddrFrIdx,
2563 EVT PtrVT, unsigned SlotSize,
2564 int FPDiff, SDLoc dl) {
2565 // Store the return address to the appropriate stack slot.
2566 if (!FPDiff) return Chain;
2567 // Calculate the new stack slot for the return address.
2568 int NewReturnAddrFI =
2569 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2571 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2572 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2573 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2579 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2580 SmallVectorImpl<SDValue> &InVals) const {
2581 SelectionDAG &DAG = CLI.DAG;
2583 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2584 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2585 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2586 SDValue Chain = CLI.Chain;
2587 SDValue Callee = CLI.Callee;
2588 CallingConv::ID CallConv = CLI.CallConv;
2589 bool &isTailCall = CLI.IsTailCall;
2590 bool isVarArg = CLI.IsVarArg;
2592 MachineFunction &MF = DAG.getMachineFunction();
2593 bool Is64Bit = Subtarget->is64Bit();
2594 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2595 StructReturnType SR = callIsStructReturn(Outs);
2596 bool IsSibcall = false;
2598 if (MF.getTarget().Options.DisableTailCalls)
2601 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2603 // Force this to be a tail call. The verifier rules are enough to ensure
2604 // that we can lower this successfully without moving the return address
2607 } else if (isTailCall) {
2608 // Check if it's really possible to do a tail call.
2609 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2610 isVarArg, SR != NotStructReturn,
2611 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2612 Outs, OutVals, Ins, DAG);
2614 // Sibcalls are automatically detected tailcalls which do not require
2616 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2623 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2624 "Var args not supported with calling convention fastcc, ghc or hipe");
2626 // Analyze operands of the call, assigning locations to each operand.
2627 SmallVector<CCValAssign, 16> ArgLocs;
2628 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2629 ArgLocs, *DAG.getContext());
2631 // Allocate shadow area for Win64
2633 CCInfo.AllocateStack(32, 8);
2635 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2637 // Get a count of how many bytes are to be pushed on the stack.
2638 unsigned NumBytes = CCInfo.getNextStackOffset();
2640 // This is a sibcall. The memory operands are available in caller's
2641 // own caller's stack.
2643 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2644 IsTailCallConvention(CallConv))
2645 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2648 if (isTailCall && !IsSibcall && !IsMustTail) {
2649 // Lower arguments at fp - stackoffset + fpdiff.
2650 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2651 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2653 FPDiff = NumBytesCallerPushed - NumBytes;
2655 // Set the delta of movement of the returnaddr stackslot.
2656 // But only set if delta is greater than previous delta.
2657 if (FPDiff < X86Info->getTCReturnAddrDelta())
2658 X86Info->setTCReturnAddrDelta(FPDiff);
2661 unsigned NumBytesToPush = NumBytes;
2662 unsigned NumBytesToPop = NumBytes;
2664 // If we have an inalloca argument, all stack space has already been allocated
2665 // for us and be right at the top of the stack. We don't support multiple
2666 // arguments passed in memory when using inalloca.
2667 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2669 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2670 "an inalloca argument must be the only memory argument");
2674 Chain = DAG.getCALLSEQ_START(
2675 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2677 SDValue RetAddrFrIdx;
2678 // Load return address for tail calls.
2679 if (isTailCall && FPDiff)
2680 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2681 Is64Bit, FPDiff, dl);
2683 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2684 SmallVector<SDValue, 8> MemOpChains;
2687 // Walk the register/memloc assignments, inserting copies/loads. In the case
2688 // of tail call optimization arguments are handle later.
2689 const X86RegisterInfo *RegInfo =
2690 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2691 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2692 // Skip inalloca arguments, they have already been written.
2693 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2694 if (Flags.isInAlloca())
2697 CCValAssign &VA = ArgLocs[i];
2698 EVT RegVT = VA.getLocVT();
2699 SDValue Arg = OutVals[i];
2700 bool isByVal = Flags.isByVal();
2702 // Promote the value if needed.
2703 switch (VA.getLocInfo()) {
2704 default: llvm_unreachable("Unknown loc info!");
2705 case CCValAssign::Full: break;
2706 case CCValAssign::SExt:
2707 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2709 case CCValAssign::ZExt:
2710 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2712 case CCValAssign::AExt:
2713 if (RegVT.is128BitVector()) {
2714 // Special case: passing MMX values in XMM registers.
2715 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2716 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2717 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2719 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2721 case CCValAssign::BCvt:
2722 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2724 case CCValAssign::Indirect: {
2725 // Store the argument.
2726 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2727 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2728 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2729 MachinePointerInfo::getFixedStack(FI),
2736 if (VA.isRegLoc()) {
2737 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2738 if (isVarArg && IsWin64) {
2739 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2740 // shadow reg if callee is a varargs function.
2741 unsigned ShadowReg = 0;
2742 switch (VA.getLocReg()) {
2743 case X86::XMM0: ShadowReg = X86::RCX; break;
2744 case X86::XMM1: ShadowReg = X86::RDX; break;
2745 case X86::XMM2: ShadowReg = X86::R8; break;
2746 case X86::XMM3: ShadowReg = X86::R9; break;
2749 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2751 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2752 assert(VA.isMemLoc());
2753 if (!StackPtr.getNode())
2754 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2756 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2757 dl, DAG, VA, Flags));
2761 if (!MemOpChains.empty())
2762 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2764 if (Subtarget->isPICStyleGOT()) {
2765 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2768 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2769 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2771 // If we are tail calling and generating PIC/GOT style code load the
2772 // address of the callee into ECX. The value in ecx is used as target of
2773 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2774 // for tail calls on PIC/GOT architectures. Normally we would just put the
2775 // address of GOT into ebx and then call target@PLT. But for tail calls
2776 // ebx would be restored (since ebx is callee saved) before jumping to the
2779 // Note: The actual moving to ECX is done further down.
2780 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2781 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2782 !G->getGlobal()->hasProtectedVisibility())
2783 Callee = LowerGlobalAddress(Callee, DAG);
2784 else if (isa<ExternalSymbolSDNode>(Callee))
2785 Callee = LowerExternalSymbol(Callee, DAG);
2789 if (Is64Bit && isVarArg && !IsWin64) {
2790 // From AMD64 ABI document:
2791 // For calls that may call functions that use varargs or stdargs
2792 // (prototype-less calls or calls to functions containing ellipsis (...) in
2793 // the declaration) %al is used as hidden argument to specify the number
2794 // of SSE registers used. The contents of %al do not need to match exactly
2795 // the number of registers, but must be an ubound on the number of SSE
2796 // registers used and is in the range 0 - 8 inclusive.
2798 // Count the number of XMM registers allocated.
2799 static const MCPhysReg XMMArgRegs[] = {
2800 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2801 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2803 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2804 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2805 && "SSE registers cannot be used when SSE is disabled");
2807 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2808 DAG.getConstant(NumXMMRegs, MVT::i8)));
2811 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2812 // don't need this because the eligibility check rejects calls that require
2813 // shuffling arguments passed in memory.
2814 if (!IsSibcall && isTailCall) {
2815 // Force all the incoming stack arguments to be loaded from the stack
2816 // before any new outgoing arguments are stored to the stack, because the
2817 // outgoing stack slots may alias the incoming argument stack slots, and
2818 // the alias isn't otherwise explicit. This is slightly more conservative
2819 // than necessary, because it means that each store effectively depends
2820 // on every argument instead of just those arguments it would clobber.
2821 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2823 SmallVector<SDValue, 8> MemOpChains2;
2826 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2827 CCValAssign &VA = ArgLocs[i];
2830 assert(VA.isMemLoc());
2831 SDValue Arg = OutVals[i];
2832 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2833 // Skip inalloca arguments. They don't require any work.
2834 if (Flags.isInAlloca())
2836 // Create frame index.
2837 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2838 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2839 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2840 FIN = DAG.getFrameIndex(FI, getPointerTy());
2842 if (Flags.isByVal()) {
2843 // Copy relative to framepointer.
2844 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2845 if (!StackPtr.getNode())
2846 StackPtr = DAG.getCopyFromReg(Chain, dl,
2847 RegInfo->getStackRegister(),
2849 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2851 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2855 // Store relative to framepointer.
2856 MemOpChains2.push_back(
2857 DAG.getStore(ArgChain, dl, Arg, FIN,
2858 MachinePointerInfo::getFixedStack(FI),
2863 if (!MemOpChains2.empty())
2864 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2866 // Store the return address to the appropriate stack slot.
2867 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2868 getPointerTy(), RegInfo->getSlotSize(),
2872 // Build a sequence of copy-to-reg nodes chained together with token chain
2873 // and flag operands which copy the outgoing args into registers.
2875 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2876 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2877 RegsToPass[i].second, InFlag);
2878 InFlag = Chain.getValue(1);
2881 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2882 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2883 // In the 64-bit large code model, we have to make all calls
2884 // through a register, since the call instruction's 32-bit
2885 // pc-relative offset may not be large enough to hold the whole
2887 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2888 // If the callee is a GlobalAddress node (quite common, every direct call
2889 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2892 // We should use extra load for direct calls to dllimported functions in
2894 const GlobalValue *GV = G->getGlobal();
2895 if (!GV->hasDLLImportStorageClass()) {
2896 unsigned char OpFlags = 0;
2897 bool ExtraLoad = false;
2898 unsigned WrapperKind = ISD::DELETED_NODE;
2900 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2901 // external symbols most go through the PLT in PIC mode. If the symbol
2902 // has hidden or protected visibility, or if it is static or local, then
2903 // we don't need to use the PLT - we can directly call it.
2904 if (Subtarget->isTargetELF() &&
2905 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2906 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2907 OpFlags = X86II::MO_PLT;
2908 } else if (Subtarget->isPICStyleStubAny() &&
2909 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2910 (!Subtarget->getTargetTriple().isMacOSX() ||
2911 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2912 // PC-relative references to external symbols should go through $stub,
2913 // unless we're building with the leopard linker or later, which
2914 // automatically synthesizes these stubs.
2915 OpFlags = X86II::MO_DARWIN_STUB;
2916 } else if (Subtarget->isPICStyleRIPRel() &&
2917 isa<Function>(GV) &&
2918 cast<Function>(GV)->getAttributes().
2919 hasAttribute(AttributeSet::FunctionIndex,
2920 Attribute::NonLazyBind)) {
2921 // If the function is marked as non-lazy, generate an indirect call
2922 // which loads from the GOT directly. This avoids runtime overhead
2923 // at the cost of eager binding (and one extra byte of encoding).
2924 OpFlags = X86II::MO_GOTPCREL;
2925 WrapperKind = X86ISD::WrapperRIP;
2929 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2930 G->getOffset(), OpFlags);
2932 // Add a wrapper if needed.
2933 if (WrapperKind != ISD::DELETED_NODE)
2934 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2935 // Add extra indirection if needed.
2937 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2938 MachinePointerInfo::getGOT(),
2939 false, false, false, 0);
2941 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2942 unsigned char OpFlags = 0;
2944 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2945 // external symbols should go through the PLT.
2946 if (Subtarget->isTargetELF() &&
2947 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2948 OpFlags = X86II::MO_PLT;
2949 } else if (Subtarget->isPICStyleStubAny() &&
2950 (!Subtarget->getTargetTriple().isMacOSX() ||
2951 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2952 // PC-relative references to external symbols should go through $stub,
2953 // unless we're building with the leopard linker or later, which
2954 // automatically synthesizes these stubs.
2955 OpFlags = X86II::MO_DARWIN_STUB;
2958 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2962 // Returns a chain & a flag for retval copy to use.
2963 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2964 SmallVector<SDValue, 8> Ops;
2966 if (!IsSibcall && isTailCall) {
2967 Chain = DAG.getCALLSEQ_END(Chain,
2968 DAG.getIntPtrConstant(NumBytesToPop, true),
2969 DAG.getIntPtrConstant(0, true), InFlag, dl);
2970 InFlag = Chain.getValue(1);
2973 Ops.push_back(Chain);
2974 Ops.push_back(Callee);
2977 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2979 // Add argument registers to the end of the list so that they are known live
2981 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2982 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2983 RegsToPass[i].second.getValueType()));
2985 // Add a register mask operand representing the call-preserved registers.
2986 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2987 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2988 assert(Mask && "Missing call preserved mask for calling convention");
2989 Ops.push_back(DAG.getRegisterMask(Mask));
2991 if (InFlag.getNode())
2992 Ops.push_back(InFlag);
2996 //// If this is the first return lowered for this function, add the regs
2997 //// to the liveout set for the function.
2998 // This isn't right, although it's probably harmless on x86; liveouts
2999 // should be computed from returns not tail calls. Consider a void
3000 // function making a tail call to a function returning int.
3001 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3004 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3005 InFlag = Chain.getValue(1);
3007 // Create the CALLSEQ_END node.
3008 unsigned NumBytesForCalleeToPop;
3009 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3010 DAG.getTarget().Options.GuaranteedTailCallOpt))
3011 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3012 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3013 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3014 SR == StackStructReturn)
3015 // If this is a call to a struct-return function, the callee
3016 // pops the hidden struct pointer, so we have to push it back.
3017 // This is common for Darwin/X86, Linux & Mingw32 targets.
3018 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3019 NumBytesForCalleeToPop = 4;
3021 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3023 // Returns a flag for retval copy to use.
3025 Chain = DAG.getCALLSEQ_END(Chain,
3026 DAG.getIntPtrConstant(NumBytesToPop, true),
3027 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3030 InFlag = Chain.getValue(1);
3033 // Handle result values, copying them out of physregs into vregs that we
3035 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3036 Ins, dl, DAG, InVals);
3039 //===----------------------------------------------------------------------===//
3040 // Fast Calling Convention (tail call) implementation
3041 //===----------------------------------------------------------------------===//
3043 // Like std call, callee cleans arguments, convention except that ECX is
3044 // reserved for storing the tail called function address. Only 2 registers are
3045 // free for argument passing (inreg). Tail call optimization is performed
3047 // * tailcallopt is enabled
3048 // * caller/callee are fastcc
3049 // On X86_64 architecture with GOT-style position independent code only local
3050 // (within module) calls are supported at the moment.
3051 // To keep the stack aligned according to platform abi the function
3052 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3053 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3054 // If a tail called function callee has more arguments than the caller the
3055 // caller needs to make sure that there is room to move the RETADDR to. This is
3056 // achieved by reserving an area the size of the argument delta right after the
3057 // original RETADDR, but before the saved framepointer or the spilled registers
3058 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3070 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3071 /// for a 16 byte align requirement.
3073 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3074 SelectionDAG& DAG) const {
3075 MachineFunction &MF = DAG.getMachineFunction();
3076 const TargetMachine &TM = MF.getTarget();
3077 const X86RegisterInfo *RegInfo =
3078 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3079 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3080 unsigned StackAlignment = TFI.getStackAlignment();
3081 uint64_t AlignMask = StackAlignment - 1;
3082 int64_t Offset = StackSize;
3083 unsigned SlotSize = RegInfo->getSlotSize();
3084 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3085 // Number smaller than 12 so just add the difference.
3086 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3088 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3089 Offset = ((~AlignMask) & Offset) + StackAlignment +
3090 (StackAlignment-SlotSize);
3095 /// MatchingStackOffset - Return true if the given stack call argument is
3096 /// already available in the same position (relatively) of the caller's
3097 /// incoming argument stack.
3099 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3100 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3101 const X86InstrInfo *TII) {
3102 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3104 if (Arg.getOpcode() == ISD::CopyFromReg) {
3105 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3106 if (!TargetRegisterInfo::isVirtualRegister(VR))
3108 MachineInstr *Def = MRI->getVRegDef(VR);
3111 if (!Flags.isByVal()) {
3112 if (!TII->isLoadFromStackSlot(Def, FI))
3115 unsigned Opcode = Def->getOpcode();
3116 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3117 Def->getOperand(1).isFI()) {
3118 FI = Def->getOperand(1).getIndex();
3119 Bytes = Flags.getByValSize();
3123 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3124 if (Flags.isByVal())
3125 // ByVal argument is passed in as a pointer but it's now being
3126 // dereferenced. e.g.
3127 // define @foo(%struct.X* %A) {
3128 // tail call @bar(%struct.X* byval %A)
3131 SDValue Ptr = Ld->getBasePtr();
3132 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3135 FI = FINode->getIndex();
3136 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3137 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3138 FI = FINode->getIndex();
3139 Bytes = Flags.getByValSize();
3143 assert(FI != INT_MAX);
3144 if (!MFI->isFixedObjectIndex(FI))
3146 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3149 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3150 /// for tail call optimization. Targets which want to do tail call
3151 /// optimization should implement this function.
3153 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3154 CallingConv::ID CalleeCC,
3156 bool isCalleeStructRet,
3157 bool isCallerStructRet,
3159 const SmallVectorImpl<ISD::OutputArg> &Outs,
3160 const SmallVectorImpl<SDValue> &OutVals,
3161 const SmallVectorImpl<ISD::InputArg> &Ins,
3162 SelectionDAG &DAG) const {
3163 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3166 // If -tailcallopt is specified, make fastcc functions tail-callable.
3167 const MachineFunction &MF = DAG.getMachineFunction();
3168 const Function *CallerF = MF.getFunction();
3170 // If the function return type is x86_fp80 and the callee return type is not,
3171 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3172 // perform a tailcall optimization here.
3173 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3176 CallingConv::ID CallerCC = CallerF->getCallingConv();
3177 bool CCMatch = CallerCC == CalleeCC;
3178 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3179 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3181 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3182 if (IsTailCallConvention(CalleeCC) && CCMatch)
3187 // Look for obvious safe cases to perform tail call optimization that do not
3188 // require ABI changes. This is what gcc calls sibcall.
3190 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3191 // emit a special epilogue.
3192 const X86RegisterInfo *RegInfo =
3193 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3194 if (RegInfo->needsStackRealignment(MF))
3197 // Also avoid sibcall optimization if either caller or callee uses struct
3198 // return semantics.
3199 if (isCalleeStructRet || isCallerStructRet)
3202 // An stdcall/thiscall caller is expected to clean up its arguments; the
3203 // callee isn't going to do that.
3204 // FIXME: this is more restrictive than needed. We could produce a tailcall
3205 // when the stack adjustment matches. For example, with a thiscall that takes
3206 // only one argument.
3207 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3208 CallerCC == CallingConv::X86_ThisCall))
3211 // Do not sibcall optimize vararg calls unless all arguments are passed via
3213 if (isVarArg && !Outs.empty()) {
3215 // Optimizing for varargs on Win64 is unlikely to be safe without
3216 // additional testing.
3217 if (IsCalleeWin64 || IsCallerWin64)
3220 SmallVector<CCValAssign, 16> ArgLocs;
3221 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3222 DAG.getTarget(), ArgLocs, *DAG.getContext());
3224 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3225 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3226 if (!ArgLocs[i].isRegLoc())
3230 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3231 // stack. Therefore, if it's not used by the call it is not safe to optimize
3232 // this into a sibcall.
3233 bool Unused = false;
3234 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3241 SmallVector<CCValAssign, 16> RVLocs;
3242 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3243 DAG.getTarget(), RVLocs, *DAG.getContext());
3244 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3245 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3246 CCValAssign &VA = RVLocs[i];
3247 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3252 // If the calling conventions do not match, then we'd better make sure the
3253 // results are returned in the same way as what the caller expects.
3255 SmallVector<CCValAssign, 16> RVLocs1;
3256 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3257 DAG.getTarget(), RVLocs1, *DAG.getContext());
3258 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3260 SmallVector<CCValAssign, 16> RVLocs2;
3261 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3262 DAG.getTarget(), RVLocs2, *DAG.getContext());
3263 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3265 if (RVLocs1.size() != RVLocs2.size())
3267 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3268 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3270 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3272 if (RVLocs1[i].isRegLoc()) {
3273 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3276 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3282 // If the callee takes no arguments then go on to check the results of the
3284 if (!Outs.empty()) {
3285 // Check if stack adjustment is needed. For now, do not do this if any
3286 // argument is passed on the stack.
3287 SmallVector<CCValAssign, 16> ArgLocs;
3288 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3289 DAG.getTarget(), ArgLocs, *DAG.getContext());
3291 // Allocate shadow area for Win64
3293 CCInfo.AllocateStack(32, 8);
3295 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3296 if (CCInfo.getNextStackOffset()) {
3297 MachineFunction &MF = DAG.getMachineFunction();
3298 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3301 // Check if the arguments are already laid out in the right way as
3302 // the caller's fixed stack objects.
3303 MachineFrameInfo *MFI = MF.getFrameInfo();
3304 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3305 const X86InstrInfo *TII =
3306 static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3307 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3308 CCValAssign &VA = ArgLocs[i];
3309 SDValue Arg = OutVals[i];
3310 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3311 if (VA.getLocInfo() == CCValAssign::Indirect)
3313 if (!VA.isRegLoc()) {
3314 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3321 // If the tailcall address may be in a register, then make sure it's
3322 // possible to register allocate for it. In 32-bit, the call address can
3323 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3324 // callee-saved registers are restored. These happen to be the same
3325 // registers used to pass 'inreg' arguments so watch out for those.
3326 if (!Subtarget->is64Bit() &&
3327 ((!isa<GlobalAddressSDNode>(Callee) &&
3328 !isa<ExternalSymbolSDNode>(Callee)) ||
3329 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3330 unsigned NumInRegs = 0;
3331 // In PIC we need an extra register to formulate the address computation
3333 unsigned MaxInRegs =
3334 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3336 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3337 CCValAssign &VA = ArgLocs[i];
3340 unsigned Reg = VA.getLocReg();
3343 case X86::EAX: case X86::EDX: case X86::ECX:
3344 if (++NumInRegs == MaxInRegs)
3356 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3357 const TargetLibraryInfo *libInfo) const {
3358 return X86::createFastISel(funcInfo, libInfo);
3361 //===----------------------------------------------------------------------===//
3362 // Other Lowering Hooks
3363 //===----------------------------------------------------------------------===//
3365 static bool MayFoldLoad(SDValue Op) {
3366 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3369 static bool MayFoldIntoStore(SDValue Op) {
3370 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3373 static bool isTargetShuffle(unsigned Opcode) {
3375 default: return false;
3376 case X86ISD::PSHUFD:
3377 case X86ISD::PSHUFHW:
3378 case X86ISD::PSHUFLW:
3380 case X86ISD::PALIGNR:
3381 case X86ISD::MOVLHPS:
3382 case X86ISD::MOVLHPD:
3383 case X86ISD::MOVHLPS:
3384 case X86ISD::MOVLPS:
3385 case X86ISD::MOVLPD:
3386 case X86ISD::MOVSHDUP:
3387 case X86ISD::MOVSLDUP:
3388 case X86ISD::MOVDDUP:
3391 case X86ISD::UNPCKL:
3392 case X86ISD::UNPCKH:
3393 case X86ISD::VPERMILP:
3394 case X86ISD::VPERM2X128:
3395 case X86ISD::VPERMI:
3400 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3401 SDValue V1, SelectionDAG &DAG) {
3403 default: llvm_unreachable("Unknown x86 shuffle node");
3404 case X86ISD::MOVSHDUP:
3405 case X86ISD::MOVSLDUP:
3406 case X86ISD::MOVDDUP:
3407 return DAG.getNode(Opc, dl, VT, V1);
3411 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3412 SDValue V1, unsigned TargetMask,
3413 SelectionDAG &DAG) {
3415 default: llvm_unreachable("Unknown x86 shuffle node");
3416 case X86ISD::PSHUFD:
3417 case X86ISD::PSHUFHW:
3418 case X86ISD::PSHUFLW:
3419 case X86ISD::VPERMILP:
3420 case X86ISD::VPERMI:
3421 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3425 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3426 SDValue V1, SDValue V2, unsigned TargetMask,
3427 SelectionDAG &DAG) {
3429 default: llvm_unreachable("Unknown x86 shuffle node");
3430 case X86ISD::PALIGNR:
3432 case X86ISD::VPERM2X128:
3433 return DAG.getNode(Opc, dl, VT, V1, V2,
3434 DAG.getConstant(TargetMask, MVT::i8));
3438 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3439 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3441 default: llvm_unreachable("Unknown x86 shuffle node");
3442 case X86ISD::MOVLHPS:
3443 case X86ISD::MOVLHPD:
3444 case X86ISD::MOVHLPS:
3445 case X86ISD::MOVLPS:
3446 case X86ISD::MOVLPD:
3449 case X86ISD::UNPCKL:
3450 case X86ISD::UNPCKH:
3451 return DAG.getNode(Opc, dl, VT, V1, V2);
3455 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3456 MachineFunction &MF = DAG.getMachineFunction();
3457 const X86RegisterInfo *RegInfo =
3458 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3459 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3460 int ReturnAddrIndex = FuncInfo->getRAIndex();
3462 if (ReturnAddrIndex == 0) {
3463 // Set up a frame object for the return address.
3464 unsigned SlotSize = RegInfo->getSlotSize();
3465 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3468 FuncInfo->setRAIndex(ReturnAddrIndex);
3471 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3474 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3475 bool hasSymbolicDisplacement) {
3476 // Offset should fit into 32 bit immediate field.
3477 if (!isInt<32>(Offset))
3480 // If we don't have a symbolic displacement - we don't have any extra
3482 if (!hasSymbolicDisplacement)
3485 // FIXME: Some tweaks might be needed for medium code model.
3486 if (M != CodeModel::Small && M != CodeModel::Kernel)
3489 // For small code model we assume that latest object is 16MB before end of 31
3490 // bits boundary. We may also accept pretty large negative constants knowing
3491 // that all objects are in the positive half of address space.
3492 if (M == CodeModel::Small && Offset < 16*1024*1024)
3495 // For kernel code model we know that all object resist in the negative half
3496 // of 32bits address space. We may not accept negative offsets, since they may
3497 // be just off and we may accept pretty large positive ones.
3498 if (M == CodeModel::Kernel && Offset > 0)
3504 /// isCalleePop - Determines whether the callee is required to pop its
3505 /// own arguments. Callee pop is necessary to support tail calls.
3506 bool X86::isCalleePop(CallingConv::ID CallingConv,
3507 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3511 switch (CallingConv) {
3514 case CallingConv::X86_StdCall:
3516 case CallingConv::X86_FastCall:
3518 case CallingConv::X86_ThisCall:
3520 case CallingConv::Fast:
3522 case CallingConv::GHC:
3524 case CallingConv::HiPE:
3529 /// \brief Return true if the condition is an unsigned comparison operation.
3530 static bool isX86CCUnsigned(unsigned X86CC) {
3532 default: llvm_unreachable("Invalid integer condition!");
3533 case X86::COND_E: return true;
3534 case X86::COND_G: return false;
3535 case X86::COND_GE: return false;
3536 case X86::COND_L: return false;
3537 case X86::COND_LE: return false;
3538 case X86::COND_NE: return true;
3539 case X86::COND_B: return true;
3540 case X86::COND_A: return true;
3541 case X86::COND_BE: return true;
3542 case X86::COND_AE: return true;
3544 llvm_unreachable("covered switch fell through?!");
3547 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3548 /// specific condition code, returning the condition code and the LHS/RHS of the
3549 /// comparison to make.
3550 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3551 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3553 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3554 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3555 // X > -1 -> X == 0, jump !sign.
3556 RHS = DAG.getConstant(0, RHS.getValueType());
3557 return X86::COND_NS;
3559 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3560 // X < 0 -> X == 0, jump on sign.
3563 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3565 RHS = DAG.getConstant(0, RHS.getValueType());
3566 return X86::COND_LE;
3570 switch (SetCCOpcode) {
3571 default: llvm_unreachable("Invalid integer condition!");
3572 case ISD::SETEQ: return X86::COND_E;
3573 case ISD::SETGT: return X86::COND_G;
3574 case ISD::SETGE: return X86::COND_GE;
3575 case ISD::SETLT: return X86::COND_L;
3576 case ISD::SETLE: return X86::COND_LE;
3577 case ISD::SETNE: return X86::COND_NE;
3578 case ISD::SETULT: return X86::COND_B;
3579 case ISD::SETUGT: return X86::COND_A;
3580 case ISD::SETULE: return X86::COND_BE;
3581 case ISD::SETUGE: return X86::COND_AE;
3585 // First determine if it is required or is profitable to flip the operands.
3587 // If LHS is a foldable load, but RHS is not, flip the condition.
3588 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3589 !ISD::isNON_EXTLoad(RHS.getNode())) {
3590 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3591 std::swap(LHS, RHS);
3594 switch (SetCCOpcode) {
3600 std::swap(LHS, RHS);
3604 // On a floating point condition, the flags are set as follows:
3606 // 0 | 0 | 0 | X > Y
3607 // 0 | 0 | 1 | X < Y
3608 // 1 | 0 | 0 | X == Y
3609 // 1 | 1 | 1 | unordered
3610 switch (SetCCOpcode) {
3611 default: llvm_unreachable("Condcode should be pre-legalized away");
3613 case ISD::SETEQ: return X86::COND_E;
3614 case ISD::SETOLT: // flipped
3616 case ISD::SETGT: return X86::COND_A;
3617 case ISD::SETOLE: // flipped
3619 case ISD::SETGE: return X86::COND_AE;
3620 case ISD::SETUGT: // flipped
3622 case ISD::SETLT: return X86::COND_B;
3623 case ISD::SETUGE: // flipped
3625 case ISD::SETLE: return X86::COND_BE;
3627 case ISD::SETNE: return X86::COND_NE;
3628 case ISD::SETUO: return X86::COND_P;
3629 case ISD::SETO: return X86::COND_NP;
3631 case ISD::SETUNE: return X86::COND_INVALID;
3635 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3636 /// code. Current x86 isa includes the following FP cmov instructions:
3637 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3638 static bool hasFPCMov(unsigned X86CC) {
3654 /// isFPImmLegal - Returns true if the target can instruction select the
3655 /// specified FP immediate natively. If false, the legalizer will
3656 /// materialize the FP immediate as a load from a constant pool.
3657 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3658 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3659 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3665 /// \brief Returns true if it is beneficial to convert a load of a constant
3666 /// to just the constant itself.
3667 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3669 assert(Ty->isIntegerTy());
3671 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3672 if (BitSize == 0 || BitSize > 64)
3677 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3678 /// the specified range (L, H].
3679 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3680 return (Val < 0) || (Val >= Low && Val < Hi);
3683 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3684 /// specified value.
3685 static bool isUndefOrEqual(int Val, int CmpVal) {
3686 return (Val < 0 || Val == CmpVal);
3689 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3690 /// from position Pos and ending in Pos+Size, falls within the specified
3691 /// sequential range (L, L+Pos]. or is undef.
3692 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3693 unsigned Pos, unsigned Size, int Low) {
3694 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3695 if (!isUndefOrEqual(Mask[i], Low))
3700 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3701 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3702 /// the second operand.
3703 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3704 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3705 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3706 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3707 return (Mask[0] < 2 && Mask[1] < 2);
3711 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3712 /// is suitable for input to PSHUFHW.
3713 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3714 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3717 // Lower quadword copied in order or undef.
3718 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3721 // Upper quadword shuffled.
3722 for (unsigned i = 4; i != 8; ++i)
3723 if (!isUndefOrInRange(Mask[i], 4, 8))
3726 if (VT == MVT::v16i16) {
3727 // Lower quadword copied in order or undef.
3728 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3731 // Upper quadword shuffled.
3732 for (unsigned i = 12; i != 16; ++i)
3733 if (!isUndefOrInRange(Mask[i], 12, 16))
3740 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3741 /// is suitable for input to PSHUFLW.
3742 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3743 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3746 // Upper quadword copied in order.
3747 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3750 // Lower quadword shuffled.
3751 for (unsigned i = 0; i != 4; ++i)
3752 if (!isUndefOrInRange(Mask[i], 0, 4))
3755 if (VT == MVT::v16i16) {
3756 // Upper quadword copied in order.
3757 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3760 // Lower quadword shuffled.
3761 for (unsigned i = 8; i != 12; ++i)
3762 if (!isUndefOrInRange(Mask[i], 8, 12))
3769 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3770 /// is suitable for input to PALIGNR.
3771 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3772 const X86Subtarget *Subtarget) {
3773 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3774 (VT.is256BitVector() && !Subtarget->hasInt256()))
3777 unsigned NumElts = VT.getVectorNumElements();
3778 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3779 unsigned NumLaneElts = NumElts/NumLanes;
3781 // Do not handle 64-bit element shuffles with palignr.
3782 if (NumLaneElts == 2)
3785 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3787 for (i = 0; i != NumLaneElts; ++i) {
3792 // Lane is all undef, go to next lane
3793 if (i == NumLaneElts)
3796 int Start = Mask[i+l];
3798 // Make sure its in this lane in one of the sources
3799 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3800 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3803 // If not lane 0, then we must match lane 0
3804 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3807 // Correct second source to be contiguous with first source
3808 if (Start >= (int)NumElts)
3809 Start -= NumElts - NumLaneElts;
3811 // Make sure we're shifting in the right direction.
3812 if (Start <= (int)(i+l))
3817 // Check the rest of the elements to see if they are consecutive.
3818 for (++i; i != NumLaneElts; ++i) {
3819 int Idx = Mask[i+l];
3821 // Make sure its in this lane
3822 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3823 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3826 // If not lane 0, then we must match lane 0
3827 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3830 if (Idx >= (int)NumElts)
3831 Idx -= NumElts - NumLaneElts;
3833 if (!isUndefOrEqual(Idx, Start+i))
3842 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3843 /// the two vector operands have swapped position.
3844 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3845 unsigned NumElems) {
3846 for (unsigned i = 0; i != NumElems; ++i) {
3850 else if (idx < (int)NumElems)
3851 Mask[i] = idx + NumElems;
3853 Mask[i] = idx - NumElems;
3857 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3858 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3859 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3860 /// reverse of what x86 shuffles want.
3861 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3863 unsigned NumElems = VT.getVectorNumElements();
3864 unsigned NumLanes = VT.getSizeInBits()/128;
3865 unsigned NumLaneElems = NumElems/NumLanes;
3867 if (NumLaneElems != 2 && NumLaneElems != 4)
3870 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3871 bool symetricMaskRequired =
3872 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3874 // VSHUFPSY divides the resulting vector into 4 chunks.
3875 // The sources are also splitted into 4 chunks, and each destination
3876 // chunk must come from a different source chunk.
3878 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3879 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3881 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3882 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3884 // VSHUFPDY divides the resulting vector into 4 chunks.
3885 // The sources are also splitted into 4 chunks, and each destination
3886 // chunk must come from a different source chunk.
3888 // SRC1 => X3 X2 X1 X0
3889 // SRC2 => Y3 Y2 Y1 Y0
3891 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3893 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3894 unsigned HalfLaneElems = NumLaneElems/2;
3895 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3896 for (unsigned i = 0; i != NumLaneElems; ++i) {
3897 int Idx = Mask[i+l];
3898 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3899 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3901 // For VSHUFPSY, the mask of the second half must be the same as the
3902 // first but with the appropriate offsets. This works in the same way as
3903 // VPERMILPS works with masks.
3904 if (!symetricMaskRequired || Idx < 0)
3906 if (MaskVal[i] < 0) {
3907 MaskVal[i] = Idx - l;
3910 if ((signed)(Idx - l) != MaskVal[i])
3918 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3919 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3920 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3921 if (!VT.is128BitVector())
3924 unsigned NumElems = VT.getVectorNumElements();
3929 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3930 return isUndefOrEqual(Mask[0], 6) &&
3931 isUndefOrEqual(Mask[1], 7) &&
3932 isUndefOrEqual(Mask[2], 2) &&
3933 isUndefOrEqual(Mask[3], 3);
3936 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3937 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3939 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3940 if (!VT.is128BitVector())
3943 unsigned NumElems = VT.getVectorNumElements();
3948 return isUndefOrEqual(Mask[0], 2) &&
3949 isUndefOrEqual(Mask[1], 3) &&
3950 isUndefOrEqual(Mask[2], 2) &&
3951 isUndefOrEqual(Mask[3], 3);
3954 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3955 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3956 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3957 if (!VT.is128BitVector())
3960 unsigned NumElems = VT.getVectorNumElements();
3962 if (NumElems != 2 && NumElems != 4)
3965 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3966 if (!isUndefOrEqual(Mask[i], i + NumElems))
3969 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3970 if (!isUndefOrEqual(Mask[i], i))
3976 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3977 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3978 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3979 if (!VT.is128BitVector())
3982 unsigned NumElems = VT.getVectorNumElements();
3984 if (NumElems != 2 && NumElems != 4)
3987 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3988 if (!isUndefOrEqual(Mask[i], i))
3991 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3992 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3998 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3999 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4000 /// i. e: If all but one element come from the same vector.
4001 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4002 // TODO: Deal with AVX's VINSERTPS
4003 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4006 unsigned CorrectPosV1 = 0;
4007 unsigned CorrectPosV2 = 0;
4008 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4009 if (Mask[i] == -1) {
4017 else if (Mask[i] == i + 4)
4021 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4022 // We have 3 elements (undefs count as elements from any vector) from one
4023 // vector, and one from another.
4030 // Some special combinations that can be optimized.
4033 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4034 SelectionDAG &DAG) {
4035 MVT VT = SVOp->getSimpleValueType(0);
4038 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4041 ArrayRef<int> Mask = SVOp->getMask();
4043 // These are the special masks that may be optimized.
4044 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4045 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4046 bool MatchEvenMask = true;
4047 bool MatchOddMask = true;
4048 for (int i=0; i<8; ++i) {
4049 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4050 MatchEvenMask = false;
4051 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4052 MatchOddMask = false;
4055 if (!MatchEvenMask && !MatchOddMask)
4058 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4060 SDValue Op0 = SVOp->getOperand(0);
4061 SDValue Op1 = SVOp->getOperand(1);
4063 if (MatchEvenMask) {
4064 // Shift the second operand right to 32 bits.
4065 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4066 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4068 // Shift the first operand left to 32 bits.
4069 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4070 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4072 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4073 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4076 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4077 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4078 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4079 bool HasInt256, bool V2IsSplat = false) {
4081 assert(VT.getSizeInBits() >= 128 &&
4082 "Unsupported vector type for unpckl");
4084 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4086 unsigned NumOf256BitLanes;
4087 unsigned NumElts = VT.getVectorNumElements();
4088 if (VT.is256BitVector()) {
4089 if (NumElts != 4 && NumElts != 8 &&
4090 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4093 NumOf256BitLanes = 1;
4094 } else if (VT.is512BitVector()) {
4095 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4096 "Unsupported vector type for unpckh");
4098 NumOf256BitLanes = 2;
4101 NumOf256BitLanes = 1;
4104 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4105 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4107 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4108 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4109 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4110 int BitI = Mask[l256*NumEltsInStride+l+i];
4111 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4112 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4114 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4116 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4124 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4125 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4126 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4127 bool HasInt256, bool V2IsSplat = false) {
4128 assert(VT.getSizeInBits() >= 128 &&
4129 "Unsupported vector type for unpckh");
4131 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4133 unsigned NumOf256BitLanes;
4134 unsigned NumElts = VT.getVectorNumElements();
4135 if (VT.is256BitVector()) {
4136 if (NumElts != 4 && NumElts != 8 &&
4137 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4140 NumOf256BitLanes = 1;
4141 } else if (VT.is512BitVector()) {
4142 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4143 "Unsupported vector type for unpckh");
4145 NumOf256BitLanes = 2;
4148 NumOf256BitLanes = 1;
4151 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4152 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4154 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4155 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4156 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4157 int BitI = Mask[l256*NumEltsInStride+l+i];
4158 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4159 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4161 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4163 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4171 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4172 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4174 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4175 unsigned NumElts = VT.getVectorNumElements();
4176 bool Is256BitVec = VT.is256BitVector();
4178 if (VT.is512BitVector())
4180 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4181 "Unsupported vector type for unpckh");
4183 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4184 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4187 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4188 // FIXME: Need a better way to get rid of this, there's no latency difference
4189 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4190 // the former later. We should also remove the "_undef" special mask.
4191 if (NumElts == 4 && Is256BitVec)
4194 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4195 // independently on 128-bit lanes.
4196 unsigned NumLanes = VT.getSizeInBits()/128;
4197 unsigned NumLaneElts = NumElts/NumLanes;
4199 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4200 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4201 int BitI = Mask[l+i];
4202 int BitI1 = Mask[l+i+1];
4204 if (!isUndefOrEqual(BitI, j))
4206 if (!isUndefOrEqual(BitI1, j))
4214 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4215 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4217 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4218 unsigned NumElts = VT.getVectorNumElements();
4220 if (VT.is512BitVector())
4223 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4224 "Unsupported vector type for unpckh");
4226 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4227 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4230 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4231 // independently on 128-bit lanes.
4232 unsigned NumLanes = VT.getSizeInBits()/128;
4233 unsigned NumLaneElts = NumElts/NumLanes;
4235 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4236 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4237 int BitI = Mask[l+i];
4238 int BitI1 = Mask[l+i+1];
4239 if (!isUndefOrEqual(BitI, j))
4241 if (!isUndefOrEqual(BitI1, j))
4248 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4249 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4250 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4251 if (!VT.is512BitVector())
4254 unsigned NumElts = VT.getVectorNumElements();
4255 unsigned HalfSize = NumElts/2;
4256 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4257 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4262 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4263 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4271 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4272 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4273 /// MOVSD, and MOVD, i.e. setting the lowest element.
4274 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4275 if (VT.getVectorElementType().getSizeInBits() < 32)
4277 if (!VT.is128BitVector())
4280 unsigned NumElts = VT.getVectorNumElements();
4282 if (!isUndefOrEqual(Mask[0], NumElts))
4285 for (unsigned i = 1; i != NumElts; ++i)
4286 if (!isUndefOrEqual(Mask[i], i))
4292 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4293 /// as permutations between 128-bit chunks or halves. As an example: this
4295 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4296 /// The first half comes from the second half of V1 and the second half from the
4297 /// the second half of V2.
4298 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4299 if (!HasFp256 || !VT.is256BitVector())
4302 // The shuffle result is divided into half A and half B. In total the two
4303 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4304 // B must come from C, D, E or F.
4305 unsigned HalfSize = VT.getVectorNumElements()/2;
4306 bool MatchA = false, MatchB = false;
4308 // Check if A comes from one of C, D, E, F.
4309 for (unsigned Half = 0; Half != 4; ++Half) {
4310 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4316 // Check if B comes from one of C, D, E, F.
4317 for (unsigned Half = 0; Half != 4; ++Half) {
4318 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4324 return MatchA && MatchB;
4327 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4328 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4329 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4330 MVT VT = SVOp->getSimpleValueType(0);
4332 unsigned HalfSize = VT.getVectorNumElements()/2;
4334 unsigned FstHalf = 0, SndHalf = 0;
4335 for (unsigned i = 0; i < HalfSize; ++i) {
4336 if (SVOp->getMaskElt(i) > 0) {
4337 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4341 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4342 if (SVOp->getMaskElt(i) > 0) {
4343 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4348 return (FstHalf | (SndHalf << 4));
4351 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4352 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4353 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4357 unsigned NumElts = VT.getVectorNumElements();
4359 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4360 for (unsigned i = 0; i != NumElts; ++i) {
4363 Imm8 |= Mask[i] << (i*2);
4368 unsigned LaneSize = 4;
4369 SmallVector<int, 4> MaskVal(LaneSize, -1);
4371 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4372 for (unsigned i = 0; i != LaneSize; ++i) {
4373 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4377 if (MaskVal[i] < 0) {
4378 MaskVal[i] = Mask[i+l] - l;
4379 Imm8 |= MaskVal[i] << (i*2);
4382 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4389 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4390 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4391 /// Note that VPERMIL mask matching is different depending whether theunderlying
4392 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4393 /// to the same elements of the low, but to the higher half of the source.
4394 /// In VPERMILPD the two lanes could be shuffled independently of each other
4395 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4396 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4397 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4398 if (VT.getSizeInBits() < 256 || EltSize < 32)
4400 bool symetricMaskRequired = (EltSize == 32);
4401 unsigned NumElts = VT.getVectorNumElements();
4403 unsigned NumLanes = VT.getSizeInBits()/128;
4404 unsigned LaneSize = NumElts/NumLanes;
4405 // 2 or 4 elements in one lane
4407 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4408 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4409 for (unsigned i = 0; i != LaneSize; ++i) {
4410 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4412 if (symetricMaskRequired) {
4413 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4414 ExpectedMaskVal[i] = Mask[i+l] - l;
4417 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4425 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4426 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4427 /// element of vector 2 and the other elements to come from vector 1 in order.
4428 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4429 bool V2IsSplat = false, bool V2IsUndef = false) {
4430 if (!VT.is128BitVector())
4433 unsigned NumOps = VT.getVectorNumElements();
4434 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4437 if (!isUndefOrEqual(Mask[0], 0))
4440 for (unsigned i = 1; i != NumOps; ++i)
4441 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4442 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4443 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4449 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4450 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4451 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4452 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4453 const X86Subtarget *Subtarget) {
4454 if (!Subtarget->hasSSE3())
4457 unsigned NumElems = VT.getVectorNumElements();
4459 if ((VT.is128BitVector() && NumElems != 4) ||
4460 (VT.is256BitVector() && NumElems != 8) ||
4461 (VT.is512BitVector() && NumElems != 16))
4464 // "i+1" is the value the indexed mask element must have
4465 for (unsigned i = 0; i != NumElems; i += 2)
4466 if (!isUndefOrEqual(Mask[i], i+1) ||
4467 !isUndefOrEqual(Mask[i+1], i+1))
4473 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4474 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4475 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4476 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4477 const X86Subtarget *Subtarget) {
4478 if (!Subtarget->hasSSE3())
4481 unsigned NumElems = VT.getVectorNumElements();
4483 if ((VT.is128BitVector() && NumElems != 4) ||
4484 (VT.is256BitVector() && NumElems != 8) ||
4485 (VT.is512BitVector() && NumElems != 16))
4488 // "i" is the value the indexed mask element must have
4489 for (unsigned i = 0; i != NumElems; i += 2)
4490 if (!isUndefOrEqual(Mask[i], i) ||
4491 !isUndefOrEqual(Mask[i+1], i))
4497 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4498 /// specifies a shuffle of elements that is suitable for input to 256-bit
4499 /// version of MOVDDUP.
4500 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4501 if (!HasFp256 || !VT.is256BitVector())
4504 unsigned NumElts = VT.getVectorNumElements();
4508 for (unsigned i = 0; i != NumElts/2; ++i)
4509 if (!isUndefOrEqual(Mask[i], 0))
4511 for (unsigned i = NumElts/2; i != NumElts; ++i)
4512 if (!isUndefOrEqual(Mask[i], NumElts/2))
4517 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4518 /// specifies a shuffle of elements that is suitable for input to 128-bit
4519 /// version of MOVDDUP.
4520 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4521 if (!VT.is128BitVector())
4524 unsigned e = VT.getVectorNumElements() / 2;
4525 for (unsigned i = 0; i != e; ++i)
4526 if (!isUndefOrEqual(Mask[i], i))
4528 for (unsigned i = 0; i != e; ++i)
4529 if (!isUndefOrEqual(Mask[e+i], i))
4534 /// isVEXTRACTIndex - Return true if the specified
4535 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4536 /// suitable for instruction that extract 128 or 256 bit vectors
4537 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4538 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4539 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4542 // The index should be aligned on a vecWidth-bit boundary.
4544 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4546 MVT VT = N->getSimpleValueType(0);
4547 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4548 bool Result = (Index * ElSize) % vecWidth == 0;
4553 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4554 /// operand specifies a subvector insert that is suitable for input to
4555 /// insertion of 128 or 256-bit subvectors
4556 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4557 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4558 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4560 // The index should be aligned on a vecWidth-bit boundary.
4562 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4564 MVT VT = N->getSimpleValueType(0);
4565 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4566 bool Result = (Index * ElSize) % vecWidth == 0;
4571 bool X86::isVINSERT128Index(SDNode *N) {
4572 return isVINSERTIndex(N, 128);
4575 bool X86::isVINSERT256Index(SDNode *N) {
4576 return isVINSERTIndex(N, 256);
4579 bool X86::isVEXTRACT128Index(SDNode *N) {
4580 return isVEXTRACTIndex(N, 128);
4583 bool X86::isVEXTRACT256Index(SDNode *N) {
4584 return isVEXTRACTIndex(N, 256);
4587 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4588 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4589 /// Handles 128-bit and 256-bit.
4590 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4591 MVT VT = N->getSimpleValueType(0);
4593 assert((VT.getSizeInBits() >= 128) &&
4594 "Unsupported vector type for PSHUF/SHUFP");
4596 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4597 // independently on 128-bit lanes.
4598 unsigned NumElts = VT.getVectorNumElements();
4599 unsigned NumLanes = VT.getSizeInBits()/128;
4600 unsigned NumLaneElts = NumElts/NumLanes;
4602 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4603 "Only supports 2, 4 or 8 elements per lane");
4605 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4607 for (unsigned i = 0; i != NumElts; ++i) {
4608 int Elt = N->getMaskElt(i);
4609 if (Elt < 0) continue;
4610 Elt &= NumLaneElts - 1;
4611 unsigned ShAmt = (i << Shift) % 8;
4612 Mask |= Elt << ShAmt;
4618 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4619 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4620 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4621 MVT VT = N->getSimpleValueType(0);
4623 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4624 "Unsupported vector type for PSHUFHW");
4626 unsigned NumElts = VT.getVectorNumElements();
4629 for (unsigned l = 0; l != NumElts; l += 8) {
4630 // 8 nodes per lane, but we only care about the last 4.
4631 for (unsigned i = 0; i < 4; ++i) {
4632 int Elt = N->getMaskElt(l+i+4);
4633 if (Elt < 0) continue;
4634 Elt &= 0x3; // only 2-bits.
4635 Mask |= Elt << (i * 2);
4642 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4643 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4644 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4645 MVT VT = N->getSimpleValueType(0);
4647 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4648 "Unsupported vector type for PSHUFHW");
4650 unsigned NumElts = VT.getVectorNumElements();
4653 for (unsigned l = 0; l != NumElts; l += 8) {
4654 // 8 nodes per lane, but we only care about the first 4.
4655 for (unsigned i = 0; i < 4; ++i) {
4656 int Elt = N->getMaskElt(l+i);
4657 if (Elt < 0) continue;
4658 Elt &= 0x3; // only 2-bits
4659 Mask |= Elt << (i * 2);
4666 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4667 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4668 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4669 MVT VT = SVOp->getSimpleValueType(0);
4670 unsigned EltSize = VT.is512BitVector() ? 1 :
4671 VT.getVectorElementType().getSizeInBits() >> 3;
4673 unsigned NumElts = VT.getVectorNumElements();
4674 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4675 unsigned NumLaneElts = NumElts/NumLanes;
4679 for (i = 0; i != NumElts; ++i) {
4680 Val = SVOp->getMaskElt(i);
4684 if (Val >= (int)NumElts)
4685 Val -= NumElts - NumLaneElts;
4687 assert(Val - i > 0 && "PALIGNR imm should be positive");
4688 return (Val - i) * EltSize;
4691 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4692 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4693 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4694 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4697 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4699 MVT VecVT = N->getOperand(0).getSimpleValueType();
4700 MVT ElVT = VecVT.getVectorElementType();
4702 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4703 return Index / NumElemsPerChunk;
4706 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4707 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4708 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4709 llvm_unreachable("Illegal insert subvector for VINSERT");
4712 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4714 MVT VecVT = N->getSimpleValueType(0);
4715 MVT ElVT = VecVT.getVectorElementType();
4717 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4718 return Index / NumElemsPerChunk;
4721 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4722 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4723 /// and VINSERTI128 instructions.
4724 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4725 return getExtractVEXTRACTImmediate(N, 128);
4728 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4729 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4730 /// and VINSERTI64x4 instructions.
4731 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4732 return getExtractVEXTRACTImmediate(N, 256);
4735 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4736 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4737 /// and VINSERTI128 instructions.
4738 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4739 return getInsertVINSERTImmediate(N, 128);
4742 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4743 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4744 /// and VINSERTI64x4 instructions.
4745 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4746 return getInsertVINSERTImmediate(N, 256);
4749 /// isZero - Returns true if Elt is a constant integer zero
4750 static bool isZero(SDValue V) {
4751 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4752 return C && C->isNullValue();
4755 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4757 bool X86::isZeroNode(SDValue Elt) {
4760 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4761 return CFP->getValueAPF().isPosZero();
4765 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4766 /// their permute mask.
4767 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4768 SelectionDAG &DAG) {
4769 MVT VT = SVOp->getSimpleValueType(0);
4770 unsigned NumElems = VT.getVectorNumElements();
4771 SmallVector<int, 8> MaskVec;
4773 for (unsigned i = 0; i != NumElems; ++i) {
4774 int Idx = SVOp->getMaskElt(i);
4776 if (Idx < (int)NumElems)
4781 MaskVec.push_back(Idx);
4783 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4784 SVOp->getOperand(0), &MaskVec[0]);
4787 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4788 /// match movhlps. The lower half elements should come from upper half of
4789 /// V1 (and in order), and the upper half elements should come from the upper
4790 /// half of V2 (and in order).
4791 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4792 if (!VT.is128BitVector())
4794 if (VT.getVectorNumElements() != 4)
4796 for (unsigned i = 0, e = 2; i != e; ++i)
4797 if (!isUndefOrEqual(Mask[i], i+2))
4799 for (unsigned i = 2; i != 4; ++i)
4800 if (!isUndefOrEqual(Mask[i], i+4))
4805 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4806 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4808 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4809 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4811 N = N->getOperand(0).getNode();
4812 if (!ISD::isNON_EXTLoad(N))
4815 *LD = cast<LoadSDNode>(N);
4819 // Test whether the given value is a vector value which will be legalized
4821 static bool WillBeConstantPoolLoad(SDNode *N) {
4822 if (N->getOpcode() != ISD::BUILD_VECTOR)
4825 // Check for any non-constant elements.
4826 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4827 switch (N->getOperand(i).getNode()->getOpcode()) {
4829 case ISD::ConstantFP:
4836 // Vectors of all-zeros and all-ones are materialized with special
4837 // instructions rather than being loaded.
4838 return !ISD::isBuildVectorAllZeros(N) &&
4839 !ISD::isBuildVectorAllOnes(N);
4842 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4843 /// match movlp{s|d}. The lower half elements should come from lower half of
4844 /// V1 (and in order), and the upper half elements should come from the upper
4845 /// half of V2 (and in order). And since V1 will become the source of the
4846 /// MOVLP, it must be either a vector load or a scalar load to vector.
4847 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4848 ArrayRef<int> Mask, MVT VT) {
4849 if (!VT.is128BitVector())
4852 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4854 // Is V2 is a vector load, don't do this transformation. We will try to use
4855 // load folding shufps op.
4856 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4859 unsigned NumElems = VT.getVectorNumElements();
4861 if (NumElems != 2 && NumElems != 4)
4863 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4864 if (!isUndefOrEqual(Mask[i], i))
4866 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4867 if (!isUndefOrEqual(Mask[i], i+NumElems))
4872 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4873 /// to an zero vector.
4874 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4875 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4876 SDValue V1 = N->getOperand(0);
4877 SDValue V2 = N->getOperand(1);
4878 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4879 for (unsigned i = 0; i != NumElems; ++i) {
4880 int Idx = N->getMaskElt(i);
4881 if (Idx >= (int)NumElems) {
4882 unsigned Opc = V2.getOpcode();
4883 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4885 if (Opc != ISD::BUILD_VECTOR ||
4886 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4888 } else if (Idx >= 0) {
4889 unsigned Opc = V1.getOpcode();
4890 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4892 if (Opc != ISD::BUILD_VECTOR ||
4893 !X86::isZeroNode(V1.getOperand(Idx)))
4900 /// getZeroVector - Returns a vector of specified type with all zero elements.
4902 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4903 SelectionDAG &DAG, SDLoc dl) {
4904 assert(VT.isVector() && "Expected a vector type");
4906 // Always build SSE zero vectors as <4 x i32> bitcasted
4907 // to their dest type. This ensures they get CSE'd.
4909 if (VT.is128BitVector()) { // SSE
4910 if (Subtarget->hasSSE2()) { // SSE2
4911 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4912 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4914 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4915 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4917 } else if (VT.is256BitVector()) { // AVX
4918 if (Subtarget->hasInt256()) { // AVX2
4919 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4920 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4921 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4923 // 256-bit logic and arithmetic instructions in AVX are all
4924 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4925 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4926 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4927 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4929 } else if (VT.is512BitVector()) { // AVX-512
4930 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4931 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4932 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4933 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4934 } else if (VT.getScalarType() == MVT::i1) {
4935 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4936 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4937 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4938 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4940 llvm_unreachable("Unexpected vector type");
4942 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4945 /// getOnesVector - Returns a vector of specified type with all bits set.
4946 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4947 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4948 /// Then bitcast to their original type, ensuring they get CSE'd.
4949 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4951 assert(VT.isVector() && "Expected a vector type");
4953 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4955 if (VT.is256BitVector()) {
4956 if (HasInt256) { // AVX2
4957 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4958 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4960 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4961 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4963 } else if (VT.is128BitVector()) {
4964 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4966 llvm_unreachable("Unexpected vector type");
4968 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4971 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4972 /// that point to V2 points to its first element.
4973 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4974 for (unsigned i = 0; i != NumElems; ++i) {
4975 if (Mask[i] > (int)NumElems) {
4981 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4982 /// operation of specified width.
4983 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4985 unsigned NumElems = VT.getVectorNumElements();
4986 SmallVector<int, 8> Mask;
4987 Mask.push_back(NumElems);
4988 for (unsigned i = 1; i != NumElems; ++i)
4990 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4993 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4994 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4996 unsigned NumElems = VT.getVectorNumElements();
4997 SmallVector<int, 8> Mask;
4998 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5000 Mask.push_back(i + NumElems);
5002 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5005 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5006 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5008 unsigned NumElems = VT.getVectorNumElements();
5009 SmallVector<int, 8> Mask;
5010 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5011 Mask.push_back(i + Half);
5012 Mask.push_back(i + NumElems + Half);
5014 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5017 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5018 // a generic shuffle instruction because the target has no such instructions.
5019 // Generate shuffles which repeat i16 and i8 several times until they can be
5020 // represented by v4f32 and then be manipulated by target suported shuffles.
5021 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5022 MVT VT = V.getSimpleValueType();
5023 int NumElems = VT.getVectorNumElements();
5026 while (NumElems > 4) {
5027 if (EltNo < NumElems/2) {
5028 V = getUnpackl(DAG, dl, VT, V, V);
5030 V = getUnpackh(DAG, dl, VT, V, V);
5031 EltNo -= NumElems/2;
5038 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5039 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5040 MVT VT = V.getSimpleValueType();
5043 if (VT.is128BitVector()) {
5044 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5045 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5046 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5048 } else if (VT.is256BitVector()) {
5049 // To use VPERMILPS to splat scalars, the second half of indicies must
5050 // refer to the higher part, which is a duplication of the lower one,
5051 // because VPERMILPS can only handle in-lane permutations.
5052 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5053 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5055 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5056 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5059 llvm_unreachable("Vector size not supported");
5061 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5064 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5065 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5066 MVT SrcVT = SV->getSimpleValueType(0);
5067 SDValue V1 = SV->getOperand(0);
5070 int EltNo = SV->getSplatIndex();
5071 int NumElems = SrcVT.getVectorNumElements();
5072 bool Is256BitVec = SrcVT.is256BitVector();
5074 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5075 "Unknown how to promote splat for type");
5077 // Extract the 128-bit part containing the splat element and update
5078 // the splat element index when it refers to the higher register.
5080 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5081 if (EltNo >= NumElems/2)
5082 EltNo -= NumElems/2;
5085 // All i16 and i8 vector types can't be used directly by a generic shuffle
5086 // instruction because the target has no such instruction. Generate shuffles
5087 // which repeat i16 and i8 several times until they fit in i32, and then can
5088 // be manipulated by target suported shuffles.
5089 MVT EltVT = SrcVT.getVectorElementType();
5090 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5091 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5093 // Recreate the 256-bit vector and place the same 128-bit vector
5094 // into the low and high part. This is necessary because we want
5095 // to use VPERM* to shuffle the vectors
5097 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5100 return getLegalSplat(DAG, V1, EltNo);
5103 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5104 /// vector of zero or undef vector. This produces a shuffle where the low
5105 /// element of V2 is swizzled into the zero/undef vector, landing at element
5106 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5107 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5109 const X86Subtarget *Subtarget,
5110 SelectionDAG &DAG) {
5111 MVT VT = V2.getSimpleValueType();
5113 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5114 unsigned NumElems = VT.getVectorNumElements();
5115 SmallVector<int, 16> MaskVec;
5116 for (unsigned i = 0; i != NumElems; ++i)
5117 // If this is the insertion idx, put the low elt of V2 here.
5118 MaskVec.push_back(i == Idx ? NumElems : i);
5119 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5122 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5123 /// target specific opcode. Returns true if the Mask could be calculated.
5124 /// Sets IsUnary to true if only uses one source.
5125 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5126 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5127 unsigned NumElems = VT.getVectorNumElements();
5131 switch(N->getOpcode()) {
5133 ImmN = N->getOperand(N->getNumOperands()-1);
5134 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5136 case X86ISD::UNPCKH:
5137 DecodeUNPCKHMask(VT, Mask);
5139 case X86ISD::UNPCKL:
5140 DecodeUNPCKLMask(VT, Mask);
5142 case X86ISD::MOVHLPS:
5143 DecodeMOVHLPSMask(NumElems, Mask);
5145 case X86ISD::MOVLHPS:
5146 DecodeMOVLHPSMask(NumElems, Mask);
5148 case X86ISD::PALIGNR:
5149 ImmN = N->getOperand(N->getNumOperands()-1);
5150 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5152 case X86ISD::PSHUFD:
5153 case X86ISD::VPERMILP:
5154 ImmN = N->getOperand(N->getNumOperands()-1);
5155 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5158 case X86ISD::PSHUFHW:
5159 ImmN = N->getOperand(N->getNumOperands()-1);
5160 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5163 case X86ISD::PSHUFLW:
5164 ImmN = N->getOperand(N->getNumOperands()-1);
5165 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5168 case X86ISD::VPERMI:
5169 ImmN = N->getOperand(N->getNumOperands()-1);
5170 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5174 case X86ISD::MOVSD: {
5175 // The index 0 always comes from the first element of the second source,
5176 // this is why MOVSS and MOVSD are used in the first place. The other
5177 // elements come from the other positions of the first source vector
5178 Mask.push_back(NumElems);
5179 for (unsigned i = 1; i != NumElems; ++i) {
5184 case X86ISD::VPERM2X128:
5185 ImmN = N->getOperand(N->getNumOperands()-1);
5186 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5187 if (Mask.empty()) return false;
5189 case X86ISD::MOVDDUP:
5190 case X86ISD::MOVLHPD:
5191 case X86ISD::MOVLPD:
5192 case X86ISD::MOVLPS:
5193 case X86ISD::MOVSHDUP:
5194 case X86ISD::MOVSLDUP:
5195 // Not yet implemented
5197 default: llvm_unreachable("unknown target shuffle node");
5203 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5204 /// element of the result of the vector shuffle.
5205 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5208 return SDValue(); // Limit search depth.
5210 SDValue V = SDValue(N, 0);
5211 EVT VT = V.getValueType();
5212 unsigned Opcode = V.getOpcode();
5214 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5215 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5216 int Elt = SV->getMaskElt(Index);
5219 return DAG.getUNDEF(VT.getVectorElementType());
5221 unsigned NumElems = VT.getVectorNumElements();
5222 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5223 : SV->getOperand(1);
5224 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5227 // Recurse into target specific vector shuffles to find scalars.
5228 if (isTargetShuffle(Opcode)) {
5229 MVT ShufVT = V.getSimpleValueType();
5230 unsigned NumElems = ShufVT.getVectorNumElements();
5231 SmallVector<int, 16> ShuffleMask;
5234 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5237 int Elt = ShuffleMask[Index];
5239 return DAG.getUNDEF(ShufVT.getVectorElementType());
5241 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5243 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5247 // Actual nodes that may contain scalar elements
5248 if (Opcode == ISD::BITCAST) {
5249 V = V.getOperand(0);
5250 EVT SrcVT = V.getValueType();
5251 unsigned NumElems = VT.getVectorNumElements();
5253 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5257 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5258 return (Index == 0) ? V.getOperand(0)
5259 : DAG.getUNDEF(VT.getVectorElementType());
5261 if (V.getOpcode() == ISD::BUILD_VECTOR)
5262 return V.getOperand(Index);
5267 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5268 /// shuffle operation which come from a consecutively from a zero. The
5269 /// search can start in two different directions, from left or right.
5270 /// We count undefs as zeros until PreferredNum is reached.
5271 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5272 unsigned NumElems, bool ZerosFromLeft,
5274 unsigned PreferredNum = -1U) {
5275 unsigned NumZeros = 0;
5276 for (unsigned i = 0; i != NumElems; ++i) {
5277 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5278 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5282 if (X86::isZeroNode(Elt))
5284 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5285 NumZeros = std::min(NumZeros + 1, PreferredNum);
5293 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5294 /// correspond consecutively to elements from one of the vector operands,
5295 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5297 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5298 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5299 unsigned NumElems, unsigned &OpNum) {
5300 bool SeenV1 = false;
5301 bool SeenV2 = false;
5303 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5304 int Idx = SVOp->getMaskElt(i);
5305 // Ignore undef indicies
5309 if (Idx < (int)NumElems)
5314 // Only accept consecutive elements from the same vector
5315 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5319 OpNum = SeenV1 ? 0 : 1;
5323 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5324 /// logical left shift of a vector.
5325 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5326 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5328 SVOp->getSimpleValueType(0).getVectorNumElements();
5329 unsigned NumZeros = getNumOfConsecutiveZeros(
5330 SVOp, NumElems, false /* check zeros from right */, DAG,
5331 SVOp->getMaskElt(0));
5337 // Considering the elements in the mask that are not consecutive zeros,
5338 // check if they consecutively come from only one of the source vectors.
5340 // V1 = {X, A, B, C} 0
5342 // vector_shuffle V1, V2 <1, 2, 3, X>
5344 if (!isShuffleMaskConsecutive(SVOp,
5345 0, // Mask Start Index
5346 NumElems-NumZeros, // Mask End Index(exclusive)
5347 NumZeros, // Where to start looking in the src vector
5348 NumElems, // Number of elements in vector
5349 OpSrc)) // Which source operand ?
5354 ShVal = SVOp->getOperand(OpSrc);
5358 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5359 /// logical left shift of a vector.
5360 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5361 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5363 SVOp->getSimpleValueType(0).getVectorNumElements();
5364 unsigned NumZeros = getNumOfConsecutiveZeros(
5365 SVOp, NumElems, true /* check zeros from left */, DAG,
5366 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5372 // Considering the elements in the mask that are not consecutive zeros,
5373 // check if they consecutively come from only one of the source vectors.
5375 // 0 { A, B, X, X } = V2
5377 // vector_shuffle V1, V2 <X, X, 4, 5>
5379 if (!isShuffleMaskConsecutive(SVOp,
5380 NumZeros, // Mask Start Index
5381 NumElems, // Mask End Index(exclusive)
5382 0, // Where to start looking in the src vector
5383 NumElems, // Number of elements in vector
5384 OpSrc)) // Which source operand ?
5389 ShVal = SVOp->getOperand(OpSrc);
5393 /// isVectorShift - Returns true if the shuffle can be implemented as a
5394 /// logical left or right shift of a vector.
5395 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5396 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5397 // Although the logic below support any bitwidth size, there are no
5398 // shift instructions which handle more than 128-bit vectors.
5399 if (!SVOp->getSimpleValueType(0).is128BitVector())
5402 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5403 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5409 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5411 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5412 unsigned NumNonZero, unsigned NumZero,
5414 const X86Subtarget* Subtarget,
5415 const TargetLowering &TLI) {
5422 for (unsigned i = 0; i < 16; ++i) {
5423 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5424 if (ThisIsNonZero && First) {
5426 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5428 V = DAG.getUNDEF(MVT::v8i16);
5433 SDValue ThisElt, LastElt;
5434 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5435 if (LastIsNonZero) {
5436 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5437 MVT::i16, Op.getOperand(i-1));
5439 if (ThisIsNonZero) {
5440 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5441 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5442 ThisElt, DAG.getConstant(8, MVT::i8));
5444 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5448 if (ThisElt.getNode())
5449 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5450 DAG.getIntPtrConstant(i/2));
5454 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5457 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5459 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5460 unsigned NumNonZero, unsigned NumZero,
5462 const X86Subtarget* Subtarget,
5463 const TargetLowering &TLI) {
5470 for (unsigned i = 0; i < 8; ++i) {
5471 bool isNonZero = (NonZeros & (1 << i)) != 0;
5475 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5477 V = DAG.getUNDEF(MVT::v8i16);
5480 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5481 MVT::v8i16, V, Op.getOperand(i),
5482 DAG.getIntPtrConstant(i));
5489 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5490 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5491 unsigned NonZeros, unsigned NumNonZero,
5492 unsigned NumZero, SelectionDAG &DAG,
5493 const X86Subtarget *Subtarget,
5494 const TargetLowering &TLI) {
5495 // We know there's at least one non-zero element
5496 unsigned FirstNonZeroIdx = 0;
5497 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5498 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5499 X86::isZeroNode(FirstNonZero)) {
5501 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5504 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5505 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5508 SDValue V = FirstNonZero.getOperand(0);
5509 MVT VVT = V.getSimpleValueType();
5510 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5513 unsigned FirstNonZeroDst =
5514 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5515 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5516 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5517 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5519 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5520 SDValue Elem = Op.getOperand(Idx);
5521 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5524 // TODO: What else can be here? Deal with it.
5525 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5528 // TODO: Some optimizations are still possible here
5529 // ex: Getting one element from a vector, and the rest from another.
5530 if (Elem.getOperand(0) != V)
5533 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5536 else if (IncorrectIdx == -1U) {
5540 // There was already one element with an incorrect index.
5541 // We can't optimize this case to an insertps.
5545 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5547 EVT VT = Op.getSimpleValueType();
5548 unsigned ElementMoveMask = 0;
5549 if (IncorrectIdx == -1U)
5550 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5552 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5554 SDValue InsertpsMask =
5555 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5556 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5562 /// getVShift - Return a vector logical shift node.
5564 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5565 unsigned NumBits, SelectionDAG &DAG,
5566 const TargetLowering &TLI, SDLoc dl) {
5567 assert(VT.is128BitVector() && "Unknown type for VShift");
5568 EVT ShVT = MVT::v2i64;
5569 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5570 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5571 return DAG.getNode(ISD::BITCAST, dl, VT,
5572 DAG.getNode(Opc, dl, ShVT, SrcOp,
5573 DAG.getConstant(NumBits,
5574 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5578 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5580 // Check if the scalar load can be widened into a vector load. And if
5581 // the address is "base + cst" see if the cst can be "absorbed" into
5582 // the shuffle mask.
5583 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5584 SDValue Ptr = LD->getBasePtr();
5585 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5587 EVT PVT = LD->getValueType(0);
5588 if (PVT != MVT::i32 && PVT != MVT::f32)
5593 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5594 FI = FINode->getIndex();
5596 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5597 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5598 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5599 Offset = Ptr.getConstantOperandVal(1);
5600 Ptr = Ptr.getOperand(0);
5605 // FIXME: 256-bit vector instructions don't require a strict alignment,
5606 // improve this code to support it better.
5607 unsigned RequiredAlign = VT.getSizeInBits()/8;
5608 SDValue Chain = LD->getChain();
5609 // Make sure the stack object alignment is at least 16 or 32.
5610 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5611 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5612 if (MFI->isFixedObjectIndex(FI)) {
5613 // Can't change the alignment. FIXME: It's possible to compute
5614 // the exact stack offset and reference FI + adjust offset instead.
5615 // If someone *really* cares about this. That's the way to implement it.
5618 MFI->setObjectAlignment(FI, RequiredAlign);
5622 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5623 // Ptr + (Offset & ~15).
5626 if ((Offset % RequiredAlign) & 3)
5628 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5630 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5631 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5633 int EltNo = (Offset - StartOffset) >> 2;
5634 unsigned NumElems = VT.getVectorNumElements();
5636 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5637 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5638 LD->getPointerInfo().getWithOffset(StartOffset),
5639 false, false, false, 0);
5641 SmallVector<int, 8> Mask;
5642 for (unsigned i = 0; i != NumElems; ++i)
5643 Mask.push_back(EltNo);
5645 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5651 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5652 /// vector of type 'VT', see if the elements can be replaced by a single large
5653 /// load which has the same value as a build_vector whose operands are 'elts'.
5655 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5657 /// FIXME: we'd also like to handle the case where the last elements are zero
5658 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5659 /// There's even a handy isZeroNode for that purpose.
5660 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5661 SDLoc &DL, SelectionDAG &DAG,
5662 bool isAfterLegalize) {
5663 EVT EltVT = VT.getVectorElementType();
5664 unsigned NumElems = Elts.size();
5666 LoadSDNode *LDBase = nullptr;
5667 unsigned LastLoadedElt = -1U;
5669 // For each element in the initializer, see if we've found a load or an undef.
5670 // If we don't find an initial load element, or later load elements are
5671 // non-consecutive, bail out.
5672 for (unsigned i = 0; i < NumElems; ++i) {
5673 SDValue Elt = Elts[i];
5675 if (!Elt.getNode() ||
5676 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5679 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5681 LDBase = cast<LoadSDNode>(Elt.getNode());
5685 if (Elt.getOpcode() == ISD::UNDEF)
5688 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5689 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5694 // If we have found an entire vector of loads and undefs, then return a large
5695 // load of the entire vector width starting at the base pointer. If we found
5696 // consecutive loads for the low half, generate a vzext_load node.
5697 if (LastLoadedElt == NumElems - 1) {
5699 if (isAfterLegalize &&
5700 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5703 SDValue NewLd = SDValue();
5705 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5706 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5707 LDBase->getPointerInfo(),
5708 LDBase->isVolatile(), LDBase->isNonTemporal(),
5709 LDBase->isInvariant(), 0);
5710 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5711 LDBase->getPointerInfo(),
5712 LDBase->isVolatile(), LDBase->isNonTemporal(),
5713 LDBase->isInvariant(), LDBase->getAlignment());
5715 if (LDBase->hasAnyUseOfValue(1)) {
5716 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5718 SDValue(NewLd.getNode(), 1));
5719 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5720 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5721 SDValue(NewLd.getNode(), 1));
5726 if (NumElems == 4 && LastLoadedElt == 1 &&
5727 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5728 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5729 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5731 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5732 LDBase->getPointerInfo(),
5733 LDBase->getAlignment(),
5734 false/*isVolatile*/, true/*ReadMem*/,
5737 // Make sure the newly-created LOAD is in the same position as LDBase in
5738 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5739 // update uses of LDBase's output chain to use the TokenFactor.
5740 if (LDBase->hasAnyUseOfValue(1)) {
5741 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5742 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5743 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5744 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5745 SDValue(ResNode.getNode(), 1));
5748 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5753 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5754 /// to generate a splat value for the following cases:
5755 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5756 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5757 /// a scalar load, or a constant.
5758 /// The VBROADCAST node is returned when a pattern is found,
5759 /// or SDValue() otherwise.
5760 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5761 SelectionDAG &DAG) {
5762 if (!Subtarget->hasFp256())
5765 MVT VT = Op.getSimpleValueType();
5768 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5769 "Unsupported vector type for broadcast.");
5774 switch (Op.getOpcode()) {
5776 // Unknown pattern found.
5779 case ISD::BUILD_VECTOR: {
5780 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5781 BitVector UndefElements;
5782 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5784 // We need a splat of a single value to use broadcast, and it doesn't
5785 // make any sense if the value is only in one element of the vector.
5786 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5790 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5791 Ld.getOpcode() == ISD::ConstantFP);
5793 // Make sure that all of the users of a non-constant load are from the
5794 // BUILD_VECTOR node.
5795 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5800 case ISD::VECTOR_SHUFFLE: {
5801 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5803 // Shuffles must have a splat mask where the first element is
5805 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5808 SDValue Sc = Op.getOperand(0);
5809 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5810 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5812 if (!Subtarget->hasInt256())
5815 // Use the register form of the broadcast instruction available on AVX2.
5816 if (VT.getSizeInBits() >= 256)
5817 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5818 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5821 Ld = Sc.getOperand(0);
5822 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5823 Ld.getOpcode() == ISD::ConstantFP);
5825 // The scalar_to_vector node and the suspected
5826 // load node must have exactly one user.
5827 // Constants may have multiple users.
5829 // AVX-512 has register version of the broadcast
5830 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5831 Ld.getValueType().getSizeInBits() >= 32;
5832 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5839 bool IsGE256 = (VT.getSizeInBits() >= 256);
5841 // Handle the broadcasting a single constant scalar from the constant pool
5842 // into a vector. On Sandybridge it is still better to load a constant vector
5843 // from the constant pool and not to broadcast it from a scalar.
5844 if (ConstSplatVal && Subtarget->hasInt256()) {
5845 EVT CVT = Ld.getValueType();
5846 assert(!CVT.isVector() && "Must not broadcast a vector type");
5847 unsigned ScalarSize = CVT.getSizeInBits();
5849 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5850 const Constant *C = nullptr;
5851 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5852 C = CI->getConstantIntValue();
5853 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5854 C = CF->getConstantFPValue();
5856 assert(C && "Invalid constant type");
5858 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5859 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5860 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5861 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5862 MachinePointerInfo::getConstantPool(),
5863 false, false, false, Alignment);
5865 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5869 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5870 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5872 // Handle AVX2 in-register broadcasts.
5873 if (!IsLoad && Subtarget->hasInt256() &&
5874 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5875 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5877 // The scalar source must be a normal load.
5881 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5882 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5884 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5885 // double since there is no vbroadcastsd xmm
5886 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5887 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5888 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5891 // Unsupported broadcast.
5895 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5896 /// underlying vector and index.
5898 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5900 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5902 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5903 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5906 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5908 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5910 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5911 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5914 // In this case the vector is the extract_subvector expression and the index
5915 // is 2, as specified by the shuffle.
5916 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5917 SDValue ShuffleVec = SVOp->getOperand(0);
5918 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5919 assert(ShuffleVecVT.getVectorElementType() ==
5920 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5922 int ShuffleIdx = SVOp->getMaskElt(Idx);
5923 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5924 ExtractedFromVec = ShuffleVec;
5930 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5931 MVT VT = Op.getSimpleValueType();
5933 // Skip if insert_vec_elt is not supported.
5934 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5935 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5939 unsigned NumElems = Op.getNumOperands();
5943 SmallVector<unsigned, 4> InsertIndices;
5944 SmallVector<int, 8> Mask(NumElems, -1);
5946 for (unsigned i = 0; i != NumElems; ++i) {
5947 unsigned Opc = Op.getOperand(i).getOpcode();
5949 if (Opc == ISD::UNDEF)
5952 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5953 // Quit if more than 1 elements need inserting.
5954 if (InsertIndices.size() > 1)
5957 InsertIndices.push_back(i);
5961 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5962 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5963 // Quit if non-constant index.
5964 if (!isa<ConstantSDNode>(ExtIdx))
5966 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5968 // Quit if extracted from vector of different type.
5969 if (ExtractedFromVec.getValueType() != VT)
5972 if (!VecIn1.getNode())
5973 VecIn1 = ExtractedFromVec;
5974 else if (VecIn1 != ExtractedFromVec) {
5975 if (!VecIn2.getNode())
5976 VecIn2 = ExtractedFromVec;
5977 else if (VecIn2 != ExtractedFromVec)
5978 // Quit if more than 2 vectors to shuffle
5982 if (ExtractedFromVec == VecIn1)
5984 else if (ExtractedFromVec == VecIn2)
5985 Mask[i] = Idx + NumElems;
5988 if (!VecIn1.getNode())
5991 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5992 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5993 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5994 unsigned Idx = InsertIndices[i];
5995 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5996 DAG.getIntPtrConstant(Idx));
6002 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6004 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6006 MVT VT = Op.getSimpleValueType();
6007 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6008 "Unexpected type in LowerBUILD_VECTORvXi1!");
6011 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6012 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6013 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6014 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6017 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6018 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6019 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6020 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6023 bool AllContants = true;
6024 uint64_t Immediate = 0;
6025 int NonConstIdx = -1;
6026 bool IsSplat = true;
6027 unsigned NumNonConsts = 0;
6028 unsigned NumConsts = 0;
6029 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6030 SDValue In = Op.getOperand(idx);
6031 if (In.getOpcode() == ISD::UNDEF)
6033 if (!isa<ConstantSDNode>(In)) {
6034 AllContants = false;
6040 if (cast<ConstantSDNode>(In)->getZExtValue())
6041 Immediate |= (1ULL << idx);
6043 if (In != Op.getOperand(0))
6048 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6049 DAG.getConstant(Immediate, MVT::i16));
6050 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6051 DAG.getIntPtrConstant(0));
6054 if (NumNonConsts == 1 && NonConstIdx != 0) {
6057 SDValue VecAsImm = DAG.getConstant(Immediate,
6058 MVT::getIntegerVT(VT.getSizeInBits()));
6059 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6062 DstVec = DAG.getUNDEF(VT);
6063 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6064 Op.getOperand(NonConstIdx),
6065 DAG.getIntPtrConstant(NonConstIdx));
6067 if (!IsSplat && (NonConstIdx != 0))
6068 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6069 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6072 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6073 DAG.getConstant(-1, SelectVT),
6074 DAG.getConstant(0, SelectVT));
6076 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6077 DAG.getConstant((Immediate | 1), SelectVT),
6078 DAG.getConstant(Immediate, SelectVT));
6079 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6082 /// \brief Return true if \p N implements a horizontal binop and return the
6083 /// operands for the horizontal binop into V0 and V1.
6085 /// This is a helper function of PerformBUILD_VECTORCombine.
6086 /// This function checks that the build_vector \p N in input implements a
6087 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6088 /// operation to match.
6089 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6090 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6091 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6094 /// This function only analyzes elements of \p N whose indices are
6095 /// in range [BaseIdx, LastIdx).
6096 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6098 unsigned BaseIdx, unsigned LastIdx,
6099 SDValue &V0, SDValue &V1) {
6100 EVT VT = N->getValueType(0);
6102 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6103 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6104 "Invalid Vector in input!");
6106 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6107 bool CanFold = true;
6108 unsigned ExpectedVExtractIdx = BaseIdx;
6109 unsigned NumElts = LastIdx - BaseIdx;
6110 V0 = DAG.getUNDEF(VT);
6111 V1 = DAG.getUNDEF(VT);
6113 // Check if N implements a horizontal binop.
6114 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6115 SDValue Op = N->getOperand(i + BaseIdx);
6118 if (Op->getOpcode() == ISD::UNDEF) {
6119 // Update the expected vector extract index.
6120 if (i * 2 == NumElts)
6121 ExpectedVExtractIdx = BaseIdx;
6122 ExpectedVExtractIdx += 2;
6126 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6131 SDValue Op0 = Op.getOperand(0);
6132 SDValue Op1 = Op.getOperand(1);
6134 // Try to match the following pattern:
6135 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6136 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6137 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6138 Op0.getOperand(0) == Op1.getOperand(0) &&
6139 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6140 isa<ConstantSDNode>(Op1.getOperand(1)));
6144 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6145 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6147 if (i * 2 < NumElts) {
6148 if (V0.getOpcode() == ISD::UNDEF)
6149 V0 = Op0.getOperand(0);
6151 if (V1.getOpcode() == ISD::UNDEF)
6152 V1 = Op0.getOperand(0);
6153 if (i * 2 == NumElts)
6154 ExpectedVExtractIdx = BaseIdx;
6157 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6158 if (I0 == ExpectedVExtractIdx)
6159 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6160 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6161 // Try to match the following dag sequence:
6162 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6163 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6167 ExpectedVExtractIdx += 2;
6173 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6174 /// a concat_vector.
6176 /// This is a helper function of PerformBUILD_VECTORCombine.
6177 /// This function expects two 256-bit vectors called V0 and V1.
6178 /// At first, each vector is split into two separate 128-bit vectors.
6179 /// Then, the resulting 128-bit vectors are used to implement two
6180 /// horizontal binary operations.
6182 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6184 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6185 /// the two new horizontal binop.
6186 /// When Mode is set, the first horizontal binop dag node would take as input
6187 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6188 /// horizontal binop dag node would take as input the lower 128-bit of V1
6189 /// and the upper 128-bit of V1.
6191 /// HADD V0_LO, V0_HI
6192 /// HADD V1_LO, V1_HI
6194 /// Otherwise, the first horizontal binop dag node takes as input the lower
6195 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6196 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6198 /// HADD V0_LO, V1_LO
6199 /// HADD V0_HI, V1_HI
6201 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6202 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6203 /// the upper 128-bits of the result.
6204 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6205 SDLoc DL, SelectionDAG &DAG,
6206 unsigned X86Opcode, bool Mode,
6207 bool isUndefLO, bool isUndefHI) {
6208 EVT VT = V0.getValueType();
6209 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6210 "Invalid nodes in input!");
6212 unsigned NumElts = VT.getVectorNumElements();
6213 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6214 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6215 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6216 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6217 EVT NewVT = V0_LO.getValueType();
6219 SDValue LO = DAG.getUNDEF(NewVT);
6220 SDValue HI = DAG.getUNDEF(NewVT);
6223 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6224 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6225 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6226 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6227 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6229 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6230 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6231 V1_LO->getOpcode() != ISD::UNDEF))
6232 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6234 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6235 V1_HI->getOpcode() != ISD::UNDEF))
6236 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6239 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6242 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6243 /// sequence of 'vadd + vsub + blendi'.
6244 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6245 const X86Subtarget *Subtarget) {
6247 EVT VT = BV->getValueType(0);
6248 unsigned NumElts = VT.getVectorNumElements();
6249 SDValue InVec0 = DAG.getUNDEF(VT);
6250 SDValue InVec1 = DAG.getUNDEF(VT);
6252 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6253 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6255 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6256 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6257 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6260 // Odd-numbered elements in the input build vector are obtained from
6261 // adding two integer/float elements.
6262 // Even-numbered elements in the input build vector are obtained from
6263 // subtracting two integer/float elements.
6264 unsigned ExpectedOpcode = ISD::FSUB;
6265 unsigned NextExpectedOpcode = ISD::FADD;
6266 bool AddFound = false;
6267 bool SubFound = false;
6269 for (unsigned i = 0, e = NumElts; i != e; i++) {
6270 SDValue Op = BV->getOperand(i);
6272 // Skip 'undef' values.
6273 unsigned Opcode = Op.getOpcode();
6274 if (Opcode == ISD::UNDEF) {
6275 std::swap(ExpectedOpcode, NextExpectedOpcode);
6279 // Early exit if we found an unexpected opcode.
6280 if (Opcode != ExpectedOpcode)
6283 SDValue Op0 = Op.getOperand(0);
6284 SDValue Op1 = Op.getOperand(1);
6286 // Try to match the following pattern:
6287 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6288 // Early exit if we cannot match that sequence.
6289 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6290 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6291 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6292 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6293 Op0.getOperand(1) != Op1.getOperand(1))
6296 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6300 // We found a valid add/sub node. Update the information accordingly.
6306 // Update InVec0 and InVec1.
6307 if (InVec0.getOpcode() == ISD::UNDEF)
6308 InVec0 = Op0.getOperand(0);
6309 if (InVec1.getOpcode() == ISD::UNDEF)
6310 InVec1 = Op1.getOperand(0);
6312 // Make sure that operands in input to each add/sub node always
6313 // come from a same pair of vectors.
6314 if (InVec0 != Op0.getOperand(0)) {
6315 if (ExpectedOpcode == ISD::FSUB)
6318 // FADD is commutable. Try to commute the operands
6319 // and then test again.
6320 std::swap(Op0, Op1);
6321 if (InVec0 != Op0.getOperand(0))
6325 if (InVec1 != Op1.getOperand(0))
6328 // Update the pair of expected opcodes.
6329 std::swap(ExpectedOpcode, NextExpectedOpcode);
6332 // Don't try to fold this build_vector into a VSELECT if it has
6333 // too many UNDEF operands.
6334 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6335 InVec1.getOpcode() != ISD::UNDEF) {
6336 // Emit a sequence of vector add and sub followed by a VSELECT.
6337 // The new VSELECT will be lowered into a BLENDI.
6338 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6339 // and emit a single ADDSUB instruction.
6340 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6341 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6343 // Construct the VSELECT mask.
6344 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6345 EVT SVT = MaskVT.getVectorElementType();
6346 unsigned SVTBits = SVT.getSizeInBits();
6347 SmallVector<SDValue, 8> Ops;
6349 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6350 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6351 APInt::getAllOnesValue(SVTBits);
6352 SDValue Constant = DAG.getConstant(Value, SVT);
6353 Ops.push_back(Constant);
6356 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6357 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6363 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6364 const X86Subtarget *Subtarget) {
6366 EVT VT = N->getValueType(0);
6367 unsigned NumElts = VT.getVectorNumElements();
6368 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6369 SDValue InVec0, InVec1;
6371 // Try to match an ADDSUB.
6372 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6373 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6374 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6375 if (Value.getNode())
6379 // Try to match horizontal ADD/SUB.
6380 unsigned NumUndefsLO = 0;
6381 unsigned NumUndefsHI = 0;
6382 unsigned Half = NumElts/2;
6384 // Count the number of UNDEF operands in the build_vector in input.
6385 for (unsigned i = 0, e = Half; i != e; ++i)
6386 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6389 for (unsigned i = Half, e = NumElts; i != e; ++i)
6390 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6393 // Early exit if this is either a build_vector of all UNDEFs or all the
6394 // operands but one are UNDEF.
6395 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6398 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6399 // Try to match an SSE3 float HADD/HSUB.
6400 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6401 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6403 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6404 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6405 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6406 // Try to match an SSSE3 integer HADD/HSUB.
6407 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6408 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6410 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6411 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6414 if (!Subtarget->hasAVX())
6417 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6418 // Try to match an AVX horizontal add/sub of packed single/double
6419 // precision floating point values from 256-bit vectors.
6420 SDValue InVec2, InVec3;
6421 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6422 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6423 ((InVec0.getOpcode() == ISD::UNDEF ||
6424 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6425 ((InVec1.getOpcode() == ISD::UNDEF ||
6426 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6427 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6429 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6430 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6431 ((InVec0.getOpcode() == ISD::UNDEF ||
6432 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6433 ((InVec1.getOpcode() == ISD::UNDEF ||
6434 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6435 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6436 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6437 // Try to match an AVX2 horizontal add/sub of signed integers.
6438 SDValue InVec2, InVec3;
6440 bool CanFold = true;
6442 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6443 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6444 ((InVec0.getOpcode() == ISD::UNDEF ||
6445 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6446 ((InVec1.getOpcode() == ISD::UNDEF ||
6447 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6448 X86Opcode = X86ISD::HADD;
6449 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6450 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6451 ((InVec0.getOpcode() == ISD::UNDEF ||
6452 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6453 ((InVec1.getOpcode() == ISD::UNDEF ||
6454 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6455 X86Opcode = X86ISD::HSUB;
6460 // Fold this build_vector into a single horizontal add/sub.
6461 // Do this only if the target has AVX2.
6462 if (Subtarget->hasAVX2())
6463 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6465 // Do not try to expand this build_vector into a pair of horizontal
6466 // add/sub if we can emit a pair of scalar add/sub.
6467 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6470 // Convert this build_vector into a pair of horizontal binop followed by
6472 bool isUndefLO = NumUndefsLO == Half;
6473 bool isUndefHI = NumUndefsHI == Half;
6474 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6475 isUndefLO, isUndefHI);
6479 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6480 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6482 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6483 X86Opcode = X86ISD::HADD;
6484 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6485 X86Opcode = X86ISD::HSUB;
6486 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6487 X86Opcode = X86ISD::FHADD;
6488 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6489 X86Opcode = X86ISD::FHSUB;
6493 // Don't try to expand this build_vector into a pair of horizontal add/sub
6494 // if we can simply emit a pair of scalar add/sub.
6495 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6498 // Convert this build_vector into two horizontal add/sub followed by
6500 bool isUndefLO = NumUndefsLO == Half;
6501 bool isUndefHI = NumUndefsHI == Half;
6502 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6503 isUndefLO, isUndefHI);
6510 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6513 MVT VT = Op.getSimpleValueType();
6514 MVT ExtVT = VT.getVectorElementType();
6515 unsigned NumElems = Op.getNumOperands();
6517 // Generate vectors for predicate vectors.
6518 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6519 return LowerBUILD_VECTORvXi1(Op, DAG);
6521 // Vectors containing all zeros can be matched by pxor and xorps later
6522 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6523 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6524 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6525 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6528 return getZeroVector(VT, Subtarget, DAG, dl);
6531 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6532 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6533 // vpcmpeqd on 256-bit vectors.
6534 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6535 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6538 if (!VT.is512BitVector())
6539 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6542 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6543 if (Broadcast.getNode())
6546 unsigned EVTBits = ExtVT.getSizeInBits();
6548 unsigned NumZero = 0;
6549 unsigned NumNonZero = 0;
6550 unsigned NonZeros = 0;
6551 bool IsAllConstants = true;
6552 SmallSet<SDValue, 8> Values;
6553 for (unsigned i = 0; i < NumElems; ++i) {
6554 SDValue Elt = Op.getOperand(i);
6555 if (Elt.getOpcode() == ISD::UNDEF)
6558 if (Elt.getOpcode() != ISD::Constant &&
6559 Elt.getOpcode() != ISD::ConstantFP)
6560 IsAllConstants = false;
6561 if (X86::isZeroNode(Elt))
6564 NonZeros |= (1 << i);
6569 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6570 if (NumNonZero == 0)
6571 return DAG.getUNDEF(VT);
6573 // Special case for single non-zero, non-undef, element.
6574 if (NumNonZero == 1) {
6575 unsigned Idx = countTrailingZeros(NonZeros);
6576 SDValue Item = Op.getOperand(Idx);
6578 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6579 // the value are obviously zero, truncate the value to i32 and do the
6580 // insertion that way. Only do this if the value is non-constant or if the
6581 // value is a constant being inserted into element 0. It is cheaper to do
6582 // a constant pool load than it is to do a movd + shuffle.
6583 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6584 (!IsAllConstants || Idx == 0)) {
6585 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6587 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6588 EVT VecVT = MVT::v4i32;
6589 unsigned VecElts = 4;
6591 // Truncate the value (which may itself be a constant) to i32, and
6592 // convert it to a vector with movd (S2V+shuffle to zero extend).
6593 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6594 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6595 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6597 // Now we have our 32-bit value zero extended in the low element of
6598 // a vector. If Idx != 0, swizzle it into place.
6600 SmallVector<int, 4> Mask;
6601 Mask.push_back(Idx);
6602 for (unsigned i = 1; i != VecElts; ++i)
6604 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6607 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6611 // If we have a constant or non-constant insertion into the low element of
6612 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6613 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6614 // depending on what the source datatype is.
6617 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6619 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6620 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6621 if (VT.is256BitVector() || VT.is512BitVector()) {
6622 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6623 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6624 Item, DAG.getIntPtrConstant(0));
6626 assert(VT.is128BitVector() && "Expected an SSE value type!");
6627 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6628 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6629 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6632 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6633 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6634 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6635 if (VT.is256BitVector()) {
6636 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6637 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6639 assert(VT.is128BitVector() && "Expected an SSE value type!");
6640 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6642 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6646 // Is it a vector logical left shift?
6647 if (NumElems == 2 && Idx == 1 &&
6648 X86::isZeroNode(Op.getOperand(0)) &&
6649 !X86::isZeroNode(Op.getOperand(1))) {
6650 unsigned NumBits = VT.getSizeInBits();
6651 return getVShift(true, VT,
6652 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6653 VT, Op.getOperand(1)),
6654 NumBits/2, DAG, *this, dl);
6657 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6660 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6661 // is a non-constant being inserted into an element other than the low one,
6662 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6663 // movd/movss) to move this into the low element, then shuffle it into
6665 if (EVTBits == 32) {
6666 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6668 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6669 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6670 SmallVector<int, 8> MaskVec;
6671 for (unsigned i = 0; i != NumElems; ++i)
6672 MaskVec.push_back(i == Idx ? 0 : 1);
6673 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6677 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6678 if (Values.size() == 1) {
6679 if (EVTBits == 32) {
6680 // Instead of a shuffle like this:
6681 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6682 // Check if it's possible to issue this instead.
6683 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6684 unsigned Idx = countTrailingZeros(NonZeros);
6685 SDValue Item = Op.getOperand(Idx);
6686 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6687 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6692 // A vector full of immediates; various special cases are already
6693 // handled, so this is best done with a single constant-pool load.
6697 // For AVX-length vectors, build the individual 128-bit pieces and use
6698 // shuffles to put them in place.
6699 if (VT.is256BitVector() || VT.is512BitVector()) {
6700 SmallVector<SDValue, 64> V;
6701 for (unsigned i = 0; i != NumElems; ++i)
6702 V.push_back(Op.getOperand(i));
6704 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6706 // Build both the lower and upper subvector.
6707 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6708 makeArrayRef(&V[0], NumElems/2));
6709 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6710 makeArrayRef(&V[NumElems / 2], NumElems/2));
6712 // Recreate the wider vector with the lower and upper part.
6713 if (VT.is256BitVector())
6714 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6715 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6718 // Let legalizer expand 2-wide build_vectors.
6719 if (EVTBits == 64) {
6720 if (NumNonZero == 1) {
6721 // One half is zero or undef.
6722 unsigned Idx = countTrailingZeros(NonZeros);
6723 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6724 Op.getOperand(Idx));
6725 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6730 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6731 if (EVTBits == 8 && NumElems == 16) {
6732 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6734 if (V.getNode()) return V;
6737 if (EVTBits == 16 && NumElems == 8) {
6738 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6740 if (V.getNode()) return V;
6743 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6744 if (EVTBits == 32 && NumElems == 4) {
6745 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6746 NumZero, DAG, Subtarget, *this);
6751 // If element VT is == 32 bits, turn it into a number of shuffles.
6752 SmallVector<SDValue, 8> V(NumElems);
6753 if (NumElems == 4 && NumZero > 0) {
6754 for (unsigned i = 0; i < 4; ++i) {
6755 bool isZero = !(NonZeros & (1 << i));
6757 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6759 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6762 for (unsigned i = 0; i < 2; ++i) {
6763 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6766 V[i] = V[i*2]; // Must be a zero vector.
6769 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6772 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6775 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6780 bool Reverse1 = (NonZeros & 0x3) == 2;
6781 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6785 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6786 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6788 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6791 if (Values.size() > 1 && VT.is128BitVector()) {
6792 // Check for a build vector of consecutive loads.
6793 for (unsigned i = 0; i < NumElems; ++i)
6794 V[i] = Op.getOperand(i);
6796 // Check for elements which are consecutive loads.
6797 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6801 // Check for a build vector from mostly shuffle plus few inserting.
6802 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6806 // For SSE 4.1, use insertps to put the high elements into the low element.
6807 if (getSubtarget()->hasSSE41()) {
6809 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6810 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6812 Result = DAG.getUNDEF(VT);
6814 for (unsigned i = 1; i < NumElems; ++i) {
6815 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6816 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6817 Op.getOperand(i), DAG.getIntPtrConstant(i));
6822 // Otherwise, expand into a number of unpckl*, start by extending each of
6823 // our (non-undef) elements to the full vector width with the element in the
6824 // bottom slot of the vector (which generates no code for SSE).
6825 for (unsigned i = 0; i < NumElems; ++i) {
6826 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6827 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6829 V[i] = DAG.getUNDEF(VT);
6832 // Next, we iteratively mix elements, e.g. for v4f32:
6833 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6834 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6835 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6836 unsigned EltStride = NumElems >> 1;
6837 while (EltStride != 0) {
6838 for (unsigned i = 0; i < EltStride; ++i) {
6839 // If V[i+EltStride] is undef and this is the first round of mixing,
6840 // then it is safe to just drop this shuffle: V[i] is already in the
6841 // right place, the one element (since it's the first round) being
6842 // inserted as undef can be dropped. This isn't safe for successive
6843 // rounds because they will permute elements within both vectors.
6844 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6845 EltStride == NumElems/2)
6848 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6857 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6858 // to create 256-bit vectors from two other 128-bit ones.
6859 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6861 MVT ResVT = Op.getSimpleValueType();
6863 assert((ResVT.is256BitVector() ||
6864 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6866 SDValue V1 = Op.getOperand(0);
6867 SDValue V2 = Op.getOperand(1);
6868 unsigned NumElems = ResVT.getVectorNumElements();
6869 if(ResVT.is256BitVector())
6870 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6872 if (Op.getNumOperands() == 4) {
6873 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6874 ResVT.getVectorNumElements()/2);
6875 SDValue V3 = Op.getOperand(2);
6876 SDValue V4 = Op.getOperand(3);
6877 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6878 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6880 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6883 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6884 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6885 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6886 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6887 Op.getNumOperands() == 4)));
6889 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6890 // from two other 128-bit ones.
6892 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6893 return LowerAVXCONCAT_VECTORS(Op, DAG);
6897 //===----------------------------------------------------------------------===//
6898 // Vector shuffle lowering
6900 // This is an experimental code path for lowering vector shuffles on x86. It is
6901 // designed to handle arbitrary vector shuffles and blends, gracefully
6902 // degrading performance as necessary. It works hard to recognize idiomatic
6903 // shuffles and lower them to optimal instruction patterns without leaving
6904 // a framework that allows reasonably efficient handling of all vector shuffle
6906 //===----------------------------------------------------------------------===//
6908 /// \brief Tiny helper function to identify a no-op mask.
6910 /// This is a somewhat boring predicate function. It checks whether the mask
6911 /// array input, which is assumed to be a single-input shuffle mask of the kind
6912 /// used by the X86 shuffle instructions (not a fully general
6913 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6914 /// in-place shuffle are 'no-op's.
6915 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6916 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6917 if (Mask[i] != -1 && Mask[i] != i)
6922 /// \brief Helper function to classify a mask as a single-input mask.
6924 /// This isn't a generic single-input test because in the vector shuffle
6925 /// lowering we canonicalize single inputs to be the first input operand. This
6926 /// means we can more quickly test for a single input by only checking whether
6927 /// an input from the second operand exists. We also assume that the size of
6928 /// mask corresponds to the size of the input vectors which isn't true in the
6929 /// fully general case.
6930 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6932 if (M >= (int)Mask.size())
6937 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6939 /// This helper function produces an 8-bit shuffle immediate corresponding to
6940 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6941 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6944 /// NB: We rely heavily on "undef" masks preserving the input lane.
6945 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6946 SelectionDAG &DAG) {
6947 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6948 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6949 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6950 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6951 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6954 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6955 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6956 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6957 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6958 return DAG.getConstant(Imm, MVT::i8);
6961 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6963 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6964 /// support for floating point shuffles but not integer shuffles. These
6965 /// instructions will incur a domain crossing penalty on some chips though so
6966 /// it is better to avoid lowering through this for integer vectors where
6968 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6969 const X86Subtarget *Subtarget,
6970 SelectionDAG &DAG) {
6972 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6973 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6974 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6975 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6976 ArrayRef<int> Mask = SVOp->getMask();
6977 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6979 if (isSingleInputShuffleMask(Mask)) {
6980 // Straight shuffle of a single input vector. Simulate this by using the
6981 // single input as both of the "inputs" to this instruction..
6982 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6983 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6984 DAG.getConstant(SHUFPDMask, MVT::i8));
6986 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6987 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6989 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6990 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6991 DAG.getConstant(SHUFPDMask, MVT::i8));
6994 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
6996 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
6997 /// the integer unit to minimize domain crossing penalties. However, for blends
6998 /// it falls back to the floating point shuffle operation with appropriate bit
7000 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7001 const X86Subtarget *Subtarget,
7002 SelectionDAG &DAG) {
7004 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7005 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7006 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7007 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7008 ArrayRef<int> Mask = SVOp->getMask();
7009 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7011 if (isSingleInputShuffleMask(Mask)) {
7012 // Straight shuffle of a single input vector. For everything from SSE2
7013 // onward this has a single fast instruction with no scary immediates.
7014 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7015 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7016 int WidenedMask[4] = {
7017 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7018 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7020 ISD::BITCAST, DL, MVT::v2i64,
7021 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7022 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7025 // We implement this with SHUFPD which is pretty lame because it will likely
7026 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7027 // However, all the alternatives are still more cycles and newer chips don't
7028 // have this problem. It would be really nice if x86 had better shuffles here.
7029 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7030 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7031 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7032 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7035 /// \brief Lower 4-lane 32-bit floating point shuffles.
7037 /// Uses instructions exclusively from the floating point unit to minimize
7038 /// domain crossing penalties, as these are sufficient to implement all v4f32
7040 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7041 const X86Subtarget *Subtarget,
7042 SelectionDAG &DAG) {
7044 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7045 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7046 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7047 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7048 ArrayRef<int> Mask = SVOp->getMask();
7049 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7051 SDValue LowV = V1, HighV = V2;
7052 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7055 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7057 if (NumV2Elements == 0)
7058 // Straight shuffle of a single input vector. We pass the input vector to
7059 // both operands to simulate this with a SHUFPS.
7060 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7061 getV4X86ShuffleImm8ForMask(Mask, DAG));
7063 if (NumV2Elements == 1) {
7065 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7067 // Compute the index adjacent to V2Index and in the same half by toggling
7069 int V2AdjIndex = V2Index ^ 1;
7071 if (Mask[V2AdjIndex] == -1) {
7072 // Handles all the cases where we have a single V2 element and an undef.
7073 // This will only ever happen in the high lanes because we commute the
7074 // vector otherwise.
7076 std::swap(LowV, HighV);
7077 NewMask[V2Index] -= 4;
7079 // Handle the case where the V2 element ends up adjacent to a V1 element.
7080 // To make this work, blend them together as the first step.
7081 int V1Index = V2AdjIndex;
7082 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7083 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7084 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7086 // Now proceed to reconstruct the final blend as we have the necessary
7087 // high or low half formed.
7094 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7095 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7097 } else if (NumV2Elements == 2) {
7098 if (Mask[0] < 4 && Mask[1] < 4) {
7099 // Handle the easy case where we have V1 in the low lanes and V2 in the
7100 // high lanes. We never see this reversed because we sort the shuffle.
7104 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7105 // trying to place elements directly, just blend them and set up the final
7106 // shuffle to place them.
7108 // The first two blend mask elements are for V1, the second two are for
7110 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7111 Mask[2] < 4 ? Mask[2] : Mask[3],
7112 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7113 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7114 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7115 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7117 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7120 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7121 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7122 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7123 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7126 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7127 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7130 /// \brief Lower 4-lane i32 vector shuffles.
7132 /// We try to handle these with integer-domain shuffles where we can, but for
7133 /// blends we use the floating point domain blend instructions.
7134 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7135 const X86Subtarget *Subtarget,
7136 SelectionDAG &DAG) {
7138 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7139 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7140 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7141 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7142 ArrayRef<int> Mask = SVOp->getMask();
7143 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7145 if (isSingleInputShuffleMask(Mask))
7146 // Straight shuffle of a single input vector. For everything from SSE2
7147 // onward this has a single fast instruction with no scary immediates.
7148 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7149 getV4X86ShuffleImm8ForMask(Mask, DAG));
7151 // We implement this with SHUFPS because it can blend from two vectors.
7152 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7153 // up the inputs, bypassing domain shift penalties that we would encur if we
7154 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7156 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7157 DAG.getVectorShuffle(
7159 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7160 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7163 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7164 /// shuffle lowering, and the most complex part.
7166 /// The lowering strategy is to try to form pairs of input lanes which are
7167 /// targeted at the same half of the final vector, and then use a dword shuffle
7168 /// to place them onto the right half, and finally unpack the paired lanes into
7169 /// their final position.
7171 /// The exact breakdown of how to form these dword pairs and align them on the
7172 /// correct sides is really tricky. See the comments within the function for
7173 /// more of the details.
7174 static SDValue lowerV8I16SingleInputVectorShuffle(
7175 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7176 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7177 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7178 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7179 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7181 SmallVector<int, 4> LoInputs;
7182 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7183 [](int M) { return M >= 0; });
7184 std::sort(LoInputs.begin(), LoInputs.end());
7185 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7186 SmallVector<int, 4> HiInputs;
7187 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7188 [](int M) { return M >= 0; });
7189 std::sort(HiInputs.begin(), HiInputs.end());
7190 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7192 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7193 int NumHToL = LoInputs.size() - NumLToL;
7195 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7196 int NumHToH = HiInputs.size() - NumLToH;
7197 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7198 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7199 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7200 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7202 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7203 // such inputs we can swap two of the dwords across the half mark and end up
7204 // with <=2 inputs to each half in each half. Once there, we can fall through
7205 // to the generic code below. For example:
7207 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7208 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7210 // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7212 auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7213 int ThreeInputHalfSum, int OneInputHalfOffset) {
7214 // Compute the index of dword with only one word among the three inputs in
7215 // a half by taking the sum of the half with three inputs and subtracting
7216 // the sum of the actual three inputs. The difference is the remaining
7218 int DWordA = (ThreeInputHalfSum -
7219 std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7221 int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7223 int PSHUFDMask[] = {0, 1, 2, 3};
7224 PSHUFDMask[DWordA] = DWordB;
7225 PSHUFDMask[DWordB] = DWordA;
7226 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7227 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7228 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7229 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7231 // Adjust the mask to match the new locations of A and B.
7233 if (M != -1 && M/2 == DWordA)
7234 M = 2 * DWordB + M % 2;
7235 else if (M != -1 && M/2 == DWordB)
7236 M = 2 * DWordA + M % 2;
7238 // Recurse back into this routine to re-compute state now that this isn't
7239 // a 3 and 1 problem.
7240 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7243 if (NumLToL == 3 && NumHToL == 1)
7244 return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7245 else if (NumLToL == 1 && NumHToL == 3)
7246 return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7247 else if (NumLToH == 1 && NumHToH == 3)
7248 return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7249 else if (NumLToH == 3 && NumHToH == 1)
7250 return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7252 // At this point there are at most two inputs to the low and high halves from
7253 // each half. That means the inputs can always be grouped into dwords and
7254 // those dwords can then be moved to the correct half with a dword shuffle.
7255 // We use at most one low and one high word shuffle to collect these paired
7256 // inputs into dwords, and finally a dword shuffle to place them.
7257 int PSHUFLMask[4] = {-1, -1, -1, -1};
7258 int PSHUFHMask[4] = {-1, -1, -1, -1};
7259 int PSHUFDMask[4] = {-1, -1, -1, -1};
7261 // First fix the masks for all the inputs that are staying in their
7262 // original halves. This will then dictate the targets of the cross-half
7264 auto fixInPlaceInputs = [&PSHUFDMask](
7265 ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7266 MutableArrayRef<int> HalfMask, int HalfOffset) {
7267 if (InPlaceInputs.empty())
7269 if (InPlaceInputs.size() == 1) {
7270 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7271 InPlaceInputs[0] - HalfOffset;
7272 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7276 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7277 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7278 InPlaceInputs[0] - HalfOffset;
7279 // Put the second input next to the first so that they are packed into
7280 // a dword. We find the adjacent index by toggling the low bit.
7281 int AdjIndex = InPlaceInputs[0] ^ 1;
7282 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7283 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7284 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7286 if (!HToLInputs.empty())
7287 fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7288 if (!LToHInputs.empty())
7289 fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7291 // Now gather the cross-half inputs and place them into a free dword of
7292 // their target half.
7293 // FIXME: This operation could almost certainly be simplified dramatically to
7294 // look more like the 3-1 fixing operation.
7295 auto moveInputsToRightHalf = [&PSHUFDMask](
7296 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7297 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7298 int SourceOffset, int DestOffset) {
7299 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7300 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7302 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7304 int LowWord = Word & ~1;
7305 int HighWord = Word | 1;
7306 return isWordClobbered(SourceHalfMask, LowWord) ||
7307 isWordClobbered(SourceHalfMask, HighWord);
7310 if (IncomingInputs.empty())
7313 if (ExistingInputs.empty()) {
7314 // Map any dwords with inputs from them into the right half.
7315 for (int Input : IncomingInputs) {
7316 // If the source half mask maps over the inputs, turn those into
7317 // swaps and use the swapped lane.
7318 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7319 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7320 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7321 Input - SourceOffset;
7322 // We have to swap the uses in our half mask in one sweep.
7323 for (int &M : HalfMask)
7324 if (M == SourceHalfMask[Input - SourceOffset])
7326 else if (M == Input)
7327 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7329 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7330 Input - SourceOffset &&
7331 "Previous placement doesn't match!");
7333 // Note that this correctly re-maps both when we do a swap and when
7334 // we observe the other side of the swap above. We rely on that to
7335 // avoid swapping the members of the input list directly.
7336 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7339 // Map the input's dword into the correct half.
7340 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7341 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7343 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7345 "Previous placement doesn't match!");
7348 // And just directly shift any other-half mask elements to be same-half
7349 // as we will have mirrored the dword containing the element into the
7350 // same position within that half.
7351 for (int &M : HalfMask)
7352 if (M >= SourceOffset && M < SourceOffset + 4) {
7353 M = M - SourceOffset + DestOffset;
7354 assert(M >= 0 && "This should never wrap below zero!");
7359 // Ensure we have the input in a viable dword of its current half. This
7360 // is particularly tricky because the original position may be clobbered
7361 // by inputs being moved and *staying* in that half.
7362 if (IncomingInputs.size() == 1) {
7363 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7364 int InputFixed = std::find(std::begin(SourceHalfMask),
7365 std::end(SourceHalfMask), -1) -
7366 std::begin(SourceHalfMask) + SourceOffset;
7367 SourceHalfMask[InputFixed - SourceOffset] =
7368 IncomingInputs[0] - SourceOffset;
7369 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7371 IncomingInputs[0] = InputFixed;
7373 } else if (IncomingInputs.size() == 2) {
7374 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7375 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7376 int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7377 assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7378 "Not all dwords can be clobbered!");
7379 SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7380 SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7381 for (int &M : HalfMask)
7382 if (M == IncomingInputs[0])
7383 M = SourceDWordBase + SourceOffset;
7384 else if (M == IncomingInputs[1])
7385 M = SourceDWordBase + 1 + SourceOffset;
7386 IncomingInputs[0] = SourceDWordBase + SourceOffset;
7387 IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7390 llvm_unreachable("Unhandled input size!");
7393 // Now hoist the DWord down to the right half.
7394 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7395 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7396 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7397 for (int Input : IncomingInputs)
7398 std::replace(HalfMask.begin(), HalfMask.end(), Input,
7399 FreeDWord * 2 + Input % 2);
7401 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7402 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7403 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7404 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7406 // Now enact all the shuffles we've computed to move the inputs into their
7408 if (!isNoopShuffleMask(PSHUFLMask))
7409 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7410 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7411 if (!isNoopShuffleMask(PSHUFHMask))
7412 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7413 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7414 if (!isNoopShuffleMask(PSHUFDMask))
7415 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7416 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7417 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7418 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7420 // At this point, each half should contain all its inputs, and we can then
7421 // just shuffle them into their final position.
7422 assert(std::count_if(LoMask.begin(), LoMask.end(),
7423 [](int M) { return M >= 4; }) == 0 &&
7424 "Failed to lift all the high half inputs to the low mask!");
7425 assert(std::count_if(HiMask.begin(), HiMask.end(),
7426 [](int M) { return M >= 0 && M < 4; }) == 0 &&
7427 "Failed to lift all the low half inputs to the high mask!");
7429 // Do a half shuffle for the low mask.
7430 if (!isNoopShuffleMask(LoMask))
7431 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7432 getV4X86ShuffleImm8ForMask(LoMask, DAG));
7434 // Do a half shuffle with the high mask after shifting its values down.
7435 for (int &M : HiMask)
7438 if (!isNoopShuffleMask(HiMask))
7439 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7440 getV4X86ShuffleImm8ForMask(HiMask, DAG));
7445 /// \brief Detect whether the mask pattern should be lowered through
7448 /// This essentially tests whether viewing the mask as an interleaving of two
7449 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7450 /// lowering it through interleaving is a significantly better strategy.
7451 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7452 int NumEvenInputs[2] = {0, 0};
7453 int NumOddInputs[2] = {0, 0};
7454 int NumLoInputs[2] = {0, 0};
7455 int NumHiInputs[2] = {0, 0};
7456 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7460 int InputIdx = Mask[i] >= Size;
7463 ++NumLoInputs[InputIdx];
7465 ++NumHiInputs[InputIdx];
7468 ++NumEvenInputs[InputIdx];
7470 ++NumOddInputs[InputIdx];
7473 // The minimum number of cross-input results for both the interleaved and
7474 // split cases. If interleaving results in fewer cross-input results, return
7476 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7477 NumEvenInputs[0] + NumOddInputs[1]);
7478 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7479 NumLoInputs[0] + NumHiInputs[1]);
7480 return InterleavedCrosses < SplitCrosses;
7483 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7485 /// This strategy only works when the inputs from each vector fit into a single
7486 /// half of that vector, and generally there are not so many inputs as to leave
7487 /// the in-place shuffles required highly constrained (and thus expensive). It
7488 /// shifts all the inputs into a single side of both input vectors and then
7489 /// uses an unpack to interleave these inputs in a single vector. At that
7490 /// point, we will fall back on the generic single input shuffle lowering.
7491 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7493 MutableArrayRef<int> Mask,
7494 const X86Subtarget *Subtarget,
7495 SelectionDAG &DAG) {
7496 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7497 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7498 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7499 for (int i = 0; i < 8; ++i)
7500 if (Mask[i] >= 0 && Mask[i] < 4)
7501 LoV1Inputs.push_back(i);
7502 else if (Mask[i] >= 4 && Mask[i] < 8)
7503 HiV1Inputs.push_back(i);
7504 else if (Mask[i] >= 8 && Mask[i] < 12)
7505 LoV2Inputs.push_back(i);
7506 else if (Mask[i] >= 12)
7507 HiV2Inputs.push_back(i);
7509 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7510 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7513 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7514 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7515 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7517 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7518 HiV1Inputs.size() + HiV2Inputs.size();
7520 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7521 ArrayRef<int> HiInputs, bool MoveToLo,
7523 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7524 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7525 if (BadInputs.empty())
7528 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7529 int MoveOffset = MoveToLo ? 0 : 4;
7531 if (GoodInputs.empty()) {
7532 for (int BadInput : BadInputs) {
7533 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7534 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7537 if (GoodInputs.size() == 2) {
7538 // If the low inputs are spread across two dwords, pack them into
7540 MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7541 Mask[GoodInputs[0]] - MaskOffset;
7542 MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7543 Mask[GoodInputs[1]] - MaskOffset;
7544 Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7545 Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7547 // Otherwise pin the low inputs.
7548 for (int GoodInput : GoodInputs)
7549 MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7553 std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7554 std::begin(MoveMask);
7555 assert(MoveMaskIdx >= MoveOffset && "Established above");
7557 if (BadInputs.size() == 2) {
7558 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7559 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7560 MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7561 Mask[BadInputs[0]] - MaskOffset;
7562 MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7563 Mask[BadInputs[1]] - MaskOffset;
7564 Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7565 Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7567 assert(BadInputs.size() == 1 && "All sizes handled");
7568 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7569 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7573 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7576 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7578 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7581 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7582 // cross-half traffic in the final shuffle.
7584 // Munge the mask to be a single-input mask after the unpack merges the
7588 M = 2 * (M % 4) + (M / 8);
7590 return DAG.getVectorShuffle(
7591 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7592 DL, MVT::v8i16, V1, V2),
7593 DAG.getUNDEF(MVT::v8i16), Mask);
7596 /// \brief Generic lowering of 8-lane i16 shuffles.
7598 /// This handles both single-input shuffles and combined shuffle/blends with
7599 /// two inputs. The single input shuffles are immediately delegated to
7600 /// a dedicated lowering routine.
7602 /// The blends are lowered in one of three fundamental ways. If there are few
7603 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7604 /// of the input is significantly cheaper when lowered as an interleaving of
7605 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7606 /// halves of the inputs separately (making them have relatively few inputs)
7607 /// and then concatenate them.
7608 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7609 const X86Subtarget *Subtarget,
7610 SelectionDAG &DAG) {
7612 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7613 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7614 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7615 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7616 ArrayRef<int> OrigMask = SVOp->getMask();
7617 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7618 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7619 MutableArrayRef<int> Mask(MaskStorage);
7621 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7623 auto isV1 = [](int M) { return M >= 0 && M < 8; };
7624 auto isV2 = [](int M) { return M >= 8; };
7626 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7627 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7629 if (NumV2Inputs == 0)
7630 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7632 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7633 "to be V1-input shuffles.");
7635 if (NumV1Inputs + NumV2Inputs <= 4)
7636 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7638 // Check whether an interleaving lowering is likely to be more efficient.
7639 // This isn't perfect but it is a strong heuristic that tends to work well on
7640 // the kinds of shuffles that show up in practice.
7642 // FIXME: Handle 1x, 2x, and 4x interleaving.
7643 if (shouldLowerAsInterleaving(Mask)) {
7644 // FIXME: Figure out whether we should pack these into the low or high
7647 int EMask[8], OMask[8];
7648 for (int i = 0; i < 4; ++i) {
7649 EMask[i] = Mask[2*i];
7650 OMask[i] = Mask[2*i + 1];
7655 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7656 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7658 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7661 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7662 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7664 for (int i = 0; i < 4; ++i) {
7665 LoBlendMask[i] = Mask[i];
7666 HiBlendMask[i] = Mask[i + 4];
7669 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7670 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7671 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7672 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7674 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7675 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7678 /// \brief Generic lowering of v16i8 shuffles.
7680 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7681 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7682 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7683 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7685 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7686 const X86Subtarget *Subtarget,
7687 SelectionDAG &DAG) {
7689 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7690 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7691 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7692 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7693 ArrayRef<int> OrigMask = SVOp->getMask();
7694 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7695 int MaskStorage[16] = {
7696 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7697 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
7698 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
7699 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7700 MutableArrayRef<int> Mask(MaskStorage);
7701 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7702 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7704 // For single-input shuffles, there are some nicer lowering tricks we can use.
7705 if (isSingleInputShuffleMask(Mask)) {
7706 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7707 // Notably, this handles splat and partial-splat shuffles more efficiently.
7708 // However, it only makes sense if the pre-duplication shuffle simplifies
7709 // things significantly. Currently, this means we need to be able to
7710 // express the pre-duplication shuffle as an i16 shuffle.
7712 // FIXME: We should check for other patterns which can be widened into an
7713 // i16 shuffle as well.
7714 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7715 for (int i = 0; i < 16; i += 2) {
7716 if (Mask[i] != Mask[i + 1])
7721 auto tryToWidenViaDuplication = [&]() -> SDValue {
7722 if (!canWidenViaDuplication(Mask))
7724 SmallVector<int, 4> LoInputs;
7725 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7726 [](int M) { return M >= 0 && M < 8; });
7727 std::sort(LoInputs.begin(), LoInputs.end());
7728 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7730 SmallVector<int, 4> HiInputs;
7731 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7732 [](int M) { return M >= 8; });
7733 std::sort(HiInputs.begin(), HiInputs.end());
7734 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7737 bool TargetLo = LoInputs.size() >= HiInputs.size();
7738 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7739 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7741 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7742 SmallDenseMap<int, int, 8> LaneMap;
7743 for (int I : InPlaceInputs) {
7744 PreDupI16Shuffle[I/2] = I/2;
7747 int j = TargetLo ? 0 : 4, je = j + 4;
7748 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7749 // Check if j is already a shuffle of this input. This happens when
7750 // there are two adjacent bytes after we move the low one.
7751 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7752 // If we haven't yet mapped the input, search for a slot into which
7754 while (j < je && PreDupI16Shuffle[j] != -1)
7758 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7761 // Map this input with the i16 shuffle.
7762 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7765 // Update the lane map based on the mapping we ended up with.
7766 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7769 ISD::BITCAST, DL, MVT::v16i8,
7770 DAG.getVectorShuffle(MVT::v8i16, DL,
7771 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7772 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
7774 // Unpack the bytes to form the i16s that will be shuffled into place.
7775 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7776 MVT::v16i8, V1, V1);
7778 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7779 for (int i = 0; i < 16; i += 2) {
7781 PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7782 assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7785 ISD::BITCAST, DL, MVT::v16i8,
7786 DAG.getVectorShuffle(MVT::v8i16, DL,
7787 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7788 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7790 if (SDValue V = tryToWidenViaDuplication())
7794 // Check whether an interleaving lowering is likely to be more efficient.
7795 // This isn't perfect but it is a strong heuristic that tends to work well on
7796 // the kinds of shuffles that show up in practice.
7798 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7799 if (shouldLowerAsInterleaving(Mask)) {
7800 // FIXME: Figure out whether we should pack these into the low or high
7803 int EMask[16], OMask[16];
7804 for (int i = 0; i < 8; ++i) {
7805 EMask[i] = Mask[2*i];
7806 OMask[i] = Mask[2*i + 1];
7811 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7812 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7814 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7817 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7818 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7819 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7820 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7822 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7823 MutableArrayRef<int> V1HalfBlendMask,
7824 MutableArrayRef<int> V2HalfBlendMask) {
7825 for (int i = 0; i < 8; ++i)
7826 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7827 V1HalfBlendMask[i] = HalfMask[i];
7829 } else if (HalfMask[i] >= 16) {
7830 V2HalfBlendMask[i] = HalfMask[i] - 16;
7831 HalfMask[i] = i + 8;
7834 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7835 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7837 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7839 auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
7840 MutableArrayRef<int> HiBlendMask) {
7842 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
7843 // them out and avoid using UNPCK{L,H} to extract the elements of V as
7845 if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
7846 [](int M) { return M >= 0 && M % 2 == 1; }) &&
7847 std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
7848 [](int M) { return M >= 0 && M % 2 == 1; })) {
7849 // Use a mask to drop the high bytes.
7850 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
7851 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
7852 DAG.getConstant(0x00FF, MVT::v8i16));
7854 // This will be a single vector shuffle instead of a blend so nuke V2.
7855 V2 = DAG.getUNDEF(MVT::v8i16);
7857 // Squash the masks to point directly into V1.
7858 for (int &M : LoBlendMask)
7861 for (int &M : HiBlendMask)
7865 // Otherwise just unpack the low half of V into V1 and the high half into
7866 // V2 so that we can blend them as i16s.
7867 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7868 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
7869 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7870 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
7873 SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7874 SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7875 return std::make_pair(BlendedLo, BlendedHi);
7877 SDValue V1Lo, V1Hi, V2Lo, V2Hi;
7878 std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
7879 std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
7881 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7882 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7884 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7887 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7889 /// This routine breaks down the specific type of 128-bit shuffle and
7890 /// dispatches to the lowering routines accordingly.
7891 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7892 MVT VT, const X86Subtarget *Subtarget,
7893 SelectionDAG &DAG) {
7894 switch (VT.SimpleTy) {
7896 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7898 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7900 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7902 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7904 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7906 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7909 llvm_unreachable("Unimplemented!");
7913 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7914 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7915 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7916 if (Mask[i] + 1 != Mask[i+1])
7922 /// \brief Top-level lowering for x86 vector shuffles.
7924 /// This handles decomposition, canonicalization, and lowering of all x86
7925 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7926 /// above in helper routines. The canonicalization attempts to widen shuffles
7927 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7928 /// s.t. only one of the two inputs needs to be tested, etc.
7929 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7930 SelectionDAG &DAG) {
7931 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7932 ArrayRef<int> Mask = SVOp->getMask();
7933 SDValue V1 = Op.getOperand(0);
7934 SDValue V2 = Op.getOperand(1);
7935 MVT VT = Op.getSimpleValueType();
7936 int NumElements = VT.getVectorNumElements();
7939 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7941 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7942 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7943 if (V1IsUndef && V2IsUndef)
7944 return DAG.getUNDEF(VT);
7946 // When we create a shuffle node we put the UNDEF node to second operand,
7947 // but in some cases the first operand may be transformed to UNDEF.
7948 // In this case we should just commute the node.
7950 return CommuteVectorShuffle(SVOp, DAG);
7952 // Check for non-undef masks pointing at an undef vector and make the masks
7953 // undef as well. This makes it easier to match the shuffle based solely on
7957 if (M >= NumElements) {
7958 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7959 for (int &M : NewMask)
7960 if (M >= NumElements)
7962 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7965 // For integer vector shuffles, try to collapse them into a shuffle of fewer
7966 // lanes but wider integers. We cap this to not form integers larger than i64
7967 // but it might be interesting to form i128 integers to handle flipping the
7968 // low and high halves of AVX 256-bit vectors.
7969 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7970 areAdjacentMasksSequential(Mask)) {
7971 SmallVector<int, 8> NewMask;
7972 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7973 NewMask.push_back(Mask[i] / 2);
7975 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7976 VT.getVectorNumElements() / 2);
7977 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7978 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7979 return DAG.getNode(ISD::BITCAST, dl, VT,
7980 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7983 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7984 for (int M : SVOp->getMask())
7987 else if (M < NumElements)
7992 // Commute the shuffle as needed such that more elements come from V1 than
7993 // V2. This allows us to match the shuffle pattern strictly on how many
7994 // elements come from V1 without handling the symmetric cases.
7995 if (NumV2Elements > NumV1Elements)
7996 return CommuteVectorShuffle(SVOp, DAG);
7998 // When the number of V1 and V2 elements are the same, try to minimize the
7999 // number of uses of V2 in the low half of the vector.
8000 if (NumV1Elements == NumV2Elements) {
8001 int LowV1Elements = 0, LowV2Elements = 0;
8002 for (int M : SVOp->getMask().slice(0, NumElements / 2))
8003 if (M >= NumElements)
8007 if (LowV2Elements > LowV1Elements)
8008 return CommuteVectorShuffle(SVOp, DAG);
8011 // For each vector width, delegate to a specialized lowering routine.
8012 if (VT.getSizeInBits() == 128)
8013 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8015 llvm_unreachable("Unimplemented!");
8019 //===----------------------------------------------------------------------===//
8020 // Legacy vector shuffle lowering
8022 // This code is the legacy code handling vector shuffles until the above
8023 // replaces its functionality and performance.
8024 //===----------------------------------------------------------------------===//
8026 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8027 bool hasInt256, unsigned *MaskOut = nullptr) {
8028 MVT EltVT = VT.getVectorElementType();
8030 // There is no blend with immediate in AVX-512.
8031 if (VT.is512BitVector())
8034 if (!hasSSE41 || EltVT == MVT::i8)
8036 if (!hasInt256 && VT == MVT::v16i16)
8039 unsigned MaskValue = 0;
8040 unsigned NumElems = VT.getVectorNumElements();
8041 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8042 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8043 unsigned NumElemsInLane = NumElems / NumLanes;
8045 // Blend for v16i16 should be symetric for the both lanes.
8046 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8048 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8049 int EltIdx = MaskVals[i];
8051 if ((EltIdx < 0 || EltIdx == (int)i) &&
8052 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8055 if (((unsigned)EltIdx == (i + NumElems)) &&
8056 (SndLaneEltIdx < 0 ||
8057 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8058 MaskValue |= (1 << i);
8064 *MaskOut = MaskValue;
8068 // Try to lower a shuffle node into a simple blend instruction.
8069 // This function assumes isBlendMask returns true for this
8070 // SuffleVectorSDNode
8071 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8073 const X86Subtarget *Subtarget,
8074 SelectionDAG &DAG) {
8075 MVT VT = SVOp->getSimpleValueType(0);
8076 MVT EltVT = VT.getVectorElementType();
8077 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8078 Subtarget->hasInt256() && "Trying to lower a "
8079 "VECTOR_SHUFFLE to a Blend but "
8080 "with the wrong mask"));
8081 SDValue V1 = SVOp->getOperand(0);
8082 SDValue V2 = SVOp->getOperand(1);
8084 unsigned NumElems = VT.getVectorNumElements();
8086 // Convert i32 vectors to floating point if it is not AVX2.
8087 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8089 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8090 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8092 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8093 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8096 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8097 DAG.getConstant(MaskValue, MVT::i32));
8098 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8101 /// In vector type \p VT, return true if the element at index \p InputIdx
8102 /// falls on a different 128-bit lane than \p OutputIdx.
8103 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8104 unsigned OutputIdx) {
8105 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8106 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8109 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
8110 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
8111 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
8112 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8114 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8115 SelectionDAG &DAG) {
8116 MVT VT = V1.getSimpleValueType();
8117 assert(VT.is128BitVector() || VT.is256BitVector());
8119 MVT EltVT = VT.getVectorElementType();
8120 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8121 unsigned NumElts = VT.getVectorNumElements();
8123 SmallVector<SDValue, 32> PshufbMask;
8124 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8125 int InputIdx = MaskVals[OutputIdx];
8126 unsigned InputByteIdx;
8128 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8129 InputByteIdx = 0x80;
8131 // Cross lane is not allowed.
8132 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8134 InputByteIdx = InputIdx * EltSizeInBytes;
8135 // Index is an byte offset within the 128-bit lane.
8136 InputByteIdx &= 0xf;
8139 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8140 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8141 if (InputByteIdx != 0x80)
8146 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8148 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8149 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8150 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8153 // v8i16 shuffles - Prefer shuffles in the following order:
8154 // 1. [all] pshuflw, pshufhw, optional move
8155 // 2. [ssse3] 1 x pshufb
8156 // 3. [ssse3] 2 x pshufb + 1 x por
8157 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8159 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8160 SelectionDAG &DAG) {
8161 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8162 SDValue V1 = SVOp->getOperand(0);
8163 SDValue V2 = SVOp->getOperand(1);
8165 SmallVector<int, 8> MaskVals;
8167 // Determine if more than 1 of the words in each of the low and high quadwords
8168 // of the result come from the same quadword of one of the two inputs. Undef
8169 // mask values count as coming from any quadword, for better codegen.
8171 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8172 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8173 unsigned LoQuad[] = { 0, 0, 0, 0 };
8174 unsigned HiQuad[] = { 0, 0, 0, 0 };
8175 // Indices of quads used.
8176 std::bitset<4> InputQuads;
8177 for (unsigned i = 0; i < 8; ++i) {
8178 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8179 int EltIdx = SVOp->getMaskElt(i);
8180 MaskVals.push_back(EltIdx);
8189 InputQuads.set(EltIdx / 4);
8192 int BestLoQuad = -1;
8193 unsigned MaxQuad = 1;
8194 for (unsigned i = 0; i < 4; ++i) {
8195 if (LoQuad[i] > MaxQuad) {
8197 MaxQuad = LoQuad[i];
8201 int BestHiQuad = -1;
8203 for (unsigned i = 0; i < 4; ++i) {
8204 if (HiQuad[i] > MaxQuad) {
8206 MaxQuad = HiQuad[i];
8210 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8211 // of the two input vectors, shuffle them into one input vector so only a
8212 // single pshufb instruction is necessary. If there are more than 2 input
8213 // quads, disable the next transformation since it does not help SSSE3.
8214 bool V1Used = InputQuads[0] || InputQuads[1];
8215 bool V2Used = InputQuads[2] || InputQuads[3];
8216 if (Subtarget->hasSSSE3()) {
8217 if (InputQuads.count() == 2 && V1Used && V2Used) {
8218 BestLoQuad = InputQuads[0] ? 0 : 1;
8219 BestHiQuad = InputQuads[2] ? 2 : 3;
8221 if (InputQuads.count() > 2) {
8227 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8228 // the shuffle mask. If a quad is scored as -1, that means that it contains
8229 // words from all 4 input quadwords.
8231 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8233 BestLoQuad < 0 ? 0 : BestLoQuad,
8234 BestHiQuad < 0 ? 1 : BestHiQuad
8236 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8237 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8238 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8239 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8241 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8242 // source words for the shuffle, to aid later transformations.
8243 bool AllWordsInNewV = true;
8244 bool InOrder[2] = { true, true };
8245 for (unsigned i = 0; i != 8; ++i) {
8246 int idx = MaskVals[i];
8248 InOrder[i/4] = false;
8249 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8251 AllWordsInNewV = false;
8255 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8256 if (AllWordsInNewV) {
8257 for (int i = 0; i != 8; ++i) {
8258 int idx = MaskVals[i];
8261 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8262 if ((idx != i) && idx < 4)
8264 if ((idx != i) && idx > 3)
8273 // If we've eliminated the use of V2, and the new mask is a pshuflw or
8274 // pshufhw, that's as cheap as it gets. Return the new shuffle.
8275 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8276 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8277 unsigned TargetMask = 0;
8278 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8279 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8280 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8281 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8282 getShufflePSHUFLWImmediate(SVOp);
8283 V1 = NewV.getOperand(0);
8284 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8288 // Promote splats to a larger type which usually leads to more efficient code.
8289 // FIXME: Is this true if pshufb is available?
8290 if (SVOp->isSplat())
8291 return PromoteSplat(SVOp, DAG);
8293 // If we have SSSE3, and all words of the result are from 1 input vector,
8294 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
8295 // is present, fall back to case 4.
8296 if (Subtarget->hasSSSE3()) {
8297 SmallVector<SDValue,16> pshufbMask;
8299 // If we have elements from both input vectors, set the high bit of the
8300 // shuffle mask element to zero out elements that come from V2 in the V1
8301 // mask, and elements that come from V1 in the V2 mask, so that the two
8302 // results can be OR'd together.
8303 bool TwoInputs = V1Used && V2Used;
8304 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8306 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8308 // Calculate the shuffle mask for the second input, shuffle it, and
8309 // OR it with the first shuffled input.
8310 CommuteVectorShuffleMask(MaskVals, 8);
8311 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8312 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8313 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8316 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8317 // and update MaskVals with new element order.
8318 std::bitset<8> InOrder;
8319 if (BestLoQuad >= 0) {
8320 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8321 for (int i = 0; i != 4; ++i) {
8322 int idx = MaskVals[i];
8325 } else if ((idx / 4) == BestLoQuad) {
8330 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8333 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8334 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8335 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8337 getShufflePSHUFLWImmediate(SVOp), DAG);
8341 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8342 // and update MaskVals with the new element order.
8343 if (BestHiQuad >= 0) {
8344 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8345 for (unsigned i = 4; i != 8; ++i) {
8346 int idx = MaskVals[i];
8349 } else if ((idx / 4) == BestHiQuad) {
8350 MaskV[i] = (idx & 3) + 4;
8354 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8357 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8358 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8359 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8361 getShufflePSHUFHWImmediate(SVOp), DAG);
8365 // In case BestHi & BestLo were both -1, which means each quadword has a word
8366 // from each of the four input quadwords, calculate the InOrder bitvector now
8367 // before falling through to the insert/extract cleanup.
8368 if (BestLoQuad == -1 && BestHiQuad == -1) {
8370 for (int i = 0; i != 8; ++i)
8371 if (MaskVals[i] < 0 || MaskVals[i] == i)
8375 // The other elements are put in the right place using pextrw and pinsrw.
8376 for (unsigned i = 0; i != 8; ++i) {
8379 int EltIdx = MaskVals[i];
8382 SDValue ExtOp = (EltIdx < 8) ?
8383 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8384 DAG.getIntPtrConstant(EltIdx)) :
8385 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8386 DAG.getIntPtrConstant(EltIdx - 8));
8387 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8388 DAG.getIntPtrConstant(i));
8393 /// \brief v16i16 shuffles
8395 /// FIXME: We only support generation of a single pshufb currently. We can
8396 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8397 /// well (e.g 2 x pshufb + 1 x por).
8399 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8400 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8401 SDValue V1 = SVOp->getOperand(0);
8402 SDValue V2 = SVOp->getOperand(1);
8405 if (V2.getOpcode() != ISD::UNDEF)
8408 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8409 return getPSHUFB(MaskVals, V1, dl, DAG);
8412 // v16i8 shuffles - Prefer shuffles in the following order:
8413 // 1. [ssse3] 1 x pshufb
8414 // 2. [ssse3] 2 x pshufb + 1 x por
8415 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
8416 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8417 const X86Subtarget* Subtarget,
8418 SelectionDAG &DAG) {
8419 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8420 SDValue V1 = SVOp->getOperand(0);
8421 SDValue V2 = SVOp->getOperand(1);
8423 ArrayRef<int> MaskVals = SVOp->getMask();
8425 // Promote splats to a larger type which usually leads to more efficient code.
8426 // FIXME: Is this true if pshufb is available?
8427 if (SVOp->isSplat())
8428 return PromoteSplat(SVOp, DAG);
8430 // If we have SSSE3, case 1 is generated when all result bytes come from
8431 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
8432 // present, fall back to case 3.
8434 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8435 if (Subtarget->hasSSSE3()) {
8436 SmallVector<SDValue,16> pshufbMask;
8438 // If all result elements are from one input vector, then only translate
8439 // undef mask values to 0x80 (zero out result) in the pshufb mask.
8441 // Otherwise, we have elements from both input vectors, and must zero out
8442 // elements that come from V2 in the first mask, and V1 in the second mask
8443 // so that we can OR them together.
8444 for (unsigned i = 0; i != 16; ++i) {
8445 int EltIdx = MaskVals[i];
8446 if (EltIdx < 0 || EltIdx >= 16)
8448 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8450 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8451 DAG.getNode(ISD::BUILD_VECTOR, dl,
8452 MVT::v16i8, pshufbMask));
8454 // As PSHUFB will zero elements with negative indices, it's safe to ignore
8455 // the 2nd operand if it's undefined or zero.
8456 if (V2.getOpcode() == ISD::UNDEF ||
8457 ISD::isBuildVectorAllZeros(V2.getNode()))
8460 // Calculate the shuffle mask for the second input, shuffle it, and
8461 // OR it with the first shuffled input.
8463 for (unsigned i = 0; i != 16; ++i) {
8464 int EltIdx = MaskVals[i];
8465 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8466 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8468 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8469 DAG.getNode(ISD::BUILD_VECTOR, dl,
8470 MVT::v16i8, pshufbMask));
8471 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8474 // No SSSE3 - Calculate in place words and then fix all out of place words
8475 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
8476 // the 16 different words that comprise the two doublequadword input vectors.
8477 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8478 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8480 for (int i = 0; i != 8; ++i) {
8481 int Elt0 = MaskVals[i*2];
8482 int Elt1 = MaskVals[i*2+1];
8484 // This word of the result is all undef, skip it.
8485 if (Elt0 < 0 && Elt1 < 0)
8488 // This word of the result is already in the correct place, skip it.
8489 if ((Elt0 == i*2) && (Elt1 == i*2+1))
8492 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8493 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8496 // If Elt0 and Elt1 are defined, are consecutive, and can be load
8497 // using a single extract together, load it and store it.
8498 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8499 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8500 DAG.getIntPtrConstant(Elt1 / 2));
8501 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8502 DAG.getIntPtrConstant(i));
8506 // If Elt1 is defined, extract it from the appropriate source. If the
8507 // source byte is not also odd, shift the extracted word left 8 bits
8508 // otherwise clear the bottom 8 bits if we need to do an or.
8510 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8511 DAG.getIntPtrConstant(Elt1 / 2));
8512 if ((Elt1 & 1) == 0)
8513 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8515 TLI.getShiftAmountTy(InsElt.getValueType())));
8517 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8518 DAG.getConstant(0xFF00, MVT::i16));
8520 // If Elt0 is defined, extract it from the appropriate source. If the
8521 // source byte is not also even, shift the extracted word right 8 bits. If
8522 // Elt1 was also defined, OR the extracted values together before
8523 // inserting them in the result.
8525 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8526 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8527 if ((Elt0 & 1) != 0)
8528 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8530 TLI.getShiftAmountTy(InsElt0.getValueType())));
8532 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8533 DAG.getConstant(0x00FF, MVT::i16));
8534 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8537 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8538 DAG.getIntPtrConstant(i));
8540 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8543 // v32i8 shuffles - Translate to VPSHUFB if possible.
8545 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8546 const X86Subtarget *Subtarget,
8547 SelectionDAG &DAG) {
8548 MVT VT = SVOp->getSimpleValueType(0);
8549 SDValue V1 = SVOp->getOperand(0);
8550 SDValue V2 = SVOp->getOperand(1);
8552 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8554 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8555 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8556 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8558 // VPSHUFB may be generated if
8559 // (1) one of input vector is undefined or zeroinitializer.
8560 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8561 // And (2) the mask indexes don't cross the 128-bit lane.
8562 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8563 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8566 if (V1IsAllZero && !V2IsAllZero) {
8567 CommuteVectorShuffleMask(MaskVals, 32);
8570 return getPSHUFB(MaskVals, V1, dl, DAG);
8573 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8574 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8575 /// done when every pair / quad of shuffle mask elements point to elements in
8576 /// the right sequence. e.g.
8577 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8579 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8580 SelectionDAG &DAG) {
8581 MVT VT = SVOp->getSimpleValueType(0);
8583 unsigned NumElems = VT.getVectorNumElements();
8586 switch (VT.SimpleTy) {
8587 default: llvm_unreachable("Unexpected!");
8590 return SDValue(SVOp, 0);
8591 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
8592 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
8593 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
8594 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
8595 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8596 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
8599 SmallVector<int, 8> MaskVec;
8600 for (unsigned i = 0; i != NumElems; i += Scale) {
8602 for (unsigned j = 0; j != Scale; ++j) {
8603 int EltIdx = SVOp->getMaskElt(i+j);
8607 StartIdx = (EltIdx / Scale);
8608 if (EltIdx != (int)(StartIdx*Scale + j))
8611 MaskVec.push_back(StartIdx);
8614 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8615 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8616 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8619 /// getVZextMovL - Return a zero-extending vector move low node.
8621 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8622 SDValue SrcOp, SelectionDAG &DAG,
8623 const X86Subtarget *Subtarget, SDLoc dl) {
8624 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8625 LoadSDNode *LD = nullptr;
8626 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8627 LD = dyn_cast<LoadSDNode>(SrcOp);
8629 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8631 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8632 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8633 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8634 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8635 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8637 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8638 return DAG.getNode(ISD::BITCAST, dl, VT,
8639 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8640 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8648 return DAG.getNode(ISD::BITCAST, dl, VT,
8649 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8650 DAG.getNode(ISD::BITCAST, dl,
8654 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8655 /// which could not be matched by any known target speficic shuffle
8657 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8659 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8660 if (NewOp.getNode())
8663 MVT VT = SVOp->getSimpleValueType(0);
8665 unsigned NumElems = VT.getVectorNumElements();
8666 unsigned NumLaneElems = NumElems / 2;
8669 MVT EltVT = VT.getVectorElementType();
8670 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8673 SmallVector<int, 16> Mask;
8674 for (unsigned l = 0; l < 2; ++l) {
8675 // Build a shuffle mask for the output, discovering on the fly which
8676 // input vectors to use as shuffle operands (recorded in InputUsed).
8677 // If building a suitable shuffle vector proves too hard, then bail
8678 // out with UseBuildVector set.
8679 bool UseBuildVector = false;
8680 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8681 unsigned LaneStart = l * NumLaneElems;
8682 for (unsigned i = 0; i != NumLaneElems; ++i) {
8683 // The mask element. This indexes into the input.
8684 int Idx = SVOp->getMaskElt(i+LaneStart);
8686 // the mask element does not index into any input vector.
8691 // The input vector this mask element indexes into.
8692 int Input = Idx / NumLaneElems;
8694 // Turn the index into an offset from the start of the input vector.
8695 Idx -= Input * NumLaneElems;
8697 // Find or create a shuffle vector operand to hold this input.
8699 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8700 if (InputUsed[OpNo] == Input)
8701 // This input vector is already an operand.
8703 if (InputUsed[OpNo] < 0) {
8704 // Create a new operand for this input vector.
8705 InputUsed[OpNo] = Input;
8710 if (OpNo >= array_lengthof(InputUsed)) {
8711 // More than two input vectors used! Give up on trying to create a
8712 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
8713 UseBuildVector = true;
8717 // Add the mask index for the new shuffle vector.
8718 Mask.push_back(Idx + OpNo * NumLaneElems);
8721 if (UseBuildVector) {
8722 SmallVector<SDValue, 16> SVOps;
8723 for (unsigned i = 0; i != NumLaneElems; ++i) {
8724 // The mask element. This indexes into the input.
8725 int Idx = SVOp->getMaskElt(i+LaneStart);
8727 SVOps.push_back(DAG.getUNDEF(EltVT));
8731 // The input vector this mask element indexes into.
8732 int Input = Idx / NumElems;
8734 // Turn the index into an offset from the start of the input vector.
8735 Idx -= Input * NumElems;
8737 // Extract the vector element by hand.
8738 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8739 SVOp->getOperand(Input),
8740 DAG.getIntPtrConstant(Idx)));
8743 // Construct the output using a BUILD_VECTOR.
8744 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8745 } else if (InputUsed[0] < 0) {
8746 // No input vectors were used! The result is undefined.
8747 Output[l] = DAG.getUNDEF(NVT);
8749 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8750 (InputUsed[0] % 2) * NumLaneElems,
8752 // If only one input was used, use an undefined vector for the other.
8753 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8754 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8755 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8756 // At least one input vector was used. Create a new shuffle vector.
8757 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8763 // Concatenate the result back
8764 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8767 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8768 /// 4 elements, and match them with several different shuffle types.
8770 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8771 SDValue V1 = SVOp->getOperand(0);
8772 SDValue V2 = SVOp->getOperand(1);
8774 MVT VT = SVOp->getSimpleValueType(0);
8776 assert(VT.is128BitVector() && "Unsupported vector size");
8778 std::pair<int, int> Locs[4];
8779 int Mask1[] = { -1, -1, -1, -1 };
8780 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8784 for (unsigned i = 0; i != 4; ++i) {
8785 int Idx = PermMask[i];
8787 Locs[i] = std::make_pair(-1, -1);
8789 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8791 Locs[i] = std::make_pair(0, NumLo);
8795 Locs[i] = std::make_pair(1, NumHi);
8797 Mask1[2+NumHi] = Idx;
8803 if (NumLo <= 2 && NumHi <= 2) {
8804 // If no more than two elements come from either vector. This can be
8805 // implemented with two shuffles. First shuffle gather the elements.
8806 // The second shuffle, which takes the first shuffle as both of its
8807 // vector operands, put the elements into the right order.
8808 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8810 int Mask2[] = { -1, -1, -1, -1 };
8812 for (unsigned i = 0; i != 4; ++i)
8813 if (Locs[i].first != -1) {
8814 unsigned Idx = (i < 2) ? 0 : 4;
8815 Idx += Locs[i].first * 2 + Locs[i].second;
8819 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8822 if (NumLo == 3 || NumHi == 3) {
8823 // Otherwise, we must have three elements from one vector, call it X, and
8824 // one element from the other, call it Y. First, use a shufps to build an
8825 // intermediate vector with the one element from Y and the element from X
8826 // that will be in the same half in the final destination (the indexes don't
8827 // matter). Then, use a shufps to build the final vector, taking the half
8828 // containing the element from Y from the intermediate, and the other half
8831 // Normalize it so the 3 elements come from V1.
8832 CommuteVectorShuffleMask(PermMask, 4);
8836 // Find the element from V2.
8838 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8839 int Val = PermMask[HiIndex];
8846 Mask1[0] = PermMask[HiIndex];
8848 Mask1[2] = PermMask[HiIndex^1];
8850 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8853 Mask1[0] = PermMask[0];
8854 Mask1[1] = PermMask[1];
8855 Mask1[2] = HiIndex & 1 ? 6 : 4;
8856 Mask1[3] = HiIndex & 1 ? 4 : 6;
8857 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8860 Mask1[0] = HiIndex & 1 ? 2 : 0;
8861 Mask1[1] = HiIndex & 1 ? 0 : 2;
8862 Mask1[2] = PermMask[2];
8863 Mask1[3] = PermMask[3];
8868 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8871 // Break it into (shuffle shuffle_hi, shuffle_lo).
8872 int LoMask[] = { -1, -1, -1, -1 };
8873 int HiMask[] = { -1, -1, -1, -1 };
8875 int *MaskPtr = LoMask;
8876 unsigned MaskIdx = 0;
8879 for (unsigned i = 0; i != 4; ++i) {
8886 int Idx = PermMask[i];
8888 Locs[i] = std::make_pair(-1, -1);
8889 } else if (Idx < 4) {
8890 Locs[i] = std::make_pair(MaskIdx, LoIdx);
8891 MaskPtr[LoIdx] = Idx;
8894 Locs[i] = std::make_pair(MaskIdx, HiIdx);
8895 MaskPtr[HiIdx] = Idx;
8900 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8901 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8902 int MaskOps[] = { -1, -1, -1, -1 };
8903 for (unsigned i = 0; i != 4; ++i)
8904 if (Locs[i].first != -1)
8905 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8906 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8909 static bool MayFoldVectorLoad(SDValue V) {
8910 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8911 V = V.getOperand(0);
8913 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8914 V = V.getOperand(0);
8915 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8916 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8917 // BUILD_VECTOR (load), undef
8918 V = V.getOperand(0);
8920 return MayFoldLoad(V);
8924 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8925 MVT VT = Op.getSimpleValueType();
8927 // Canonizalize to v2f64.
8928 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8929 return DAG.getNode(ISD::BITCAST, dl, VT,
8930 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8935 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8937 SDValue V1 = Op.getOperand(0);
8938 SDValue V2 = Op.getOperand(1);
8939 MVT VT = Op.getSimpleValueType();
8941 assert(VT != MVT::v2i64 && "unsupported shuffle type");
8943 if (HasSSE2 && VT == MVT::v2f64)
8944 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8946 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8947 return DAG.getNode(ISD::BITCAST, dl, VT,
8948 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8949 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8950 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8954 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8955 SDValue V1 = Op.getOperand(0);
8956 SDValue V2 = Op.getOperand(1);
8957 MVT VT = Op.getSimpleValueType();
8959 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8960 "unsupported shuffle type");
8962 if (V2.getOpcode() == ISD::UNDEF)
8966 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8970 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8971 SDValue V1 = Op.getOperand(0);
8972 SDValue V2 = Op.getOperand(1);
8973 MVT VT = Op.getSimpleValueType();
8974 unsigned NumElems = VT.getVectorNumElements();
8976 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8977 // operand of these instructions is only memory, so check if there's a
8978 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8980 bool CanFoldLoad = false;
8982 // Trivial case, when V2 comes from a load.
8983 if (MayFoldVectorLoad(V2))
8986 // When V1 is a load, it can be folded later into a store in isel, example:
8987 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8989 // (MOVLPSmr addr:$src1, VR128:$src2)
8990 // So, recognize this potential and also use MOVLPS or MOVLPD
8991 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8994 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8996 if (HasSSE2 && NumElems == 2)
8997 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9000 // If we don't care about the second element, proceed to use movss.
9001 if (SVOp->getMaskElt(1) != -1)
9002 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9005 // movl and movlp will both match v2i64, but v2i64 is never matched by
9006 // movl earlier because we make it strict to avoid messing with the movlp load
9007 // folding logic (see the code above getMOVLP call). Match it here then,
9008 // this is horrible, but will stay like this until we move all shuffle
9009 // matching to x86 specific nodes. Note that for the 1st condition all
9010 // types are matched with movsd.
9012 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9013 // as to remove this logic from here, as much as possible
9014 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9015 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9016 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9019 assert(VT != MVT::v4i32 && "unsupported shuffle type");
9021 // Invert the operand order and use SHUFPS to match it.
9022 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9023 getShuffleSHUFImmediate(SVOp), DAG);
9026 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9027 SelectionDAG &DAG) {
9029 MVT VT = Load->getSimpleValueType(0);
9030 MVT EVT = VT.getVectorElementType();
9031 SDValue Addr = Load->getOperand(1);
9032 SDValue NewAddr = DAG.getNode(
9033 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9034 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9037 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9038 DAG.getMachineFunction().getMachineMemOperand(
9039 Load->getMemOperand(), 0, EVT.getStoreSize()));
9043 // It is only safe to call this function if isINSERTPSMask is true for
9044 // this shufflevector mask.
9045 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9046 SelectionDAG &DAG) {
9047 // Generate an insertps instruction when inserting an f32 from memory onto a
9048 // v4f32 or when copying a member from one v4f32 to another.
9049 // We also use it for transferring i32 from one register to another,
9050 // since it simply copies the same bits.
9051 // If we're transferring an i32 from memory to a specific element in a
9052 // register, we output a generic DAG that will match the PINSRD
9054 MVT VT = SVOp->getSimpleValueType(0);
9055 MVT EVT = VT.getVectorElementType();
9056 SDValue V1 = SVOp->getOperand(0);
9057 SDValue V2 = SVOp->getOperand(1);
9058 auto Mask = SVOp->getMask();
9059 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9060 "unsupported vector type for insertps/pinsrd");
9062 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9063 auto FromV2Predicate = [](const int &i) { return i >= 4; };
9064 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9072 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9075 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9076 "More than one element from V1 and from V2, or no elements from one "
9077 "of the vectors. This case should not have returned true from "
9082 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9085 unsigned SrcIndex = Mask[DestIndex] % 4;
9086 if (MayFoldLoad(From)) {
9087 // Trivial case, when From comes from a load and is only used by the
9088 // shuffle. Make it use insertps from the vector that we need from that
9091 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9092 if (!NewLoad.getNode())
9095 if (EVT == MVT::f32) {
9096 // Create this as a scalar to vector to match the instruction pattern.
9097 SDValue LoadScalarToVector =
9098 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9099 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9100 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9102 } else { // EVT == MVT::i32
9103 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9104 // instruction, to match the PINSRD instruction, which loads an i32 to a
9105 // certain vector element.
9106 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9107 DAG.getConstant(DestIndex, MVT::i32));
9111 // Vector-element-to-vector
9112 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9113 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9116 // Reduce a vector shuffle to zext.
9117 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9118 SelectionDAG &DAG) {
9119 // PMOVZX is only available from SSE41.
9120 if (!Subtarget->hasSSE41())
9123 MVT VT = Op.getSimpleValueType();
9125 // Only AVX2 support 256-bit vector integer extending.
9126 if (!Subtarget->hasInt256() && VT.is256BitVector())
9129 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9131 SDValue V1 = Op.getOperand(0);
9132 SDValue V2 = Op.getOperand(1);
9133 unsigned NumElems = VT.getVectorNumElements();
9135 // Extending is an unary operation and the element type of the source vector
9136 // won't be equal to or larger than i64.
9137 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9138 VT.getVectorElementType() == MVT::i64)
9141 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9142 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9143 while ((1U << Shift) < NumElems) {
9144 if (SVOp->getMaskElt(1U << Shift) == 1)
9147 // The maximal ratio is 8, i.e. from i8 to i64.
9152 // Check the shuffle mask.
9153 unsigned Mask = (1U << Shift) - 1;
9154 for (unsigned i = 0; i != NumElems; ++i) {
9155 int EltIdx = SVOp->getMaskElt(i);
9156 if ((i & Mask) != 0 && EltIdx != -1)
9158 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9162 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9163 MVT NeVT = MVT::getIntegerVT(NBits);
9164 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9166 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9169 // Simplify the operand as it's prepared to be fed into shuffle.
9170 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9171 if (V1.getOpcode() == ISD::BITCAST &&
9172 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9173 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9174 V1.getOperand(0).getOperand(0)
9175 .getSimpleValueType().getSizeInBits() == SignificantBits) {
9176 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9177 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9178 ConstantSDNode *CIdx =
9179 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9180 // If it's foldable, i.e. normal load with single use, we will let code
9181 // selection to fold it. Otherwise, we will short the conversion sequence.
9182 if (CIdx && CIdx->getZExtValue() == 0 &&
9183 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9184 MVT FullVT = V.getSimpleValueType();
9185 MVT V1VT = V1.getSimpleValueType();
9186 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9187 // The "ext_vec_elt" node is wider than the result node.
9188 // In this case we should extract subvector from V.
9189 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9190 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9191 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9192 FullVT.getVectorNumElements()/Ratio);
9193 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9194 DAG.getIntPtrConstant(0));
9196 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9200 return DAG.getNode(ISD::BITCAST, DL, VT,
9201 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9204 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9205 SelectionDAG &DAG) {
9206 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9207 MVT VT = Op.getSimpleValueType();
9209 SDValue V1 = Op.getOperand(0);
9210 SDValue V2 = Op.getOperand(1);
9212 if (isZeroShuffle(SVOp))
9213 return getZeroVector(VT, Subtarget, DAG, dl);
9215 // Handle splat operations
9216 if (SVOp->isSplat()) {
9217 // Use vbroadcast whenever the splat comes from a foldable load
9218 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9219 if (Broadcast.getNode())
9223 // Check integer expanding shuffles.
9224 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9225 if (NewOp.getNode())
9228 // If the shuffle can be profitably rewritten as a narrower shuffle, then
9230 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9232 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9233 if (NewOp.getNode())
9234 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9235 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9236 // FIXME: Figure out a cleaner way to do this.
9237 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9238 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9239 if (NewOp.getNode()) {
9240 MVT NewVT = NewOp.getSimpleValueType();
9241 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9242 NewVT, true, false))
9243 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9246 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9247 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9248 if (NewOp.getNode()) {
9249 MVT NewVT = NewOp.getSimpleValueType();
9250 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9251 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9260 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9261 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9262 SDValue V1 = Op.getOperand(0);
9263 SDValue V2 = Op.getOperand(1);
9264 MVT VT = Op.getSimpleValueType();
9266 unsigned NumElems = VT.getVectorNumElements();
9267 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9268 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9269 bool V1IsSplat = false;
9270 bool V2IsSplat = false;
9271 bool HasSSE2 = Subtarget->hasSSE2();
9272 bool HasFp256 = Subtarget->hasFp256();
9273 bool HasInt256 = Subtarget->hasInt256();
9274 MachineFunction &MF = DAG.getMachineFunction();
9275 bool OptForSize = MF.getFunction()->getAttributes().
9276 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9278 // Check if we should use the experimental vector shuffle lowering. If so,
9279 // delegate completely to that code path.
9280 if (ExperimentalVectorShuffleLowering)
9281 return lowerVectorShuffle(Op, Subtarget, DAG);
9283 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9285 if (V1IsUndef && V2IsUndef)
9286 return DAG.getUNDEF(VT);
9288 // When we create a shuffle node we put the UNDEF node to second operand,
9289 // but in some cases the first operand may be transformed to UNDEF.
9290 // In this case we should just commute the node.
9292 return CommuteVectorShuffle(SVOp, DAG);
9294 // Vector shuffle lowering takes 3 steps:
9296 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9297 // narrowing and commutation of operands should be handled.
9298 // 2) Matching of shuffles with known shuffle masks to x86 target specific
9300 // 3) Rewriting of unmatched masks into new generic shuffle operations,
9301 // so the shuffle can be broken into other shuffles and the legalizer can
9302 // try the lowering again.
9304 // The general idea is that no vector_shuffle operation should be left to
9305 // be matched during isel, all of them must be converted to a target specific
9308 // Normalize the input vectors. Here splats, zeroed vectors, profitable
9309 // narrowing and commutation of operands should be handled. The actual code
9310 // doesn't include all of those, work in progress...
9311 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9312 if (NewOp.getNode())
9315 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9317 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9318 // unpckh_undef). Only use pshufd if speed is more important than size.
9319 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9320 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9321 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9322 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9324 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9325 V2IsUndef && MayFoldVectorLoad(V1))
9326 return getMOVDDup(Op, dl, V1, DAG);
9328 if (isMOVHLPS_v_undef_Mask(M, VT))
9329 return getMOVHighToLow(Op, dl, DAG);
9331 // Use to match splats
9332 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9333 (VT == MVT::v2f64 || VT == MVT::v2i64))
9334 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9336 if (isPSHUFDMask(M, VT)) {
9337 // The actual implementation will match the mask in the if above and then
9338 // during isel it can match several different instructions, not only pshufd
9339 // as its name says, sad but true, emulate the behavior for now...
9340 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9341 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9343 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9345 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9346 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9348 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9349 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9352 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9356 if (isPALIGNRMask(M, VT, Subtarget))
9357 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9358 getShufflePALIGNRImmediate(SVOp),
9361 // Check if this can be converted into a logical shift.
9362 bool isLeft = false;
9365 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9366 if (isShift && ShVal.hasOneUse()) {
9367 // If the shifted value has multiple uses, it may be cheaper to use
9368 // v_set0 + movlhps or movhlps, etc.
9369 MVT EltVT = VT.getVectorElementType();
9370 ShAmt *= EltVT.getSizeInBits();
9371 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9374 if (isMOVLMask(M, VT)) {
9375 if (ISD::isBuildVectorAllZeros(V1.getNode()))
9376 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9377 if (!isMOVLPMask(M, VT)) {
9378 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9379 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9381 if (VT == MVT::v4i32 || VT == MVT::v4f32)
9382 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9386 // FIXME: fold these into legal mask.
9387 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9388 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9390 if (isMOVHLPSMask(M, VT))
9391 return getMOVHighToLow(Op, dl, DAG);
9393 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9394 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9396 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9397 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9399 if (isMOVLPMask(M, VT))
9400 return getMOVLP(Op, dl, DAG, HasSSE2);
9402 if (ShouldXformToMOVHLPS(M, VT) ||
9403 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9404 return CommuteVectorShuffle(SVOp, DAG);
9407 // No better options. Use a vshldq / vsrldq.
9408 MVT EltVT = VT.getVectorElementType();
9409 ShAmt *= EltVT.getSizeInBits();
9410 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9413 bool Commuted = false;
9414 // FIXME: This should also accept a bitcast of a splat? Be careful, not
9415 // 1,1,1,1 -> v8i16 though.
9416 BitVector UndefElements;
9417 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9418 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9420 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9421 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9424 // Canonicalize the splat or undef, if present, to be on the RHS.
9425 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9426 CommuteVectorShuffleMask(M, NumElems);
9428 std::swap(V1IsSplat, V2IsSplat);
9432 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9433 // Shuffling low element of v1 into undef, just return v1.
9436 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9437 // the instruction selector will not match, so get a canonical MOVL with
9438 // swapped operands to undo the commute.
9439 return getMOVL(DAG, dl, VT, V2, V1);
9442 if (isUNPCKLMask(M, VT, HasInt256))
9443 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9445 if (isUNPCKHMask(M, VT, HasInt256))
9446 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9449 // Normalize mask so all entries that point to V2 points to its first
9450 // element then try to match unpck{h|l} again. If match, return a
9451 // new vector_shuffle with the corrected mask.p
9452 SmallVector<int, 8> NewMask(M.begin(), M.end());
9453 NormalizeMask(NewMask, NumElems);
9454 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9455 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9456 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9457 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9461 // Commute is back and try unpck* again.
9462 // FIXME: this seems wrong.
9463 CommuteVectorShuffleMask(M, NumElems);
9465 std::swap(V1IsSplat, V2IsSplat);
9467 if (isUNPCKLMask(M, VT, HasInt256))
9468 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9470 if (isUNPCKHMask(M, VT, HasInt256))
9471 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9474 // Normalize the node to match x86 shuffle ops if needed
9475 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9476 return CommuteVectorShuffle(SVOp, DAG);
9478 // The checks below are all present in isShuffleMaskLegal, but they are
9479 // inlined here right now to enable us to directly emit target specific
9480 // nodes, and remove one by one until they don't return Op anymore.
9482 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9483 SVOp->getSplatIndex() == 0 && V2IsUndef) {
9484 if (VT == MVT::v2f64 || VT == MVT::v2i64)
9485 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9488 if (isPSHUFHWMask(M, VT, HasInt256))
9489 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9490 getShufflePSHUFHWImmediate(SVOp),
9493 if (isPSHUFLWMask(M, VT, HasInt256))
9494 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9495 getShufflePSHUFLWImmediate(SVOp),
9499 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9501 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9503 if (isSHUFPMask(M, VT))
9504 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9505 getShuffleSHUFImmediate(SVOp), DAG);
9507 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9508 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9509 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9510 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9512 //===--------------------------------------------------------------------===//
9513 // Generate target specific nodes for 128 or 256-bit shuffles only
9514 // supported in the AVX instruction set.
9517 // Handle VMOVDDUPY permutations
9518 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9519 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9521 // Handle VPERMILPS/D* permutations
9522 if (isVPERMILPMask(M, VT)) {
9523 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9524 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9525 getShuffleSHUFImmediate(SVOp), DAG);
9526 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9527 getShuffleSHUFImmediate(SVOp), DAG);
9531 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9532 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9533 Idx*(NumElems/2), DAG, dl);
9535 // Handle VPERM2F128/VPERM2I128 permutations
9536 if (isVPERM2X128Mask(M, VT, HasFp256))
9537 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9538 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9540 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9541 return getINSERTPS(SVOp, dl, DAG);
9544 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9545 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9547 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9548 VT.is512BitVector()) {
9549 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9550 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9551 SmallVector<SDValue, 16> permclMask;
9552 for (unsigned i = 0; i != NumElems; ++i) {
9553 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9556 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9558 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9559 return DAG.getNode(X86ISD::VPERMV, dl, VT,
9560 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9561 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9562 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9565 //===--------------------------------------------------------------------===//
9566 // Since no target specific shuffle was selected for this generic one,
9567 // lower it into other known shuffles. FIXME: this isn't true yet, but
9568 // this is the plan.
9571 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9572 if (VT == MVT::v8i16) {
9573 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9574 if (NewOp.getNode())
9578 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9579 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9580 if (NewOp.getNode())
9584 if (VT == MVT::v16i8) {
9585 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9586 if (NewOp.getNode())
9590 if (VT == MVT::v32i8) {
9591 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9592 if (NewOp.getNode())
9596 // Handle all 128-bit wide vectors with 4 elements, and match them with
9597 // several different shuffle types.
9598 if (NumElems == 4 && VT.is128BitVector())
9599 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9601 // Handle general 256-bit shuffles
9602 if (VT.is256BitVector())
9603 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9608 // This function assumes its argument is a BUILD_VECTOR of constants or
9609 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9611 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9612 unsigned &MaskValue) {
9614 unsigned NumElems = BuildVector->getNumOperands();
9615 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9616 unsigned NumLanes = (NumElems - 1) / 8 + 1;
9617 unsigned NumElemsInLane = NumElems / NumLanes;
9619 // Blend for v16i16 should be symetric for the both lanes.
9620 for (unsigned i = 0; i < NumElemsInLane; ++i) {
9621 SDValue EltCond = BuildVector->getOperand(i);
9622 SDValue SndLaneEltCond =
9623 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9625 int Lane1Cond = -1, Lane2Cond = -1;
9626 if (isa<ConstantSDNode>(EltCond))
9627 Lane1Cond = !isZero(EltCond);
9628 if (isa<ConstantSDNode>(SndLaneEltCond))
9629 Lane2Cond = !isZero(SndLaneEltCond);
9631 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9632 // Lane1Cond != 0, means we want the first argument.
9633 // Lane1Cond == 0, means we want the second argument.
9634 // The encoding of this argument is 0 for the first argument, 1
9635 // for the second. Therefore, invert the condition.
9636 MaskValue |= !Lane1Cond << i;
9637 else if (Lane1Cond < 0)
9638 MaskValue |= !Lane2Cond << i;
9645 // Try to lower a vselect node into a simple blend instruction.
9646 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9647 SelectionDAG &DAG) {
9648 SDValue Cond = Op.getOperand(0);
9649 SDValue LHS = Op.getOperand(1);
9650 SDValue RHS = Op.getOperand(2);
9652 MVT VT = Op.getSimpleValueType();
9653 MVT EltVT = VT.getVectorElementType();
9654 unsigned NumElems = VT.getVectorNumElements();
9656 // There is no blend with immediate in AVX-512.
9657 if (VT.is512BitVector())
9660 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9662 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9665 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9668 // Check the mask for BLEND and build the value.
9669 unsigned MaskValue = 0;
9670 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9673 // Convert i32 vectors to floating point if it is not AVX2.
9674 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9676 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9677 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9679 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9680 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9683 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9684 DAG.getConstant(MaskValue, MVT::i32));
9685 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9688 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9689 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9690 if (BlendOp.getNode())
9693 // Some types for vselect were previously set to Expand, not Legal or
9694 // Custom. Return an empty SDValue so we fall-through to Expand, after
9695 // the Custom lowering phase.
9696 MVT VT = Op.getSimpleValueType();
9697 switch (VT.SimpleTy) {
9705 // We couldn't create a "Blend with immediate" node.
9706 // This node should still be legal, but we'll have to emit a blendv*
9711 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9712 MVT VT = Op.getSimpleValueType();
9715 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9718 if (VT.getSizeInBits() == 8) {
9719 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9720 Op.getOperand(0), Op.getOperand(1));
9721 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9722 DAG.getValueType(VT));
9723 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9726 if (VT.getSizeInBits() == 16) {
9727 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9728 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9730 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9731 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9732 DAG.getNode(ISD::BITCAST, dl,
9736 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9737 Op.getOperand(0), Op.getOperand(1));
9738 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9739 DAG.getValueType(VT));
9740 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9743 if (VT == MVT::f32) {
9744 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9745 // the result back to FR32 register. It's only worth matching if the
9746 // result has a single use which is a store or a bitcast to i32. And in
9747 // the case of a store, it's not worth it if the index is a constant 0,
9748 // because a MOVSSmr can be used instead, which is smaller and faster.
9749 if (!Op.hasOneUse())
9751 SDNode *User = *Op.getNode()->use_begin();
9752 if ((User->getOpcode() != ISD::STORE ||
9753 (isa<ConstantSDNode>(Op.getOperand(1)) &&
9754 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9755 (User->getOpcode() != ISD::BITCAST ||
9756 User->getValueType(0) != MVT::i32))
9758 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9759 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9762 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9765 if (VT == MVT::i32 || VT == MVT::i64) {
9766 // ExtractPS/pextrq works with constant index.
9767 if (isa<ConstantSDNode>(Op.getOperand(1)))
9773 /// Extract one bit from mask vector, like v16i1 or v8i1.
9774 /// AVX-512 feature.
9776 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9777 SDValue Vec = Op.getOperand(0);
9779 MVT VecVT = Vec.getSimpleValueType();
9780 SDValue Idx = Op.getOperand(1);
9781 MVT EltVT = Op.getSimpleValueType();
9783 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9785 // variable index can't be handled in mask registers,
9786 // extend vector to VR512
9787 if (!isa<ConstantSDNode>(Idx)) {
9788 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9789 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9790 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9791 ExtVT.getVectorElementType(), Ext, Idx);
9792 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9795 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9796 const TargetRegisterClass* rc = getRegClassFor(VecVT);
9797 unsigned MaxSift = rc->getSize()*8 - 1;
9798 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9799 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9800 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9801 DAG.getConstant(MaxSift, MVT::i8));
9802 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9803 DAG.getIntPtrConstant(0));
9807 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9808 SelectionDAG &DAG) const {
9810 SDValue Vec = Op.getOperand(0);
9811 MVT VecVT = Vec.getSimpleValueType();
9812 SDValue Idx = Op.getOperand(1);
9814 if (Op.getSimpleValueType() == MVT::i1)
9815 return ExtractBitFromMaskVector(Op, DAG);
9817 if (!isa<ConstantSDNode>(Idx)) {
9818 if (VecVT.is512BitVector() ||
9819 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9820 VecVT.getVectorElementType().getSizeInBits() == 32)) {
9823 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9824 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9825 MaskEltVT.getSizeInBits());
9827 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9828 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9829 getZeroVector(MaskVT, Subtarget, DAG, dl),
9830 Idx, DAG.getConstant(0, getPointerTy()));
9831 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9832 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9833 Perm, DAG.getConstant(0, getPointerTy()));
9838 // If this is a 256-bit vector result, first extract the 128-bit vector and
9839 // then extract the element from the 128-bit vector.
9840 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9842 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9843 // Get the 128-bit vector.
9844 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9845 MVT EltVT = VecVT.getVectorElementType();
9847 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9849 //if (IdxVal >= NumElems/2)
9850 // IdxVal -= NumElems/2;
9851 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9852 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9853 DAG.getConstant(IdxVal, MVT::i32));
9856 assert(VecVT.is128BitVector() && "Unexpected vector length");
9858 if (Subtarget->hasSSE41()) {
9859 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9864 MVT VT = Op.getSimpleValueType();
9865 // TODO: handle v16i8.
9866 if (VT.getSizeInBits() == 16) {
9867 SDValue Vec = Op.getOperand(0);
9868 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9870 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9871 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9872 DAG.getNode(ISD::BITCAST, dl,
9875 // Transform it so it match pextrw which produces a 32-bit result.
9876 MVT EltVT = MVT::i32;
9877 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9878 Op.getOperand(0), Op.getOperand(1));
9879 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9880 DAG.getValueType(VT));
9881 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9884 if (VT.getSizeInBits() == 32) {
9885 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9889 // SHUFPS the element to the lowest double word, then movss.
9890 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9891 MVT VVT = Op.getOperand(0).getSimpleValueType();
9892 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9893 DAG.getUNDEF(VVT), Mask);
9894 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9895 DAG.getIntPtrConstant(0));
9898 if (VT.getSizeInBits() == 64) {
9899 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9900 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9901 // to match extract_elt for f64.
9902 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9906 // UNPCKHPD the element to the lowest double word, then movsd.
9907 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9908 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9909 int Mask[2] = { 1, -1 };
9910 MVT VVT = Op.getOperand(0).getSimpleValueType();
9911 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9912 DAG.getUNDEF(VVT), Mask);
9913 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9914 DAG.getIntPtrConstant(0));
9920 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9921 MVT VT = Op.getSimpleValueType();
9922 MVT EltVT = VT.getVectorElementType();
9925 SDValue N0 = Op.getOperand(0);
9926 SDValue N1 = Op.getOperand(1);
9927 SDValue N2 = Op.getOperand(2);
9929 if (!VT.is128BitVector())
9932 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9933 isa<ConstantSDNode>(N2)) {
9935 if (VT == MVT::v8i16)
9936 Opc = X86ISD::PINSRW;
9937 else if (VT == MVT::v16i8)
9938 Opc = X86ISD::PINSRB;
9940 Opc = X86ISD::PINSRB;
9942 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9944 if (N1.getValueType() != MVT::i32)
9945 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9946 if (N2.getValueType() != MVT::i32)
9947 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9948 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9951 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9952 // Bits [7:6] of the constant are the source select. This will always be
9953 // zero here. The DAG Combiner may combine an extract_elt index into these
9954 // bits. For example (insert (extract, 3), 2) could be matched by putting
9955 // the '3' into bits [7:6] of X86ISD::INSERTPS.
9956 // Bits [5:4] of the constant are the destination select. This is the
9957 // value of the incoming immediate.
9958 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
9959 // combine either bitwise AND or insert of float 0.0 to set these bits.
9960 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9961 // Create this as a scalar to vector..
9962 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9963 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9966 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9967 // PINSR* works with constant index.
9973 /// Insert one bit to mask vector, like v16i1 or v8i1.
9974 /// AVX-512 feature.
9976 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9978 SDValue Vec = Op.getOperand(0);
9979 SDValue Elt = Op.getOperand(1);
9980 SDValue Idx = Op.getOperand(2);
9981 MVT VecVT = Vec.getSimpleValueType();
9983 if (!isa<ConstantSDNode>(Idx)) {
9984 // Non constant index. Extend source and destination,
9985 // insert element and then truncate the result.
9986 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9987 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
9988 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
9989 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9990 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9991 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
9994 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9995 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
9996 if (Vec.getOpcode() == ISD::UNDEF)
9997 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9998 DAG.getConstant(IdxVal, MVT::i8));
9999 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10000 unsigned MaxSift = rc->getSize()*8 - 1;
10001 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10002 DAG.getConstant(MaxSift, MVT::i8));
10003 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10004 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10005 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10008 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10009 MVT VT = Op.getSimpleValueType();
10010 MVT EltVT = VT.getVectorElementType();
10012 if (EltVT == MVT::i1)
10013 return InsertBitToMaskVector(Op, DAG);
10016 SDValue N0 = Op.getOperand(0);
10017 SDValue N1 = Op.getOperand(1);
10018 SDValue N2 = Op.getOperand(2);
10020 // If this is a 256-bit vector result, first extract the 128-bit vector,
10021 // insert the element into the extracted half and then place it back.
10022 if (VT.is256BitVector() || VT.is512BitVector()) {
10023 if (!isa<ConstantSDNode>(N2))
10026 // Get the desired 128-bit vector half.
10027 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10028 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10030 // Insert the element into the desired half.
10031 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10032 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10034 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10035 DAG.getConstant(IdxIn128, MVT::i32));
10037 // Insert the changed part back to the 256-bit vector
10038 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10041 if (Subtarget->hasSSE41())
10042 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10044 if (EltVT == MVT::i8)
10047 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10048 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10049 // as its second argument.
10050 if (N1.getValueType() != MVT::i32)
10051 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10052 if (N2.getValueType() != MVT::i32)
10053 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10054 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10059 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10061 MVT OpVT = Op.getSimpleValueType();
10063 // If this is a 256-bit vector result, first insert into a 128-bit
10064 // vector and then insert into the 256-bit vector.
10065 if (!OpVT.is128BitVector()) {
10066 // Insert into a 128-bit vector.
10067 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10068 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10069 OpVT.getVectorNumElements() / SizeFactor);
10071 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10073 // Insert the 128-bit vector.
10074 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10077 if (OpVT == MVT::v1i64 &&
10078 Op.getOperand(0).getValueType() == MVT::i64)
10079 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10081 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10082 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10083 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10084 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10087 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10088 // a simple subregister reference or explicit instructions to grab
10089 // upper bits of a vector.
10090 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10091 SelectionDAG &DAG) {
10093 SDValue In = Op.getOperand(0);
10094 SDValue Idx = Op.getOperand(1);
10095 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10096 MVT ResVT = Op.getSimpleValueType();
10097 MVT InVT = In.getSimpleValueType();
10099 if (Subtarget->hasFp256()) {
10100 if (ResVT.is128BitVector() &&
10101 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10102 isa<ConstantSDNode>(Idx)) {
10103 return Extract128BitVector(In, IdxVal, DAG, dl);
10105 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10106 isa<ConstantSDNode>(Idx)) {
10107 return Extract256BitVector(In, IdxVal, DAG, dl);
10113 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10114 // simple superregister reference or explicit instructions to insert
10115 // the upper bits of a vector.
10116 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10117 SelectionDAG &DAG) {
10118 if (Subtarget->hasFp256()) {
10119 SDLoc dl(Op.getNode());
10120 SDValue Vec = Op.getNode()->getOperand(0);
10121 SDValue SubVec = Op.getNode()->getOperand(1);
10122 SDValue Idx = Op.getNode()->getOperand(2);
10124 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10125 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10126 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10127 isa<ConstantSDNode>(Idx)) {
10128 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10129 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10132 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10133 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10134 isa<ConstantSDNode>(Idx)) {
10135 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10136 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10142 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10143 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10144 // one of the above mentioned nodes. It has to be wrapped because otherwise
10145 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10146 // be used to form addressing mode. These wrapped nodes will be selected
10149 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10150 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10152 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10153 // global base reg.
10154 unsigned char OpFlag = 0;
10155 unsigned WrapperKind = X86ISD::Wrapper;
10156 CodeModel::Model M = DAG.getTarget().getCodeModel();
10158 if (Subtarget->isPICStyleRIPRel() &&
10159 (M == CodeModel::Small || M == CodeModel::Kernel))
10160 WrapperKind = X86ISD::WrapperRIP;
10161 else if (Subtarget->isPICStyleGOT())
10162 OpFlag = X86II::MO_GOTOFF;
10163 else if (Subtarget->isPICStyleStubPIC())
10164 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10166 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10167 CP->getAlignment(),
10168 CP->getOffset(), OpFlag);
10170 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10171 // With PIC, the address is actually $g + Offset.
10173 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10174 DAG.getNode(X86ISD::GlobalBaseReg,
10175 SDLoc(), getPointerTy()),
10182 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10183 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10185 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10186 // global base reg.
10187 unsigned char OpFlag = 0;
10188 unsigned WrapperKind = X86ISD::Wrapper;
10189 CodeModel::Model M = DAG.getTarget().getCodeModel();
10191 if (Subtarget->isPICStyleRIPRel() &&
10192 (M == CodeModel::Small || M == CodeModel::Kernel))
10193 WrapperKind = X86ISD::WrapperRIP;
10194 else if (Subtarget->isPICStyleGOT())
10195 OpFlag = X86II::MO_GOTOFF;
10196 else if (Subtarget->isPICStyleStubPIC())
10197 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10199 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10202 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10204 // With PIC, the address is actually $g + Offset.
10206 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10207 DAG.getNode(X86ISD::GlobalBaseReg,
10208 SDLoc(), getPointerTy()),
10215 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10216 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10218 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10219 // global base reg.
10220 unsigned char OpFlag = 0;
10221 unsigned WrapperKind = X86ISD::Wrapper;
10222 CodeModel::Model M = DAG.getTarget().getCodeModel();
10224 if (Subtarget->isPICStyleRIPRel() &&
10225 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10226 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10227 OpFlag = X86II::MO_GOTPCREL;
10228 WrapperKind = X86ISD::WrapperRIP;
10229 } else if (Subtarget->isPICStyleGOT()) {
10230 OpFlag = X86II::MO_GOT;
10231 } else if (Subtarget->isPICStyleStubPIC()) {
10232 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10233 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10234 OpFlag = X86II::MO_DARWIN_NONLAZY;
10237 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10240 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10242 // With PIC, the address is actually $g + Offset.
10243 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10244 !Subtarget->is64Bit()) {
10245 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10246 DAG.getNode(X86ISD::GlobalBaseReg,
10247 SDLoc(), getPointerTy()),
10251 // For symbols that require a load from a stub to get the address, emit the
10253 if (isGlobalStubReference(OpFlag))
10254 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10255 MachinePointerInfo::getGOT(), false, false, false, 0);
10261 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10262 // Create the TargetBlockAddressAddress node.
10263 unsigned char OpFlags =
10264 Subtarget->ClassifyBlockAddressReference();
10265 CodeModel::Model M = DAG.getTarget().getCodeModel();
10266 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10267 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10269 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10272 if (Subtarget->isPICStyleRIPRel() &&
10273 (M == CodeModel::Small || M == CodeModel::Kernel))
10274 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10276 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10278 // With PIC, the address is actually $g + Offset.
10279 if (isGlobalRelativeToPICBase(OpFlags)) {
10280 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10281 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10289 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10290 int64_t Offset, SelectionDAG &DAG) const {
10291 // Create the TargetGlobalAddress node, folding in the constant
10292 // offset if it is legal.
10293 unsigned char OpFlags =
10294 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10295 CodeModel::Model M = DAG.getTarget().getCodeModel();
10297 if (OpFlags == X86II::MO_NO_FLAG &&
10298 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10299 // A direct static reference to a global.
10300 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10303 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10306 if (Subtarget->isPICStyleRIPRel() &&
10307 (M == CodeModel::Small || M == CodeModel::Kernel))
10308 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10310 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10312 // With PIC, the address is actually $g + Offset.
10313 if (isGlobalRelativeToPICBase(OpFlags)) {
10314 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10315 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10319 // For globals that require a load from a stub to get the address, emit the
10321 if (isGlobalStubReference(OpFlags))
10322 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10323 MachinePointerInfo::getGOT(), false, false, false, 0);
10325 // If there was a non-zero offset that we didn't fold, create an explicit
10326 // addition for it.
10328 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10329 DAG.getConstant(Offset, getPointerTy()));
10335 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10336 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10337 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10338 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10342 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10343 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10344 unsigned char OperandFlags, bool LocalDynamic = false) {
10345 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10346 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10348 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10349 GA->getValueType(0),
10353 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10357 SDValue Ops[] = { Chain, TGA, *InFlag };
10358 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10360 SDValue Ops[] = { Chain, TGA };
10361 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10364 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10365 MFI->setAdjustsStack(true);
10367 SDValue Flag = Chain.getValue(1);
10368 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10371 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10373 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10376 SDLoc dl(GA); // ? function entry point might be better
10377 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10378 DAG.getNode(X86ISD::GlobalBaseReg,
10379 SDLoc(), PtrVT), InFlag);
10380 InFlag = Chain.getValue(1);
10382 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10385 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10387 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10389 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10390 X86::RAX, X86II::MO_TLSGD);
10393 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10399 // Get the start address of the TLS block for this module.
10400 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10401 .getInfo<X86MachineFunctionInfo>();
10402 MFI->incNumLocalDynamicTLSAccesses();
10406 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10407 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10410 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10411 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10412 InFlag = Chain.getValue(1);
10413 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10414 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10417 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10421 unsigned char OperandFlags = X86II::MO_DTPOFF;
10422 unsigned WrapperKind = X86ISD::Wrapper;
10423 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10424 GA->getValueType(0),
10425 GA->getOffset(), OperandFlags);
10426 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10428 // Add x@dtpoff with the base.
10429 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10432 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10433 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10434 const EVT PtrVT, TLSModel::Model model,
10435 bool is64Bit, bool isPIC) {
10438 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10439 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10440 is64Bit ? 257 : 256));
10442 SDValue ThreadPointer =
10443 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10444 MachinePointerInfo(Ptr), false, false, false, 0);
10446 unsigned char OperandFlags = 0;
10447 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10449 unsigned WrapperKind = X86ISD::Wrapper;
10450 if (model == TLSModel::LocalExec) {
10451 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10452 } else if (model == TLSModel::InitialExec) {
10454 OperandFlags = X86II::MO_GOTTPOFF;
10455 WrapperKind = X86ISD::WrapperRIP;
10457 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10460 llvm_unreachable("Unexpected model");
10463 // emit "addl x@ntpoff,%eax" (local exec)
10464 // or "addl x@indntpoff,%eax" (initial exec)
10465 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10467 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10468 GA->getOffset(), OperandFlags);
10469 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10471 if (model == TLSModel::InitialExec) {
10472 if (isPIC && !is64Bit) {
10473 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10474 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10478 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10479 MachinePointerInfo::getGOT(), false, false, false, 0);
10482 // The address of the thread local variable is the add of the thread
10483 // pointer with the offset of the variable.
10484 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10488 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10490 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10491 const GlobalValue *GV = GA->getGlobal();
10493 if (Subtarget->isTargetELF()) {
10494 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10497 case TLSModel::GeneralDynamic:
10498 if (Subtarget->is64Bit())
10499 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10500 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10501 case TLSModel::LocalDynamic:
10502 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10503 Subtarget->is64Bit());
10504 case TLSModel::InitialExec:
10505 case TLSModel::LocalExec:
10506 return LowerToTLSExecModel(
10507 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10508 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10510 llvm_unreachable("Unknown TLS model.");
10513 if (Subtarget->isTargetDarwin()) {
10514 // Darwin only has one model of TLS. Lower to that.
10515 unsigned char OpFlag = 0;
10516 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10517 X86ISD::WrapperRIP : X86ISD::Wrapper;
10519 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10520 // global base reg.
10521 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10522 !Subtarget->is64Bit();
10524 OpFlag = X86II::MO_TLVP_PIC_BASE;
10526 OpFlag = X86II::MO_TLVP;
10528 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10529 GA->getValueType(0),
10530 GA->getOffset(), OpFlag);
10531 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10533 // With PIC32, the address is actually $g + Offset.
10535 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10536 DAG.getNode(X86ISD::GlobalBaseReg,
10537 SDLoc(), getPointerTy()),
10540 // Lowering the machine isd will make sure everything is in the right
10542 SDValue Chain = DAG.getEntryNode();
10543 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10544 SDValue Args[] = { Chain, Offset };
10545 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10547 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10548 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10549 MFI->setAdjustsStack(true);
10551 // And our return value (tls address) is in the standard call return value
10553 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10554 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10555 Chain.getValue(1));
10558 if (Subtarget->isTargetKnownWindowsMSVC() ||
10559 Subtarget->isTargetWindowsGNU()) {
10560 // Just use the implicit TLS architecture
10561 // Need to generate someting similar to:
10562 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10564 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
10565 // mov rcx, qword [rdx+rcx*8]
10566 // mov eax, .tls$:tlsvar
10567 // [rax+rcx] contains the address
10568 // Windows 64bit: gs:0x58
10569 // Windows 32bit: fs:__tls_array
10572 SDValue Chain = DAG.getEntryNode();
10574 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10575 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10576 // use its literal value of 0x2C.
10577 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10578 ? Type::getInt8PtrTy(*DAG.getContext(),
10580 : Type::getInt32PtrTy(*DAG.getContext(),
10584 Subtarget->is64Bit()
10585 ? DAG.getIntPtrConstant(0x58)
10586 : (Subtarget->isTargetWindowsGNU()
10587 ? DAG.getIntPtrConstant(0x2C)
10588 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10590 SDValue ThreadPointer =
10591 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10592 MachinePointerInfo(Ptr), false, false, false, 0);
10594 // Load the _tls_index variable
10595 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10596 if (Subtarget->is64Bit())
10597 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10598 IDX, MachinePointerInfo(), MVT::i32,
10601 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10602 false, false, false, 0);
10604 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10606 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10608 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10609 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10610 false, false, false, 0);
10612 // Get the offset of start of .tls section
10613 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10614 GA->getValueType(0),
10615 GA->getOffset(), X86II::MO_SECREL);
10616 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10618 // The address of the thread local variable is the add of the thread
10619 // pointer with the offset of the variable.
10620 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10623 llvm_unreachable("TLS not implemented for this target.");
10626 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10627 /// and take a 2 x i32 value to shift plus a shift amount.
10628 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10629 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10630 MVT VT = Op.getSimpleValueType();
10631 unsigned VTBits = VT.getSizeInBits();
10633 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10634 SDValue ShOpLo = Op.getOperand(0);
10635 SDValue ShOpHi = Op.getOperand(1);
10636 SDValue ShAmt = Op.getOperand(2);
10637 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10638 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10640 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10641 DAG.getConstant(VTBits - 1, MVT::i8));
10642 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10643 DAG.getConstant(VTBits - 1, MVT::i8))
10644 : DAG.getConstant(0, VT);
10646 SDValue Tmp2, Tmp3;
10647 if (Op.getOpcode() == ISD::SHL_PARTS) {
10648 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10649 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10651 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10652 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10655 // If the shift amount is larger or equal than the width of a part we can't
10656 // rely on the results of shld/shrd. Insert a test and select the appropriate
10657 // values for large shift amounts.
10658 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10659 DAG.getConstant(VTBits, MVT::i8));
10660 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10661 AndNode, DAG.getConstant(0, MVT::i8));
10664 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10665 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10666 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10668 if (Op.getOpcode() == ISD::SHL_PARTS) {
10669 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10670 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10672 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10673 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10676 SDValue Ops[2] = { Lo, Hi };
10677 return DAG.getMergeValues(Ops, dl);
10680 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10681 SelectionDAG &DAG) const {
10682 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10684 if (SrcVT.isVector())
10687 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10688 "Unknown SINT_TO_FP to lower!");
10690 // These are really Legal; return the operand so the caller accepts it as
10692 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10694 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10695 Subtarget->is64Bit()) {
10700 unsigned Size = SrcVT.getSizeInBits()/8;
10701 MachineFunction &MF = DAG.getMachineFunction();
10702 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10703 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10704 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10706 MachinePointerInfo::getFixedStack(SSFI),
10708 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10711 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10713 SelectionDAG &DAG) const {
10717 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10719 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10721 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10723 unsigned ByteSize = SrcVT.getSizeInBits()/8;
10725 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10726 MachineMemOperand *MMO;
10728 int SSFI = FI->getIndex();
10730 DAG.getMachineFunction()
10731 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10732 MachineMemOperand::MOLoad, ByteSize, ByteSize);
10734 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10735 StackSlot = StackSlot.getOperand(1);
10737 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10738 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10740 Tys, Ops, SrcVT, MMO);
10743 Chain = Result.getValue(1);
10744 SDValue InFlag = Result.getValue(2);
10746 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10747 // shouldn't be necessary except that RFP cannot be live across
10748 // multiple blocks. When stackifier is fixed, they can be uncoupled.
10749 MachineFunction &MF = DAG.getMachineFunction();
10750 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10751 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10752 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10753 Tys = DAG.getVTList(MVT::Other);
10755 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10757 MachineMemOperand *MMO =
10758 DAG.getMachineFunction()
10759 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10760 MachineMemOperand::MOStore, SSFISize, SSFISize);
10762 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10763 Ops, Op.getValueType(), MMO);
10764 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10765 MachinePointerInfo::getFixedStack(SSFI),
10766 false, false, false, 0);
10772 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10773 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10774 SelectionDAG &DAG) const {
10775 // This algorithm is not obvious. Here it is what we're trying to output:
10778 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10779 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10781 haddpd %xmm0, %xmm0
10783 pshufd $0x4e, %xmm0, %xmm1
10789 LLVMContext *Context = DAG.getContext();
10791 // Build some magic constants.
10792 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10793 Constant *C0 = ConstantDataVector::get(*Context, CV0);
10794 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10796 SmallVector<Constant*,2> CV1;
10798 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10799 APInt(64, 0x4330000000000000ULL))));
10801 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10802 APInt(64, 0x4530000000000000ULL))));
10803 Constant *C1 = ConstantVector::get(CV1);
10804 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10806 // Load the 64-bit value into an XMM register.
10807 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10809 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10810 MachinePointerInfo::getConstantPool(),
10811 false, false, false, 16);
10812 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10813 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10816 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10817 MachinePointerInfo::getConstantPool(),
10818 false, false, false, 16);
10819 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10820 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10823 if (Subtarget->hasSSE3()) {
10824 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10825 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10827 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10828 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10830 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10831 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10835 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10836 DAG.getIntPtrConstant(0));
10839 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10840 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10841 SelectionDAG &DAG) const {
10843 // FP constant to bias correct the final result.
10844 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10847 // Load the 32-bit value into an XMM register.
10848 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10851 // Zero out the upper parts of the register.
10852 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10854 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10855 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10856 DAG.getIntPtrConstant(0));
10858 // Or the load with the bias.
10859 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10860 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10861 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10862 MVT::v2f64, Load)),
10863 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10864 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10865 MVT::v2f64, Bias)));
10866 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10867 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10868 DAG.getIntPtrConstant(0));
10870 // Subtract the bias.
10871 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10873 // Handle final rounding.
10874 EVT DestVT = Op.getValueType();
10876 if (DestVT.bitsLT(MVT::f64))
10877 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10878 DAG.getIntPtrConstant(0));
10879 if (DestVT.bitsGT(MVT::f64))
10880 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10882 // Handle final rounding.
10886 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10887 SelectionDAG &DAG) const {
10888 SDValue N0 = Op.getOperand(0);
10889 MVT SVT = N0.getSimpleValueType();
10892 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10893 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10894 "Custom UINT_TO_FP is not supported!");
10896 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10897 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10898 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10901 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10902 SelectionDAG &DAG) const {
10903 SDValue N0 = Op.getOperand(0);
10906 if (Op.getValueType().isVector())
10907 return lowerUINT_TO_FP_vec(Op, DAG);
10909 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10910 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10911 // the optimization here.
10912 if (DAG.SignBitIsZero(N0))
10913 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10915 MVT SrcVT = N0.getSimpleValueType();
10916 MVT DstVT = Op.getSimpleValueType();
10917 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10918 return LowerUINT_TO_FP_i64(Op, DAG);
10919 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10920 return LowerUINT_TO_FP_i32(Op, DAG);
10921 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10924 // Make a 64-bit buffer, and use it to build an FILD.
10925 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10926 if (SrcVT == MVT::i32) {
10927 SDValue WordOff = DAG.getConstant(4, getPointerTy());
10928 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10929 getPointerTy(), StackSlot, WordOff);
10930 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10931 StackSlot, MachinePointerInfo(),
10933 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10934 OffsetSlot, MachinePointerInfo(),
10936 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10940 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10941 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10942 StackSlot, MachinePointerInfo(),
10944 // For i64 source, we need to add the appropriate power of 2 if the input
10945 // was negative. This is the same as the optimization in
10946 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10947 // we must be careful to do the computation in x87 extended precision, not
10948 // in SSE. (The generic code can't know it's OK to do this, or how to.)
10949 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10950 MachineMemOperand *MMO =
10951 DAG.getMachineFunction()
10952 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10953 MachineMemOperand::MOLoad, 8, 8);
10955 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10956 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10957 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10960 APInt FF(32, 0x5F800000ULL);
10962 // Check whether the sign bit is set.
10963 SDValue SignSet = DAG.getSetCC(dl,
10964 getSetCCResultType(*DAG.getContext(), MVT::i64),
10965 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10968 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10969 SDValue FudgePtr = DAG.getConstantPool(
10970 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10973 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10974 SDValue Zero = DAG.getIntPtrConstant(0);
10975 SDValue Four = DAG.getIntPtrConstant(4);
10976 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10978 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10980 // Load the value out, extending it from f32 to f80.
10981 // FIXME: Avoid the extend by constructing the right constant pool?
10982 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10983 FudgePtr, MachinePointerInfo::getConstantPool(),
10984 MVT::f32, false, false, 4);
10985 // Extend everything to 80 bits to force it to be done on x87.
10986 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10987 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10990 std::pair<SDValue,SDValue>
10991 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
10992 bool IsSigned, bool IsReplace) const {
10995 EVT DstTy = Op.getValueType();
10997 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
10998 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11002 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11003 DstTy.getSimpleVT() >= MVT::i16 &&
11004 "Unknown FP_TO_INT to lower!");
11006 // These are really Legal.
11007 if (DstTy == MVT::i32 &&
11008 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11009 return std::make_pair(SDValue(), SDValue());
11010 if (Subtarget->is64Bit() &&
11011 DstTy == MVT::i64 &&
11012 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11013 return std::make_pair(SDValue(), SDValue());
11015 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11016 // stack slot, or into the FTOL runtime function.
11017 MachineFunction &MF = DAG.getMachineFunction();
11018 unsigned MemSize = DstTy.getSizeInBits()/8;
11019 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11020 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11023 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11024 Opc = X86ISD::WIN_FTOL;
11026 switch (DstTy.getSimpleVT().SimpleTy) {
11027 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11028 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11029 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11030 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11033 SDValue Chain = DAG.getEntryNode();
11034 SDValue Value = Op.getOperand(0);
11035 EVT TheVT = Op.getOperand(0).getValueType();
11036 // FIXME This causes a redundant load/store if the SSE-class value is already
11037 // in memory, such as if it is on the callstack.
11038 if (isScalarFPTypeInSSEReg(TheVT)) {
11039 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11040 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11041 MachinePointerInfo::getFixedStack(SSFI),
11043 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11045 Chain, StackSlot, DAG.getValueType(TheVT)
11048 MachineMemOperand *MMO =
11049 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11050 MachineMemOperand::MOLoad, MemSize, MemSize);
11051 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11052 Chain = Value.getValue(1);
11053 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11054 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11057 MachineMemOperand *MMO =
11058 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11059 MachineMemOperand::MOStore, MemSize, MemSize);
11061 if (Opc != X86ISD::WIN_FTOL) {
11062 // Build the FP_TO_INT*_IN_MEM
11063 SDValue Ops[] = { Chain, Value, StackSlot };
11064 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11066 return std::make_pair(FIST, StackSlot);
11068 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11069 DAG.getVTList(MVT::Other, MVT::Glue),
11071 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11072 MVT::i32, ftol.getValue(1));
11073 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11074 MVT::i32, eax.getValue(2));
11075 SDValue Ops[] = { eax, edx };
11076 SDValue pair = IsReplace
11077 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11078 : DAG.getMergeValues(Ops, DL);
11079 return std::make_pair(pair, SDValue());
11083 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11084 const X86Subtarget *Subtarget) {
11085 MVT VT = Op->getSimpleValueType(0);
11086 SDValue In = Op->getOperand(0);
11087 MVT InVT = In.getSimpleValueType();
11090 // Optimize vectors in AVX mode:
11093 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11094 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11095 // Concat upper and lower parts.
11098 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11099 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11100 // Concat upper and lower parts.
11103 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11104 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11105 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11108 if (Subtarget->hasInt256())
11109 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11111 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11112 SDValue Undef = DAG.getUNDEF(InVT);
11113 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11114 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11115 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11117 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11118 VT.getVectorNumElements()/2);
11120 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11121 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11123 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11126 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11127 SelectionDAG &DAG) {
11128 MVT VT = Op->getSimpleValueType(0);
11129 SDValue In = Op->getOperand(0);
11130 MVT InVT = In.getSimpleValueType();
11132 unsigned int NumElts = VT.getVectorNumElements();
11133 if (NumElts != 8 && NumElts != 16)
11136 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11137 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11139 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11140 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11141 // Now we have only mask extension
11142 assert(InVT.getVectorElementType() == MVT::i1);
11143 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11144 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11145 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11146 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11147 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11148 MachinePointerInfo::getConstantPool(),
11149 false, false, false, Alignment);
11151 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11152 if (VT.is512BitVector())
11154 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11157 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11158 SelectionDAG &DAG) {
11159 if (Subtarget->hasFp256()) {
11160 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11168 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11169 SelectionDAG &DAG) {
11171 MVT VT = Op.getSimpleValueType();
11172 SDValue In = Op.getOperand(0);
11173 MVT SVT = In.getSimpleValueType();
11175 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11176 return LowerZERO_EXTEND_AVX512(Op, DAG);
11178 if (Subtarget->hasFp256()) {
11179 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11184 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11185 VT.getVectorNumElements() != SVT.getVectorNumElements());
11189 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11191 MVT VT = Op.getSimpleValueType();
11192 SDValue In = Op.getOperand(0);
11193 MVT InVT = In.getSimpleValueType();
11195 if (VT == MVT::i1) {
11196 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11197 "Invalid scalar TRUNCATE operation");
11198 if (InVT == MVT::i32)
11200 if (InVT.getSizeInBits() == 64)
11201 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11202 else if (InVT.getSizeInBits() < 32)
11203 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11204 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11206 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11207 "Invalid TRUNCATE operation");
11209 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11210 if (VT.getVectorElementType().getSizeInBits() >=8)
11211 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11213 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11214 unsigned NumElts = InVT.getVectorNumElements();
11215 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11216 if (InVT.getSizeInBits() < 512) {
11217 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11218 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11222 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11223 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11224 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11225 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11226 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11227 MachinePointerInfo::getConstantPool(),
11228 false, false, false, Alignment);
11229 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11230 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11231 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11234 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11235 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11236 if (Subtarget->hasInt256()) {
11237 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11238 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11239 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11241 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11242 DAG.getIntPtrConstant(0));
11245 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11246 DAG.getIntPtrConstant(0));
11247 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11248 DAG.getIntPtrConstant(2));
11249 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11250 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11251 static const int ShufMask[] = {0, 2, 4, 6};
11252 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11255 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11256 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11257 if (Subtarget->hasInt256()) {
11258 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11260 SmallVector<SDValue,32> pshufbMask;
11261 for (unsigned i = 0; i < 2; ++i) {
11262 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11263 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11264 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11265 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11266 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11267 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11268 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11269 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11270 for (unsigned j = 0; j < 8; ++j)
11271 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11273 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11274 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11275 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11277 static const int ShufMask[] = {0, 2, -1, -1};
11278 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11280 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11281 DAG.getIntPtrConstant(0));
11282 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11285 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11286 DAG.getIntPtrConstant(0));
11288 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11289 DAG.getIntPtrConstant(4));
11291 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11292 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11294 // The PSHUFB mask:
11295 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11296 -1, -1, -1, -1, -1, -1, -1, -1};
11298 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11299 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11300 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11302 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11303 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11305 // The MOVLHPS Mask:
11306 static const int ShufMask2[] = {0, 1, 4, 5};
11307 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11308 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11311 // Handle truncation of V256 to V128 using shuffles.
11312 if (!VT.is128BitVector() || !InVT.is256BitVector())
11315 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11317 unsigned NumElems = VT.getVectorNumElements();
11318 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11320 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11321 // Prepare truncation shuffle mask
11322 for (unsigned i = 0; i != NumElems; ++i)
11323 MaskVec[i] = i * 2;
11324 SDValue V = DAG.getVectorShuffle(NVT, DL,
11325 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11326 DAG.getUNDEF(NVT), &MaskVec[0]);
11327 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11328 DAG.getIntPtrConstant(0));
11331 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11332 SelectionDAG &DAG) const {
11333 assert(!Op.getSimpleValueType().isVector());
11335 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11336 /*IsSigned=*/ true, /*IsReplace=*/ false);
11337 SDValue FIST = Vals.first, StackSlot = Vals.second;
11338 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11339 if (!FIST.getNode()) return Op;
11341 if (StackSlot.getNode())
11342 // Load the result.
11343 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11344 FIST, StackSlot, MachinePointerInfo(),
11345 false, false, false, 0);
11347 // The node is the result.
11351 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11352 SelectionDAG &DAG) const {
11353 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11354 /*IsSigned=*/ false, /*IsReplace=*/ false);
11355 SDValue FIST = Vals.first, StackSlot = Vals.second;
11356 assert(FIST.getNode() && "Unexpected failure");
11358 if (StackSlot.getNode())
11359 // Load the result.
11360 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11361 FIST, StackSlot, MachinePointerInfo(),
11362 false, false, false, 0);
11364 // The node is the result.
11368 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11370 MVT VT = Op.getSimpleValueType();
11371 SDValue In = Op.getOperand(0);
11372 MVT SVT = In.getSimpleValueType();
11374 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11376 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11377 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11378 In, DAG.getUNDEF(SVT)));
11381 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11382 LLVMContext *Context = DAG.getContext();
11384 MVT VT = Op.getSimpleValueType();
11386 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11387 if (VT.isVector()) {
11388 EltVT = VT.getVectorElementType();
11389 NumElts = VT.getVectorNumElements();
11392 if (EltVT == MVT::f64)
11393 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11394 APInt(64, ~(1ULL << 63))));
11396 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11397 APInt(32, ~(1U << 31))));
11398 C = ConstantVector::getSplat(NumElts, C);
11399 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11400 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11401 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11402 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11403 MachinePointerInfo::getConstantPool(),
11404 false, false, false, Alignment);
11405 if (VT.isVector()) {
11406 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11407 return DAG.getNode(ISD::BITCAST, dl, VT,
11408 DAG.getNode(ISD::AND, dl, ANDVT,
11409 DAG.getNode(ISD::BITCAST, dl, ANDVT,
11411 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11413 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11416 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11417 LLVMContext *Context = DAG.getContext();
11419 MVT VT = Op.getSimpleValueType();
11421 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11422 if (VT.isVector()) {
11423 EltVT = VT.getVectorElementType();
11424 NumElts = VT.getVectorNumElements();
11427 if (EltVT == MVT::f64)
11428 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11429 APInt(64, 1ULL << 63)));
11431 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11432 APInt(32, 1U << 31)));
11433 C = ConstantVector::getSplat(NumElts, C);
11434 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11435 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11436 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11437 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11438 MachinePointerInfo::getConstantPool(),
11439 false, false, false, Alignment);
11440 if (VT.isVector()) {
11441 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11442 return DAG.getNode(ISD::BITCAST, dl, VT,
11443 DAG.getNode(ISD::XOR, dl, XORVT,
11444 DAG.getNode(ISD::BITCAST, dl, XORVT,
11446 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11449 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11452 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11453 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11454 LLVMContext *Context = DAG.getContext();
11455 SDValue Op0 = Op.getOperand(0);
11456 SDValue Op1 = Op.getOperand(1);
11458 MVT VT = Op.getSimpleValueType();
11459 MVT SrcVT = Op1.getSimpleValueType();
11461 // If second operand is smaller, extend it first.
11462 if (SrcVT.bitsLT(VT)) {
11463 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11466 // And if it is bigger, shrink it first.
11467 if (SrcVT.bitsGT(VT)) {
11468 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11472 // At this point the operands and the result should have the same
11473 // type, and that won't be f80 since that is not custom lowered.
11475 // First get the sign bit of second operand.
11476 SmallVector<Constant*,4> CV;
11477 if (SrcVT == MVT::f64) {
11478 const fltSemantics &Sem = APFloat::IEEEdouble;
11479 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11480 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11482 const fltSemantics &Sem = APFloat::IEEEsingle;
11483 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11484 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11485 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11486 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11488 Constant *C = ConstantVector::get(CV);
11489 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11490 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11491 MachinePointerInfo::getConstantPool(),
11492 false, false, false, 16);
11493 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11495 // Shift sign bit right or left if the two operands have different types.
11496 if (SrcVT.bitsGT(VT)) {
11497 // Op0 is MVT::f32, Op1 is MVT::f64.
11498 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11499 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11500 DAG.getConstant(32, MVT::i32));
11501 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11502 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11503 DAG.getIntPtrConstant(0));
11506 // Clear first operand sign bit.
11508 if (VT == MVT::f64) {
11509 const fltSemantics &Sem = APFloat::IEEEdouble;
11510 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11511 APInt(64, ~(1ULL << 63)))));
11512 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11514 const fltSemantics &Sem = APFloat::IEEEsingle;
11515 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11516 APInt(32, ~(1U << 31)))));
11517 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11518 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11519 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11521 C = ConstantVector::get(CV);
11522 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11523 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11524 MachinePointerInfo::getConstantPool(),
11525 false, false, false, 16);
11526 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11528 // Or the value with the sign bit.
11529 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11532 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11533 SDValue N0 = Op.getOperand(0);
11535 MVT VT = Op.getSimpleValueType();
11537 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11538 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11539 DAG.getConstant(1, VT));
11540 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11543 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11545 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11546 SelectionDAG &DAG) {
11547 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11549 if (!Subtarget->hasSSE41())
11552 if (!Op->hasOneUse())
11555 SDNode *N = Op.getNode();
11558 SmallVector<SDValue, 8> Opnds;
11559 DenseMap<SDValue, unsigned> VecInMap;
11560 SmallVector<SDValue, 8> VecIns;
11561 EVT VT = MVT::Other;
11563 // Recognize a special case where a vector is casted into wide integer to
11565 Opnds.push_back(N->getOperand(0));
11566 Opnds.push_back(N->getOperand(1));
11568 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11569 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11570 // BFS traverse all OR'd operands.
11571 if (I->getOpcode() == ISD::OR) {
11572 Opnds.push_back(I->getOperand(0));
11573 Opnds.push_back(I->getOperand(1));
11574 // Re-evaluate the number of nodes to be traversed.
11575 e += 2; // 2 more nodes (LHS and RHS) are pushed.
11579 // Quit if a non-EXTRACT_VECTOR_ELT
11580 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11583 // Quit if without a constant index.
11584 SDValue Idx = I->getOperand(1);
11585 if (!isa<ConstantSDNode>(Idx))
11588 SDValue ExtractedFromVec = I->getOperand(0);
11589 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11590 if (M == VecInMap.end()) {
11591 VT = ExtractedFromVec.getValueType();
11592 // Quit if not 128/256-bit vector.
11593 if (!VT.is128BitVector() && !VT.is256BitVector())
11595 // Quit if not the same type.
11596 if (VecInMap.begin() != VecInMap.end() &&
11597 VT != VecInMap.begin()->first.getValueType())
11599 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11600 VecIns.push_back(ExtractedFromVec);
11602 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11605 assert((VT.is128BitVector() || VT.is256BitVector()) &&
11606 "Not extracted from 128-/256-bit vector.");
11608 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11610 for (DenseMap<SDValue, unsigned>::const_iterator
11611 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11612 // Quit if not all elements are used.
11613 if (I->second != FullMask)
11617 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11619 // Cast all vectors into TestVT for PTEST.
11620 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11621 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11623 // If more than one full vectors are evaluated, OR them first before PTEST.
11624 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11625 // Each iteration will OR 2 nodes and append the result until there is only
11626 // 1 node left, i.e. the final OR'd value of all vectors.
11627 SDValue LHS = VecIns[Slot];
11628 SDValue RHS = VecIns[Slot + 1];
11629 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11632 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11633 VecIns.back(), VecIns.back());
11636 /// \brief return true if \c Op has a use that doesn't just read flags.
11637 static bool hasNonFlagsUse(SDValue Op) {
11638 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11640 SDNode *User = *UI;
11641 unsigned UOpNo = UI.getOperandNo();
11642 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11643 // Look pass truncate.
11644 UOpNo = User->use_begin().getOperandNo();
11645 User = *User->use_begin();
11648 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11649 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11655 /// Emit nodes that will be selected as "test Op0,Op0", or something
11657 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11658 SelectionDAG &DAG) const {
11659 if (Op.getValueType() == MVT::i1)
11660 // KORTEST instruction should be selected
11661 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11662 DAG.getConstant(0, Op.getValueType()));
11664 // CF and OF aren't always set the way we want. Determine which
11665 // of these we need.
11666 bool NeedCF = false;
11667 bool NeedOF = false;
11670 case X86::COND_A: case X86::COND_AE:
11671 case X86::COND_B: case X86::COND_BE:
11674 case X86::COND_G: case X86::COND_GE:
11675 case X86::COND_L: case X86::COND_LE:
11676 case X86::COND_O: case X86::COND_NO: {
11677 // Check if we really need to set the
11678 // Overflow flag. If NoSignedWrap is present
11679 // that is not actually needed.
11680 switch (Op->getOpcode()) {
11685 const BinaryWithFlagsSDNode *BinNode =
11686 cast<BinaryWithFlagsSDNode>(Op.getNode());
11687 if (BinNode->hasNoSignedWrap())
11697 // See if we can use the EFLAGS value from the operand instead of
11698 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11699 // we prove that the arithmetic won't overflow, we can't use OF or CF.
11700 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11701 // Emit a CMP with 0, which is the TEST pattern.
11702 //if (Op.getValueType() == MVT::i1)
11703 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11704 // DAG.getConstant(0, MVT::i1));
11705 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11706 DAG.getConstant(0, Op.getValueType()));
11708 unsigned Opcode = 0;
11709 unsigned NumOperands = 0;
11711 // Truncate operations may prevent the merge of the SETCC instruction
11712 // and the arithmetic instruction before it. Attempt to truncate the operands
11713 // of the arithmetic instruction and use a reduced bit-width instruction.
11714 bool NeedTruncation = false;
11715 SDValue ArithOp = Op;
11716 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11717 SDValue Arith = Op->getOperand(0);
11718 // Both the trunc and the arithmetic op need to have one user each.
11719 if (Arith->hasOneUse())
11720 switch (Arith.getOpcode()) {
11727 NeedTruncation = true;
11733 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11734 // which may be the result of a CAST. We use the variable 'Op', which is the
11735 // non-casted variable when we check for possible users.
11736 switch (ArithOp.getOpcode()) {
11738 // Due to an isel shortcoming, be conservative if this add is likely to be
11739 // selected as part of a load-modify-store instruction. When the root node
11740 // in a match is a store, isel doesn't know how to remap non-chain non-flag
11741 // uses of other nodes in the match, such as the ADD in this case. This
11742 // leads to the ADD being left around and reselected, with the result being
11743 // two adds in the output. Alas, even if none our users are stores, that
11744 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
11745 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
11746 // climbing the DAG back to the root, and it doesn't seem to be worth the
11748 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11749 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11750 if (UI->getOpcode() != ISD::CopyToReg &&
11751 UI->getOpcode() != ISD::SETCC &&
11752 UI->getOpcode() != ISD::STORE)
11755 if (ConstantSDNode *C =
11756 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11757 // An add of one will be selected as an INC.
11758 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11759 Opcode = X86ISD::INC;
11764 // An add of negative one (subtract of one) will be selected as a DEC.
11765 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11766 Opcode = X86ISD::DEC;
11772 // Otherwise use a regular EFLAGS-setting add.
11773 Opcode = X86ISD::ADD;
11778 // If we have a constant logical shift that's only used in a comparison
11779 // against zero turn it into an equivalent AND. This allows turning it into
11780 // a TEST instruction later.
11781 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11782 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11783 EVT VT = Op.getValueType();
11784 unsigned BitWidth = VT.getSizeInBits();
11785 unsigned ShAmt = Op->getConstantOperandVal(1);
11786 if (ShAmt >= BitWidth) // Avoid undefined shifts.
11788 APInt Mask = ArithOp.getOpcode() == ISD::SRL
11789 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11790 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11791 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11793 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11794 DAG.getConstant(Mask, VT));
11795 DAG.ReplaceAllUsesWith(Op, New);
11801 // If the primary and result isn't used, don't bother using X86ISD::AND,
11802 // because a TEST instruction will be better.
11803 if (!hasNonFlagsUse(Op))
11809 // Due to the ISEL shortcoming noted above, be conservative if this op is
11810 // likely to be selected as part of a load-modify-store instruction.
11811 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11812 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11813 if (UI->getOpcode() == ISD::STORE)
11816 // Otherwise use a regular EFLAGS-setting instruction.
11817 switch (ArithOp.getOpcode()) {
11818 default: llvm_unreachable("unexpected operator!");
11819 case ISD::SUB: Opcode = X86ISD::SUB; break;
11820 case ISD::XOR: Opcode = X86ISD::XOR; break;
11821 case ISD::AND: Opcode = X86ISD::AND; break;
11823 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11824 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11825 if (EFLAGS.getNode())
11828 Opcode = X86ISD::OR;
11842 return SDValue(Op.getNode(), 1);
11848 // If we found that truncation is beneficial, perform the truncation and
11850 if (NeedTruncation) {
11851 EVT VT = Op.getValueType();
11852 SDValue WideVal = Op->getOperand(0);
11853 EVT WideVT = WideVal.getValueType();
11854 unsigned ConvertedOp = 0;
11855 // Use a target machine opcode to prevent further DAGCombine
11856 // optimizations that may separate the arithmetic operations
11857 // from the setcc node.
11858 switch (WideVal.getOpcode()) {
11860 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11861 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11862 case ISD::AND: ConvertedOp = X86ISD::AND; break;
11863 case ISD::OR: ConvertedOp = X86ISD::OR; break;
11864 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11868 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11869 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11870 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11871 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11872 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11878 // Emit a CMP with 0, which is the TEST pattern.
11879 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11880 DAG.getConstant(0, Op.getValueType()));
11882 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11883 SmallVector<SDValue, 4> Ops;
11884 for (unsigned i = 0; i != NumOperands; ++i)
11885 Ops.push_back(Op.getOperand(i));
11887 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11888 DAG.ReplaceAllUsesWith(Op, New);
11889 return SDValue(New.getNode(), 1);
11892 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11894 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11895 SDLoc dl, SelectionDAG &DAG) const {
11896 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11897 if (C->getAPIntValue() == 0)
11898 return EmitTest(Op0, X86CC, dl, DAG);
11900 if (Op0.getValueType() == MVT::i1)
11901 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11904 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11905 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11906 // Do the comparison at i32 if it's smaller, besides the Atom case.
11907 // This avoids subregister aliasing issues. Keep the smaller reference
11908 // if we're optimizing for size, however, as that'll allow better folding
11909 // of memory operations.
11910 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11911 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11912 AttributeSet::FunctionIndex, Attribute::MinSize) &&
11913 !Subtarget->isAtom()) {
11914 unsigned ExtendOp =
11915 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11916 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11917 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11919 // Use SUB instead of CMP to enable CSE between SUB and CMP.
11920 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11921 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11923 return SDValue(Sub.getNode(), 1);
11925 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11928 /// Convert a comparison if required by the subtarget.
11929 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11930 SelectionDAG &DAG) const {
11931 // If the subtarget does not support the FUCOMI instruction, floating-point
11932 // comparisons have to be converted.
11933 if (Subtarget->hasCMov() ||
11934 Cmp.getOpcode() != X86ISD::CMP ||
11935 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11936 !Cmp.getOperand(1).getValueType().isFloatingPoint())
11939 // The instruction selector will select an FUCOM instruction instead of
11940 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11941 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11942 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11944 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11945 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11946 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11947 DAG.getConstant(8, MVT::i8));
11948 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11949 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11952 static bool isAllOnes(SDValue V) {
11953 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11954 return C && C->isAllOnesValue();
11957 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11958 /// if it's possible.
11959 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11960 SDLoc dl, SelectionDAG &DAG) const {
11961 SDValue Op0 = And.getOperand(0);
11962 SDValue Op1 = And.getOperand(1);
11963 if (Op0.getOpcode() == ISD::TRUNCATE)
11964 Op0 = Op0.getOperand(0);
11965 if (Op1.getOpcode() == ISD::TRUNCATE)
11966 Op1 = Op1.getOperand(0);
11969 if (Op1.getOpcode() == ISD::SHL)
11970 std::swap(Op0, Op1);
11971 if (Op0.getOpcode() == ISD::SHL) {
11972 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11973 if (And00C->getZExtValue() == 1) {
11974 // If we looked past a truncate, check that it's only truncating away
11976 unsigned BitWidth = Op0.getValueSizeInBits();
11977 unsigned AndBitWidth = And.getValueSizeInBits();
11978 if (BitWidth > AndBitWidth) {
11980 DAG.computeKnownBits(Op0, Zeros, Ones);
11981 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11985 RHS = Op0.getOperand(1);
11987 } else if (Op1.getOpcode() == ISD::Constant) {
11988 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11989 uint64_t AndRHSVal = AndRHS->getZExtValue();
11990 SDValue AndLHS = Op0;
11992 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
11993 LHS = AndLHS.getOperand(0);
11994 RHS = AndLHS.getOperand(1);
11997 // Use BT if the immediate can't be encoded in a TEST instruction.
11998 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12000 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12004 if (LHS.getNode()) {
12005 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12006 // instruction. Since the shift amount is in-range-or-undefined, we know
12007 // that doing a bittest on the i32 value is ok. We extend to i32 because
12008 // the encoding for the i16 version is larger than the i32 version.
12009 // Also promote i16 to i32 for performance / code size reason.
12010 if (LHS.getValueType() == MVT::i8 ||
12011 LHS.getValueType() == MVT::i16)
12012 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12014 // If the operand types disagree, extend the shift amount to match. Since
12015 // BT ignores high bits (like shifts) we can use anyextend.
12016 if (LHS.getValueType() != RHS.getValueType())
12017 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12019 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12020 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12021 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12022 DAG.getConstant(Cond, MVT::i8), BT);
12028 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12030 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12035 // SSE Condition code mapping:
12044 switch (SetCCOpcode) {
12045 default: llvm_unreachable("Unexpected SETCC condition");
12047 case ISD::SETEQ: SSECC = 0; break;
12049 case ISD::SETGT: Swap = true; // Fallthrough
12051 case ISD::SETOLT: SSECC = 1; break;
12053 case ISD::SETGE: Swap = true; // Fallthrough
12055 case ISD::SETOLE: SSECC = 2; break;
12056 case ISD::SETUO: SSECC = 3; break;
12058 case ISD::SETNE: SSECC = 4; break;
12059 case ISD::SETULE: Swap = true; // Fallthrough
12060 case ISD::SETUGE: SSECC = 5; break;
12061 case ISD::SETULT: Swap = true; // Fallthrough
12062 case ISD::SETUGT: SSECC = 6; break;
12063 case ISD::SETO: SSECC = 7; break;
12065 case ISD::SETONE: SSECC = 8; break;
12068 std::swap(Op0, Op1);
12073 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12074 // ones, and then concatenate the result back.
12075 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12076 MVT VT = Op.getSimpleValueType();
12078 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12079 "Unsupported value type for operation");
12081 unsigned NumElems = VT.getVectorNumElements();
12083 SDValue CC = Op.getOperand(2);
12085 // Extract the LHS vectors
12086 SDValue LHS = Op.getOperand(0);
12087 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12088 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12090 // Extract the RHS vectors
12091 SDValue RHS = Op.getOperand(1);
12092 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12093 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12095 // Issue the operation on the smaller types and concatenate the result back
12096 MVT EltVT = VT.getVectorElementType();
12097 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12098 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12099 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12100 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12103 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12104 const X86Subtarget *Subtarget) {
12105 SDValue Op0 = Op.getOperand(0);
12106 SDValue Op1 = Op.getOperand(1);
12107 SDValue CC = Op.getOperand(2);
12108 MVT VT = Op.getSimpleValueType();
12111 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12112 Op.getValueType().getScalarType() == MVT::i1 &&
12113 "Cannot set masked compare for this operation");
12115 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12117 bool Unsigned = false;
12120 switch (SetCCOpcode) {
12121 default: llvm_unreachable("Unexpected SETCC condition");
12122 case ISD::SETNE: SSECC = 4; break;
12123 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12124 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12125 case ISD::SETLT: Swap = true; //fall-through
12126 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12127 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12128 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12129 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12130 case ISD::SETULE: Unsigned = true; //fall-through
12131 case ISD::SETLE: SSECC = 2; break;
12135 std::swap(Op0, Op1);
12137 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12138 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12139 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12140 DAG.getConstant(SSECC, MVT::i8));
12143 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12144 /// operand \p Op1. If non-trivial (for example because it's not constant)
12145 /// return an empty value.
12146 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12148 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12152 MVT VT = Op1.getSimpleValueType();
12153 MVT EVT = VT.getVectorElementType();
12154 unsigned n = VT.getVectorNumElements();
12155 SmallVector<SDValue, 8> ULTOp1;
12157 for (unsigned i = 0; i < n; ++i) {
12158 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12159 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12162 // Avoid underflow.
12163 APInt Val = Elt->getAPIntValue();
12167 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12170 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12173 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12174 SelectionDAG &DAG) {
12175 SDValue Op0 = Op.getOperand(0);
12176 SDValue Op1 = Op.getOperand(1);
12177 SDValue CC = Op.getOperand(2);
12178 MVT VT = Op.getSimpleValueType();
12179 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12180 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12185 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12186 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12189 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12190 unsigned Opc = X86ISD::CMPP;
12191 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12192 assert(VT.getVectorNumElements() <= 16);
12193 Opc = X86ISD::CMPM;
12195 // In the two special cases we can't handle, emit two comparisons.
12198 unsigned CombineOpc;
12199 if (SetCCOpcode == ISD::SETUEQ) {
12200 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12202 assert(SetCCOpcode == ISD::SETONE);
12203 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12206 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12207 DAG.getConstant(CC0, MVT::i8));
12208 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12209 DAG.getConstant(CC1, MVT::i8));
12210 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12212 // Handle all other FP comparisons here.
12213 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12214 DAG.getConstant(SSECC, MVT::i8));
12217 // Break 256-bit integer vector compare into smaller ones.
12218 if (VT.is256BitVector() && !Subtarget->hasInt256())
12219 return Lower256IntVSETCC(Op, DAG);
12221 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12222 EVT OpVT = Op1.getValueType();
12223 if (Subtarget->hasAVX512()) {
12224 if (Op1.getValueType().is512BitVector() ||
12225 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12226 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12228 // In AVX-512 architecture setcc returns mask with i1 elements,
12229 // But there is no compare instruction for i8 and i16 elements.
12230 // We are not talking about 512-bit operands in this case, these
12231 // types are illegal.
12233 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12234 OpVT.getVectorElementType().getSizeInBits() >= 8))
12235 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12236 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12239 // We are handling one of the integer comparisons here. Since SSE only has
12240 // GT and EQ comparisons for integer, swapping operands and multiple
12241 // operations may be required for some comparisons.
12243 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12244 bool Subus = false;
12246 switch (SetCCOpcode) {
12247 default: llvm_unreachable("Unexpected SETCC condition");
12248 case ISD::SETNE: Invert = true;
12249 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12250 case ISD::SETLT: Swap = true;
12251 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12252 case ISD::SETGE: Swap = true;
12253 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12254 Invert = true; break;
12255 case ISD::SETULT: Swap = true;
12256 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12257 FlipSigns = true; break;
12258 case ISD::SETUGE: Swap = true;
12259 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12260 FlipSigns = true; Invert = true; break;
12263 // Special case: Use min/max operations for SETULE/SETUGE
12264 MVT VET = VT.getVectorElementType();
12266 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12267 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12270 switch (SetCCOpcode) {
12272 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12273 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12276 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12279 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12280 if (!MinMax && hasSubus) {
12281 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12283 // t = psubus Op0, Op1
12284 // pcmpeq t, <0..0>
12285 switch (SetCCOpcode) {
12287 case ISD::SETULT: {
12288 // If the comparison is against a constant we can turn this into a
12289 // setule. With psubus, setule does not require a swap. This is
12290 // beneficial because the constant in the register is no longer
12291 // destructed as the destination so it can be hoisted out of a loop.
12292 // Only do this pre-AVX since vpcmp* is no longer destructive.
12293 if (Subtarget->hasAVX())
12295 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12296 if (ULEOp1.getNode()) {
12298 Subus = true; Invert = false; Swap = false;
12302 // Psubus is better than flip-sign because it requires no inversion.
12303 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
12304 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12308 Opc = X86ISD::SUBUS;
12314 std::swap(Op0, Op1);
12316 // Check that the operation in question is available (most are plain SSE2,
12317 // but PCMPGTQ and PCMPEQQ have different requirements).
12318 if (VT == MVT::v2i64) {
12319 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12320 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12322 // First cast everything to the right type.
12323 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12324 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12326 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12327 // bits of the inputs before performing those operations. The lower
12328 // compare is always unsigned.
12331 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12333 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12334 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12335 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12336 Sign, Zero, Sign, Zero);
12338 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12339 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12341 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12342 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12343 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12345 // Create masks for only the low parts/high parts of the 64 bit integers.
12346 static const int MaskHi[] = { 1, 1, 3, 3 };
12347 static const int MaskLo[] = { 0, 0, 2, 2 };
12348 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12349 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12350 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12352 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12353 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12356 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12358 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12361 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12362 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12363 // pcmpeqd + pshufd + pand.
12364 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12366 // First cast everything to the right type.
12367 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12368 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12371 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12373 // Make sure the lower and upper halves are both all-ones.
12374 static const int Mask[] = { 1, 0, 3, 2 };
12375 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12376 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12379 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12381 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12385 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12386 // bits of the inputs before performing those operations.
12388 EVT EltVT = VT.getVectorElementType();
12389 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12390 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12391 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12394 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12396 // If the logical-not of the result is required, perform that now.
12398 Result = DAG.getNOT(dl, Result, VT);
12401 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12404 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12405 getZeroVector(VT, Subtarget, DAG, dl));
12410 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12412 MVT VT = Op.getSimpleValueType();
12414 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12416 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12417 && "SetCC type must be 8-bit or 1-bit integer");
12418 SDValue Op0 = Op.getOperand(0);
12419 SDValue Op1 = Op.getOperand(1);
12421 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12423 // Optimize to BT if possible.
12424 // Lower (X & (1 << N)) == 0 to BT(X, N).
12425 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12426 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12427 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12428 Op1.getOpcode() == ISD::Constant &&
12429 cast<ConstantSDNode>(Op1)->isNullValue() &&
12430 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12431 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12432 if (NewSetCC.getNode())
12436 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
12438 if (Op1.getOpcode() == ISD::Constant &&
12439 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12440 cast<ConstantSDNode>(Op1)->isNullValue()) &&
12441 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12443 // If the input is a setcc, then reuse the input setcc or use a new one with
12444 // the inverted condition.
12445 if (Op0.getOpcode() == X86ISD::SETCC) {
12446 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12447 bool Invert = (CC == ISD::SETNE) ^
12448 cast<ConstantSDNode>(Op1)->isNullValue();
12452 CCode = X86::GetOppositeBranchCondition(CCode);
12453 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12454 DAG.getConstant(CCode, MVT::i8),
12455 Op0.getOperand(1));
12457 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12461 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12462 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12463 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12465 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12466 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12469 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12470 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12471 if (X86CC == X86::COND_INVALID)
12474 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12475 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12476 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12477 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12479 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12483 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12484 static bool isX86LogicalCmp(SDValue Op) {
12485 unsigned Opc = Op.getNode()->getOpcode();
12486 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12487 Opc == X86ISD::SAHF)
12489 if (Op.getResNo() == 1 &&
12490 (Opc == X86ISD::ADD ||
12491 Opc == X86ISD::SUB ||
12492 Opc == X86ISD::ADC ||
12493 Opc == X86ISD::SBB ||
12494 Opc == X86ISD::SMUL ||
12495 Opc == X86ISD::UMUL ||
12496 Opc == X86ISD::INC ||
12497 Opc == X86ISD::DEC ||
12498 Opc == X86ISD::OR ||
12499 Opc == X86ISD::XOR ||
12500 Opc == X86ISD::AND))
12503 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12509 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12510 if (V.getOpcode() != ISD::TRUNCATE)
12513 SDValue VOp0 = V.getOperand(0);
12514 unsigned InBits = VOp0.getValueSizeInBits();
12515 unsigned Bits = V.getValueSizeInBits();
12516 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12519 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12520 bool addTest = true;
12521 SDValue Cond = Op.getOperand(0);
12522 SDValue Op1 = Op.getOperand(1);
12523 SDValue Op2 = Op.getOperand(2);
12525 EVT VT = Op1.getValueType();
12528 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12529 // are available. Otherwise fp cmovs get lowered into a less efficient branch
12530 // sequence later on.
12531 if (Cond.getOpcode() == ISD::SETCC &&
12532 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12533 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12534 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12535 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12536 int SSECC = translateX86FSETCC(
12537 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12540 if (Subtarget->hasAVX512()) {
12541 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12542 DAG.getConstant(SSECC, MVT::i8));
12543 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12545 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12546 DAG.getConstant(SSECC, MVT::i8));
12547 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12548 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12549 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12553 if (Cond.getOpcode() == ISD::SETCC) {
12554 SDValue NewCond = LowerSETCC(Cond, DAG);
12555 if (NewCond.getNode())
12559 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12560 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12561 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12562 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12563 if (Cond.getOpcode() == X86ISD::SETCC &&
12564 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12565 isZero(Cond.getOperand(1).getOperand(1))) {
12566 SDValue Cmp = Cond.getOperand(1);
12568 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12570 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12571 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12572 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12574 SDValue CmpOp0 = Cmp.getOperand(0);
12575 // Apply further optimizations for special cases
12576 // (select (x != 0), -1, 0) -> neg & sbb
12577 // (select (x == 0), 0, -1) -> neg & sbb
12578 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12579 if (YC->isNullValue() &&
12580 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12581 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12582 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12583 DAG.getConstant(0, CmpOp0.getValueType()),
12585 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12586 DAG.getConstant(X86::COND_B, MVT::i8),
12587 SDValue(Neg.getNode(), 1));
12591 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12592 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12593 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12595 SDValue Res = // Res = 0 or -1.
12596 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12597 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12599 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12600 Res = DAG.getNOT(DL, Res, Res.getValueType());
12602 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12603 if (!N2C || !N2C->isNullValue())
12604 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12609 // Look past (and (setcc_carry (cmp ...)), 1).
12610 if (Cond.getOpcode() == ISD::AND &&
12611 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12612 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12613 if (C && C->getAPIntValue() == 1)
12614 Cond = Cond.getOperand(0);
12617 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12618 // setting operand in place of the X86ISD::SETCC.
12619 unsigned CondOpcode = Cond.getOpcode();
12620 if (CondOpcode == X86ISD::SETCC ||
12621 CondOpcode == X86ISD::SETCC_CARRY) {
12622 CC = Cond.getOperand(0);
12624 SDValue Cmp = Cond.getOperand(1);
12625 unsigned Opc = Cmp.getOpcode();
12626 MVT VT = Op.getSimpleValueType();
12628 bool IllegalFPCMov = false;
12629 if (VT.isFloatingPoint() && !VT.isVector() &&
12630 !isScalarFPTypeInSSEReg(VT)) // FPStack?
12631 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12633 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12634 Opc == X86ISD::BT) { // FIXME
12638 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12639 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12640 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12641 Cond.getOperand(0).getValueType() != MVT::i8)) {
12642 SDValue LHS = Cond.getOperand(0);
12643 SDValue RHS = Cond.getOperand(1);
12644 unsigned X86Opcode;
12647 switch (CondOpcode) {
12648 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12649 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12650 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12651 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12652 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12653 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12654 default: llvm_unreachable("unexpected overflowing operator");
12656 if (CondOpcode == ISD::UMULO)
12657 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12660 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12662 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12664 if (CondOpcode == ISD::UMULO)
12665 Cond = X86Op.getValue(2);
12667 Cond = X86Op.getValue(1);
12669 CC = DAG.getConstant(X86Cond, MVT::i8);
12674 // Look pass the truncate if the high bits are known zero.
12675 if (isTruncWithZeroHighBitsInput(Cond, DAG))
12676 Cond = Cond.getOperand(0);
12678 // We know the result of AND is compared against zero. Try to match
12680 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12681 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12682 if (NewSetCC.getNode()) {
12683 CC = NewSetCC.getOperand(0);
12684 Cond = NewSetCC.getOperand(1);
12691 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12692 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12695 // a < b ? -1 : 0 -> RES = ~setcc_carry
12696 // a < b ? 0 : -1 -> RES = setcc_carry
12697 // a >= b ? -1 : 0 -> RES = setcc_carry
12698 // a >= b ? 0 : -1 -> RES = ~setcc_carry
12699 if (Cond.getOpcode() == X86ISD::SUB) {
12700 Cond = ConvertCmpIfNecessary(Cond, DAG);
12701 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12703 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12704 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12705 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12706 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12707 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12708 return DAG.getNOT(DL, Res, Res.getValueType());
12713 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12714 // widen the cmov and push the truncate through. This avoids introducing a new
12715 // branch during isel and doesn't add any extensions.
12716 if (Op.getValueType() == MVT::i8 &&
12717 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12718 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12719 if (T1.getValueType() == T2.getValueType() &&
12720 // Blacklist CopyFromReg to avoid partial register stalls.
12721 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12722 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12723 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12724 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12728 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12729 // condition is true.
12730 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12731 SDValue Ops[] = { Op2, Op1, CC, Cond };
12732 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12735 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12736 MVT VT = Op->getSimpleValueType(0);
12737 SDValue In = Op->getOperand(0);
12738 MVT InVT = In.getSimpleValueType();
12741 unsigned int NumElts = VT.getVectorNumElements();
12742 if (NumElts != 8 && NumElts != 16)
12745 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12746 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12748 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12749 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12751 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12752 Constant *C = ConstantInt::get(*DAG.getContext(),
12753 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12755 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12756 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12757 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12758 MachinePointerInfo::getConstantPool(),
12759 false, false, false, Alignment);
12760 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12761 if (VT.is512BitVector())
12763 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12766 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12767 SelectionDAG &DAG) {
12768 MVT VT = Op->getSimpleValueType(0);
12769 SDValue In = Op->getOperand(0);
12770 MVT InVT = In.getSimpleValueType();
12773 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12774 return LowerSIGN_EXTEND_AVX512(Op, DAG);
12776 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12777 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12778 (VT != MVT::v16i16 || InVT != MVT::v16i8))
12781 if (Subtarget->hasInt256())
12782 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12784 // Optimize vectors in AVX mode
12785 // Sign extend v8i16 to v8i32 and
12788 // Divide input vector into two parts
12789 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12790 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12791 // concat the vectors to original VT
12793 unsigned NumElems = InVT.getVectorNumElements();
12794 SDValue Undef = DAG.getUNDEF(InVT);
12796 SmallVector<int,8> ShufMask1(NumElems, -1);
12797 for (unsigned i = 0; i != NumElems/2; ++i)
12800 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12802 SmallVector<int,8> ShufMask2(NumElems, -1);
12803 for (unsigned i = 0; i != NumElems/2; ++i)
12804 ShufMask2[i] = i + NumElems/2;
12806 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12808 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12809 VT.getVectorNumElements()/2);
12811 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12812 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12814 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12817 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12818 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12819 // from the AND / OR.
12820 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12821 Opc = Op.getOpcode();
12822 if (Opc != ISD::OR && Opc != ISD::AND)
12824 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12825 Op.getOperand(0).hasOneUse() &&
12826 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12827 Op.getOperand(1).hasOneUse());
12830 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12831 // 1 and that the SETCC node has a single use.
12832 static bool isXor1OfSetCC(SDValue Op) {
12833 if (Op.getOpcode() != ISD::XOR)
12835 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12836 if (N1C && N1C->getAPIntValue() == 1) {
12837 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12838 Op.getOperand(0).hasOneUse();
12843 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12844 bool addTest = true;
12845 SDValue Chain = Op.getOperand(0);
12846 SDValue Cond = Op.getOperand(1);
12847 SDValue Dest = Op.getOperand(2);
12850 bool Inverted = false;
12852 if (Cond.getOpcode() == ISD::SETCC) {
12853 // Check for setcc([su]{add,sub,mul}o == 0).
12854 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12855 isa<ConstantSDNode>(Cond.getOperand(1)) &&
12856 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12857 Cond.getOperand(0).getResNo() == 1 &&
12858 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12859 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12860 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12861 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12862 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12863 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12865 Cond = Cond.getOperand(0);
12867 SDValue NewCond = LowerSETCC(Cond, DAG);
12868 if (NewCond.getNode())
12873 // FIXME: LowerXALUO doesn't handle these!!
12874 else if (Cond.getOpcode() == X86ISD::ADD ||
12875 Cond.getOpcode() == X86ISD::SUB ||
12876 Cond.getOpcode() == X86ISD::SMUL ||
12877 Cond.getOpcode() == X86ISD::UMUL)
12878 Cond = LowerXALUO(Cond, DAG);
12881 // Look pass (and (setcc_carry (cmp ...)), 1).
12882 if (Cond.getOpcode() == ISD::AND &&
12883 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12884 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12885 if (C && C->getAPIntValue() == 1)
12886 Cond = Cond.getOperand(0);
12889 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12890 // setting operand in place of the X86ISD::SETCC.
12891 unsigned CondOpcode = Cond.getOpcode();
12892 if (CondOpcode == X86ISD::SETCC ||
12893 CondOpcode == X86ISD::SETCC_CARRY) {
12894 CC = Cond.getOperand(0);
12896 SDValue Cmp = Cond.getOperand(1);
12897 unsigned Opc = Cmp.getOpcode();
12898 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12899 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12903 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12907 // These can only come from an arithmetic instruction with overflow,
12908 // e.g. SADDO, UADDO.
12909 Cond = Cond.getNode()->getOperand(1);
12915 CondOpcode = Cond.getOpcode();
12916 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12917 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12918 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12919 Cond.getOperand(0).getValueType() != MVT::i8)) {
12920 SDValue LHS = Cond.getOperand(0);
12921 SDValue RHS = Cond.getOperand(1);
12922 unsigned X86Opcode;
12925 // Keep this in sync with LowerXALUO, otherwise we might create redundant
12926 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12928 switch (CondOpcode) {
12929 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12931 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12933 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12936 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12937 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12939 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12941 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12944 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12945 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12946 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12947 default: llvm_unreachable("unexpected overflowing operator");
12950 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12951 if (CondOpcode == ISD::UMULO)
12952 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12955 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12957 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12959 if (CondOpcode == ISD::UMULO)
12960 Cond = X86Op.getValue(2);
12962 Cond = X86Op.getValue(1);
12964 CC = DAG.getConstant(X86Cond, MVT::i8);
12968 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12969 SDValue Cmp = Cond.getOperand(0).getOperand(1);
12970 if (CondOpc == ISD::OR) {
12971 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12972 // two branches instead of an explicit OR instruction with a
12974 if (Cmp == Cond.getOperand(1).getOperand(1) &&
12975 isX86LogicalCmp(Cmp)) {
12976 CC = Cond.getOperand(0).getOperand(0);
12977 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12978 Chain, Dest, CC, Cmp);
12979 CC = Cond.getOperand(1).getOperand(0);
12983 } else { // ISD::AND
12984 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12985 // two branches instead of an explicit AND instruction with a
12986 // separate test. However, we only do this if this block doesn't
12987 // have a fall-through edge, because this requires an explicit
12988 // jmp when the condition is false.
12989 if (Cmp == Cond.getOperand(1).getOperand(1) &&
12990 isX86LogicalCmp(Cmp) &&
12991 Op.getNode()->hasOneUse()) {
12992 X86::CondCode CCode =
12993 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12994 CCode = X86::GetOppositeBranchCondition(CCode);
12995 CC = DAG.getConstant(CCode, MVT::i8);
12996 SDNode *User = *Op.getNode()->use_begin();
12997 // Look for an unconditional branch following this conditional branch.
12998 // We need this because we need to reverse the successors in order
12999 // to implement FCMP_OEQ.
13000 if (User->getOpcode() == ISD::BR) {
13001 SDValue FalseBB = User->getOperand(1);
13003 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13004 assert(NewBR == User);
13008 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13009 Chain, Dest, CC, Cmp);
13010 X86::CondCode CCode =
13011 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13012 CCode = X86::GetOppositeBranchCondition(CCode);
13013 CC = DAG.getConstant(CCode, MVT::i8);
13019 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13020 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13021 // It should be transformed during dag combiner except when the condition
13022 // is set by a arithmetics with overflow node.
13023 X86::CondCode CCode =
13024 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13025 CCode = X86::GetOppositeBranchCondition(CCode);
13026 CC = DAG.getConstant(CCode, MVT::i8);
13027 Cond = Cond.getOperand(0).getOperand(1);
13029 } else if (Cond.getOpcode() == ISD::SETCC &&
13030 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13031 // For FCMP_OEQ, we can emit
13032 // two branches instead of an explicit AND instruction with a
13033 // separate test. However, we only do this if this block doesn't
13034 // have a fall-through edge, because this requires an explicit
13035 // jmp when the condition is false.
13036 if (Op.getNode()->hasOneUse()) {
13037 SDNode *User = *Op.getNode()->use_begin();
13038 // Look for an unconditional branch following this conditional branch.
13039 // We need this because we need to reverse the successors in order
13040 // to implement FCMP_OEQ.
13041 if (User->getOpcode() == ISD::BR) {
13042 SDValue FalseBB = User->getOperand(1);
13044 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13045 assert(NewBR == User);
13049 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13050 Cond.getOperand(0), Cond.getOperand(1));
13051 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13052 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13053 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13054 Chain, Dest, CC, Cmp);
13055 CC = DAG.getConstant(X86::COND_P, MVT::i8);
13060 } else if (Cond.getOpcode() == ISD::SETCC &&
13061 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13062 // For FCMP_UNE, we can emit
13063 // two branches instead of an explicit AND instruction with a
13064 // separate test. However, we only do this if this block doesn't
13065 // have a fall-through edge, because this requires an explicit
13066 // jmp when the condition is false.
13067 if (Op.getNode()->hasOneUse()) {
13068 SDNode *User = *Op.getNode()->use_begin();
13069 // Look for an unconditional branch following this conditional branch.
13070 // We need this because we need to reverse the successors in order
13071 // to implement FCMP_UNE.
13072 if (User->getOpcode() == ISD::BR) {
13073 SDValue FalseBB = User->getOperand(1);
13075 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13076 assert(NewBR == User);
13079 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13080 Cond.getOperand(0), Cond.getOperand(1));
13081 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13082 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13083 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13084 Chain, Dest, CC, Cmp);
13085 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13095 // Look pass the truncate if the high bits are known zero.
13096 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13097 Cond = Cond.getOperand(0);
13099 // We know the result of AND is compared against zero. Try to match
13101 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13102 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13103 if (NewSetCC.getNode()) {
13104 CC = NewSetCC.getOperand(0);
13105 Cond = NewSetCC.getOperand(1);
13112 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13113 CC = DAG.getConstant(X86Cond, MVT::i8);
13114 Cond = EmitTest(Cond, X86Cond, dl, DAG);
13116 Cond = ConvertCmpIfNecessary(Cond, DAG);
13117 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13118 Chain, Dest, CC, Cond);
13121 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13122 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13123 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13124 // that the guard pages used by the OS virtual memory manager are allocated in
13125 // correct sequence.
13127 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13128 SelectionDAG &DAG) const {
13129 MachineFunction &MF = DAG.getMachineFunction();
13130 bool SplitStack = MF.shouldSplitStack();
13131 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13136 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13137 SDNode* Node = Op.getNode();
13139 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13140 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13141 " not tell us which reg is the stack pointer!");
13142 EVT VT = Node->getValueType(0);
13143 SDValue Tmp1 = SDValue(Node, 0);
13144 SDValue Tmp2 = SDValue(Node, 1);
13145 SDValue Tmp3 = Node->getOperand(2);
13146 SDValue Chain = Tmp1.getOperand(0);
13148 // Chain the dynamic stack allocation so that it doesn't modify the stack
13149 // pointer when other instructions are using the stack.
13150 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13153 SDValue Size = Tmp2.getOperand(1);
13154 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13155 Chain = SP.getValue(1);
13156 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13157 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13158 unsigned StackAlign = TFI.getStackAlignment();
13159 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13160 if (Align > StackAlign)
13161 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13162 DAG.getConstant(-(uint64_t)Align, VT));
13163 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13165 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13166 DAG.getIntPtrConstant(0, true), SDValue(),
13169 SDValue Ops[2] = { Tmp1, Tmp2 };
13170 return DAG.getMergeValues(Ops, dl);
13174 SDValue Chain = Op.getOperand(0);
13175 SDValue Size = Op.getOperand(1);
13176 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13177 EVT VT = Op.getNode()->getValueType(0);
13179 bool Is64Bit = Subtarget->is64Bit();
13180 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13183 MachineRegisterInfo &MRI = MF.getRegInfo();
13186 // The 64 bit implementation of segmented stacks needs to clobber both r10
13187 // r11. This makes it impossible to use it along with nested parameters.
13188 const Function *F = MF.getFunction();
13190 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13192 if (I->hasNestAttr())
13193 report_fatal_error("Cannot use segmented stacks with functions that "
13194 "have nested arguments.");
13197 const TargetRegisterClass *AddrRegClass =
13198 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13199 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13200 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13201 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13202 DAG.getRegister(Vreg, SPTy));
13203 SDValue Ops1[2] = { Value, Chain };
13204 return DAG.getMergeValues(Ops1, dl);
13207 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13209 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13210 Flag = Chain.getValue(1);
13211 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13213 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13215 const X86RegisterInfo *RegInfo =
13216 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13217 unsigned SPReg = RegInfo->getStackRegister();
13218 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13219 Chain = SP.getValue(1);
13222 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13223 DAG.getConstant(-(uint64_t)Align, VT));
13224 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13227 SDValue Ops1[2] = { SP, Chain };
13228 return DAG.getMergeValues(Ops1, dl);
13232 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13233 MachineFunction &MF = DAG.getMachineFunction();
13234 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13236 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13239 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13240 // vastart just stores the address of the VarArgsFrameIndex slot into the
13241 // memory location argument.
13242 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13244 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13245 MachinePointerInfo(SV), false, false, 0);
13249 // gp_offset (0 - 6 * 8)
13250 // fp_offset (48 - 48 + 8 * 16)
13251 // overflow_arg_area (point to parameters coming in memory).
13253 SmallVector<SDValue, 8> MemOps;
13254 SDValue FIN = Op.getOperand(1);
13256 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13257 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13259 FIN, MachinePointerInfo(SV), false, false, 0);
13260 MemOps.push_back(Store);
13263 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13264 FIN, DAG.getIntPtrConstant(4));
13265 Store = DAG.getStore(Op.getOperand(0), DL,
13266 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13268 FIN, MachinePointerInfo(SV, 4), false, false, 0);
13269 MemOps.push_back(Store);
13271 // Store ptr to overflow_arg_area
13272 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13273 FIN, DAG.getIntPtrConstant(4));
13274 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13276 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13277 MachinePointerInfo(SV, 8),
13279 MemOps.push_back(Store);
13281 // Store ptr to reg_save_area.
13282 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13283 FIN, DAG.getIntPtrConstant(8));
13284 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13286 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13287 MachinePointerInfo(SV, 16), false, false, 0);
13288 MemOps.push_back(Store);
13289 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13292 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13293 assert(Subtarget->is64Bit() &&
13294 "LowerVAARG only handles 64-bit va_arg!");
13295 assert((Subtarget->isTargetLinux() ||
13296 Subtarget->isTargetDarwin()) &&
13297 "Unhandled target in LowerVAARG");
13298 assert(Op.getNode()->getNumOperands() == 4);
13299 SDValue Chain = Op.getOperand(0);
13300 SDValue SrcPtr = Op.getOperand(1);
13301 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13302 unsigned Align = Op.getConstantOperandVal(3);
13305 EVT ArgVT = Op.getNode()->getValueType(0);
13306 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13307 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13310 // Decide which area this value should be read from.
13311 // TODO: Implement the AMD64 ABI in its entirety. This simple
13312 // selection mechanism works only for the basic types.
13313 if (ArgVT == MVT::f80) {
13314 llvm_unreachable("va_arg for f80 not yet implemented");
13315 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13316 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
13317 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13318 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
13320 llvm_unreachable("Unhandled argument type in LowerVAARG");
13323 if (ArgMode == 2) {
13324 // Sanity Check: Make sure using fp_offset makes sense.
13325 assert(!DAG.getTarget().Options.UseSoftFloat &&
13326 !(DAG.getMachineFunction()
13327 .getFunction()->getAttributes()
13328 .hasAttribute(AttributeSet::FunctionIndex,
13329 Attribute::NoImplicitFloat)) &&
13330 Subtarget->hasSSE1());
13333 // Insert VAARG_64 node into the DAG
13334 // VAARG_64 returns two values: Variable Argument Address, Chain
13335 SmallVector<SDValue, 11> InstOps;
13336 InstOps.push_back(Chain);
13337 InstOps.push_back(SrcPtr);
13338 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13339 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13340 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13341 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13342 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13343 VTs, InstOps, MVT::i64,
13344 MachinePointerInfo(SV),
13346 /*Volatile=*/false,
13348 /*WriteMem=*/true);
13349 Chain = VAARG.getValue(1);
13351 // Load the next argument and return it
13352 return DAG.getLoad(ArgVT, dl,
13355 MachinePointerInfo(),
13356 false, false, false, 0);
13359 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13360 SelectionDAG &DAG) {
13361 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13362 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13363 SDValue Chain = Op.getOperand(0);
13364 SDValue DstPtr = Op.getOperand(1);
13365 SDValue SrcPtr = Op.getOperand(2);
13366 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13367 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13370 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13371 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13373 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13376 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13377 // amount is a constant. Takes immediate version of shift as input.
13378 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13379 SDValue SrcOp, uint64_t ShiftAmt,
13380 SelectionDAG &DAG) {
13381 MVT ElementType = VT.getVectorElementType();
13383 // Fold this packed shift into its first operand if ShiftAmt is 0.
13387 // Check for ShiftAmt >= element width
13388 if (ShiftAmt >= ElementType.getSizeInBits()) {
13389 if (Opc == X86ISD::VSRAI)
13390 ShiftAmt = ElementType.getSizeInBits() - 1;
13392 return DAG.getConstant(0, VT);
13395 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13396 && "Unknown target vector shift-by-constant node");
13398 // Fold this packed vector shift into a build vector if SrcOp is a
13399 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13400 if (VT == SrcOp.getSimpleValueType() &&
13401 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13402 SmallVector<SDValue, 8> Elts;
13403 unsigned NumElts = SrcOp->getNumOperands();
13404 ConstantSDNode *ND;
13407 default: llvm_unreachable(nullptr);
13408 case X86ISD::VSHLI:
13409 for (unsigned i=0; i!=NumElts; ++i) {
13410 SDValue CurrentOp = SrcOp->getOperand(i);
13411 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13412 Elts.push_back(CurrentOp);
13415 ND = cast<ConstantSDNode>(CurrentOp);
13416 const APInt &C = ND->getAPIntValue();
13417 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13420 case X86ISD::VSRLI:
13421 for (unsigned i=0; i!=NumElts; ++i) {
13422 SDValue CurrentOp = SrcOp->getOperand(i);
13423 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13424 Elts.push_back(CurrentOp);
13427 ND = cast<ConstantSDNode>(CurrentOp);
13428 const APInt &C = ND->getAPIntValue();
13429 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13432 case X86ISD::VSRAI:
13433 for (unsigned i=0; i!=NumElts; ++i) {
13434 SDValue CurrentOp = SrcOp->getOperand(i);
13435 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13436 Elts.push_back(CurrentOp);
13439 ND = cast<ConstantSDNode>(CurrentOp);
13440 const APInt &C = ND->getAPIntValue();
13441 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13446 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13449 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13452 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13453 // may or may not be a constant. Takes immediate version of shift as input.
13454 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13455 SDValue SrcOp, SDValue ShAmt,
13456 SelectionDAG &DAG) {
13457 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13459 // Catch shift-by-constant.
13460 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13461 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13462 CShAmt->getZExtValue(), DAG);
13464 // Change opcode to non-immediate version
13466 default: llvm_unreachable("Unknown target vector shift node");
13467 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13468 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13469 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13472 // Need to build a vector containing shift amount
13473 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13476 ShOps[1] = DAG.getConstant(0, MVT::i32);
13477 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13478 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13480 // The return type has to be a 128-bit type with the same element
13481 // type as the input type.
13482 MVT EltVT = VT.getVectorElementType();
13483 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13485 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13486 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13489 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13491 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13493 default: return SDValue(); // Don't custom lower most intrinsics.
13494 // Comparison intrinsics.
13495 case Intrinsic::x86_sse_comieq_ss:
13496 case Intrinsic::x86_sse_comilt_ss:
13497 case Intrinsic::x86_sse_comile_ss:
13498 case Intrinsic::x86_sse_comigt_ss:
13499 case Intrinsic::x86_sse_comige_ss:
13500 case Intrinsic::x86_sse_comineq_ss:
13501 case Intrinsic::x86_sse_ucomieq_ss:
13502 case Intrinsic::x86_sse_ucomilt_ss:
13503 case Intrinsic::x86_sse_ucomile_ss:
13504 case Intrinsic::x86_sse_ucomigt_ss:
13505 case Intrinsic::x86_sse_ucomige_ss:
13506 case Intrinsic::x86_sse_ucomineq_ss:
13507 case Intrinsic::x86_sse2_comieq_sd:
13508 case Intrinsic::x86_sse2_comilt_sd:
13509 case Intrinsic::x86_sse2_comile_sd:
13510 case Intrinsic::x86_sse2_comigt_sd:
13511 case Intrinsic::x86_sse2_comige_sd:
13512 case Intrinsic::x86_sse2_comineq_sd:
13513 case Intrinsic::x86_sse2_ucomieq_sd:
13514 case Intrinsic::x86_sse2_ucomilt_sd:
13515 case Intrinsic::x86_sse2_ucomile_sd:
13516 case Intrinsic::x86_sse2_ucomigt_sd:
13517 case Intrinsic::x86_sse2_ucomige_sd:
13518 case Intrinsic::x86_sse2_ucomineq_sd: {
13522 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13523 case Intrinsic::x86_sse_comieq_ss:
13524 case Intrinsic::x86_sse2_comieq_sd:
13525 Opc = X86ISD::COMI;
13528 case Intrinsic::x86_sse_comilt_ss:
13529 case Intrinsic::x86_sse2_comilt_sd:
13530 Opc = X86ISD::COMI;
13533 case Intrinsic::x86_sse_comile_ss:
13534 case Intrinsic::x86_sse2_comile_sd:
13535 Opc = X86ISD::COMI;
13538 case Intrinsic::x86_sse_comigt_ss:
13539 case Intrinsic::x86_sse2_comigt_sd:
13540 Opc = X86ISD::COMI;
13543 case Intrinsic::x86_sse_comige_ss:
13544 case Intrinsic::x86_sse2_comige_sd:
13545 Opc = X86ISD::COMI;
13548 case Intrinsic::x86_sse_comineq_ss:
13549 case Intrinsic::x86_sse2_comineq_sd:
13550 Opc = X86ISD::COMI;
13553 case Intrinsic::x86_sse_ucomieq_ss:
13554 case Intrinsic::x86_sse2_ucomieq_sd:
13555 Opc = X86ISD::UCOMI;
13558 case Intrinsic::x86_sse_ucomilt_ss:
13559 case Intrinsic::x86_sse2_ucomilt_sd:
13560 Opc = X86ISD::UCOMI;
13563 case Intrinsic::x86_sse_ucomile_ss:
13564 case Intrinsic::x86_sse2_ucomile_sd:
13565 Opc = X86ISD::UCOMI;
13568 case Intrinsic::x86_sse_ucomigt_ss:
13569 case Intrinsic::x86_sse2_ucomigt_sd:
13570 Opc = X86ISD::UCOMI;
13573 case Intrinsic::x86_sse_ucomige_ss:
13574 case Intrinsic::x86_sse2_ucomige_sd:
13575 Opc = X86ISD::UCOMI;
13578 case Intrinsic::x86_sse_ucomineq_ss:
13579 case Intrinsic::x86_sse2_ucomineq_sd:
13580 Opc = X86ISD::UCOMI;
13585 SDValue LHS = Op.getOperand(1);
13586 SDValue RHS = Op.getOperand(2);
13587 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13588 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13589 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13590 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13591 DAG.getConstant(X86CC, MVT::i8), Cond);
13592 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13595 // Arithmetic intrinsics.
13596 case Intrinsic::x86_sse2_pmulu_dq:
13597 case Intrinsic::x86_avx2_pmulu_dq:
13598 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13599 Op.getOperand(1), Op.getOperand(2));
13601 case Intrinsic::x86_sse41_pmuldq:
13602 case Intrinsic::x86_avx2_pmul_dq:
13603 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13604 Op.getOperand(1), Op.getOperand(2));
13606 case Intrinsic::x86_sse2_pmulhu_w:
13607 case Intrinsic::x86_avx2_pmulhu_w:
13608 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13609 Op.getOperand(1), Op.getOperand(2));
13611 case Intrinsic::x86_sse2_pmulh_w:
13612 case Intrinsic::x86_avx2_pmulh_w:
13613 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13614 Op.getOperand(1), Op.getOperand(2));
13616 // SSE2/AVX2 sub with unsigned saturation intrinsics
13617 case Intrinsic::x86_sse2_psubus_b:
13618 case Intrinsic::x86_sse2_psubus_w:
13619 case Intrinsic::x86_avx2_psubus_b:
13620 case Intrinsic::x86_avx2_psubus_w:
13621 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13622 Op.getOperand(1), Op.getOperand(2));
13624 // SSE3/AVX horizontal add/sub intrinsics
13625 case Intrinsic::x86_sse3_hadd_ps:
13626 case Intrinsic::x86_sse3_hadd_pd:
13627 case Intrinsic::x86_avx_hadd_ps_256:
13628 case Intrinsic::x86_avx_hadd_pd_256:
13629 case Intrinsic::x86_sse3_hsub_ps:
13630 case Intrinsic::x86_sse3_hsub_pd:
13631 case Intrinsic::x86_avx_hsub_ps_256:
13632 case Intrinsic::x86_avx_hsub_pd_256:
13633 case Intrinsic::x86_ssse3_phadd_w_128:
13634 case Intrinsic::x86_ssse3_phadd_d_128:
13635 case Intrinsic::x86_avx2_phadd_w:
13636 case Intrinsic::x86_avx2_phadd_d:
13637 case Intrinsic::x86_ssse3_phsub_w_128:
13638 case Intrinsic::x86_ssse3_phsub_d_128:
13639 case Intrinsic::x86_avx2_phsub_w:
13640 case Intrinsic::x86_avx2_phsub_d: {
13643 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13644 case Intrinsic::x86_sse3_hadd_ps:
13645 case Intrinsic::x86_sse3_hadd_pd:
13646 case Intrinsic::x86_avx_hadd_ps_256:
13647 case Intrinsic::x86_avx_hadd_pd_256:
13648 Opcode = X86ISD::FHADD;
13650 case Intrinsic::x86_sse3_hsub_ps:
13651 case Intrinsic::x86_sse3_hsub_pd:
13652 case Intrinsic::x86_avx_hsub_ps_256:
13653 case Intrinsic::x86_avx_hsub_pd_256:
13654 Opcode = X86ISD::FHSUB;
13656 case Intrinsic::x86_ssse3_phadd_w_128:
13657 case Intrinsic::x86_ssse3_phadd_d_128:
13658 case Intrinsic::x86_avx2_phadd_w:
13659 case Intrinsic::x86_avx2_phadd_d:
13660 Opcode = X86ISD::HADD;
13662 case Intrinsic::x86_ssse3_phsub_w_128:
13663 case Intrinsic::x86_ssse3_phsub_d_128:
13664 case Intrinsic::x86_avx2_phsub_w:
13665 case Intrinsic::x86_avx2_phsub_d:
13666 Opcode = X86ISD::HSUB;
13669 return DAG.getNode(Opcode, dl, Op.getValueType(),
13670 Op.getOperand(1), Op.getOperand(2));
13673 // SSE2/SSE41/AVX2 integer max/min intrinsics.
13674 case Intrinsic::x86_sse2_pmaxu_b:
13675 case Intrinsic::x86_sse41_pmaxuw:
13676 case Intrinsic::x86_sse41_pmaxud:
13677 case Intrinsic::x86_avx2_pmaxu_b:
13678 case Intrinsic::x86_avx2_pmaxu_w:
13679 case Intrinsic::x86_avx2_pmaxu_d:
13680 case Intrinsic::x86_sse2_pminu_b:
13681 case Intrinsic::x86_sse41_pminuw:
13682 case Intrinsic::x86_sse41_pminud:
13683 case Intrinsic::x86_avx2_pminu_b:
13684 case Intrinsic::x86_avx2_pminu_w:
13685 case Intrinsic::x86_avx2_pminu_d:
13686 case Intrinsic::x86_sse41_pmaxsb:
13687 case Intrinsic::x86_sse2_pmaxs_w:
13688 case Intrinsic::x86_sse41_pmaxsd:
13689 case Intrinsic::x86_avx2_pmaxs_b:
13690 case Intrinsic::x86_avx2_pmaxs_w:
13691 case Intrinsic::x86_avx2_pmaxs_d:
13692 case Intrinsic::x86_sse41_pminsb:
13693 case Intrinsic::x86_sse2_pmins_w:
13694 case Intrinsic::x86_sse41_pminsd:
13695 case Intrinsic::x86_avx2_pmins_b:
13696 case Intrinsic::x86_avx2_pmins_w:
13697 case Intrinsic::x86_avx2_pmins_d: {
13700 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13701 case Intrinsic::x86_sse2_pmaxu_b:
13702 case Intrinsic::x86_sse41_pmaxuw:
13703 case Intrinsic::x86_sse41_pmaxud:
13704 case Intrinsic::x86_avx2_pmaxu_b:
13705 case Intrinsic::x86_avx2_pmaxu_w:
13706 case Intrinsic::x86_avx2_pmaxu_d:
13707 Opcode = X86ISD::UMAX;
13709 case Intrinsic::x86_sse2_pminu_b:
13710 case Intrinsic::x86_sse41_pminuw:
13711 case Intrinsic::x86_sse41_pminud:
13712 case Intrinsic::x86_avx2_pminu_b:
13713 case Intrinsic::x86_avx2_pminu_w:
13714 case Intrinsic::x86_avx2_pminu_d:
13715 Opcode = X86ISD::UMIN;
13717 case Intrinsic::x86_sse41_pmaxsb:
13718 case Intrinsic::x86_sse2_pmaxs_w:
13719 case Intrinsic::x86_sse41_pmaxsd:
13720 case Intrinsic::x86_avx2_pmaxs_b:
13721 case Intrinsic::x86_avx2_pmaxs_w:
13722 case Intrinsic::x86_avx2_pmaxs_d:
13723 Opcode = X86ISD::SMAX;
13725 case Intrinsic::x86_sse41_pminsb:
13726 case Intrinsic::x86_sse2_pmins_w:
13727 case Intrinsic::x86_sse41_pminsd:
13728 case Intrinsic::x86_avx2_pmins_b:
13729 case Intrinsic::x86_avx2_pmins_w:
13730 case Intrinsic::x86_avx2_pmins_d:
13731 Opcode = X86ISD::SMIN;
13734 return DAG.getNode(Opcode, dl, Op.getValueType(),
13735 Op.getOperand(1), Op.getOperand(2));
13738 // SSE/SSE2/AVX floating point max/min intrinsics.
13739 case Intrinsic::x86_sse_max_ps:
13740 case Intrinsic::x86_sse2_max_pd:
13741 case Intrinsic::x86_avx_max_ps_256:
13742 case Intrinsic::x86_avx_max_pd_256:
13743 case Intrinsic::x86_sse_min_ps:
13744 case Intrinsic::x86_sse2_min_pd:
13745 case Intrinsic::x86_avx_min_ps_256:
13746 case Intrinsic::x86_avx_min_pd_256: {
13749 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13750 case Intrinsic::x86_sse_max_ps:
13751 case Intrinsic::x86_sse2_max_pd:
13752 case Intrinsic::x86_avx_max_ps_256:
13753 case Intrinsic::x86_avx_max_pd_256:
13754 Opcode = X86ISD::FMAX;
13756 case Intrinsic::x86_sse_min_ps:
13757 case Intrinsic::x86_sse2_min_pd:
13758 case Intrinsic::x86_avx_min_ps_256:
13759 case Intrinsic::x86_avx_min_pd_256:
13760 Opcode = X86ISD::FMIN;
13763 return DAG.getNode(Opcode, dl, Op.getValueType(),
13764 Op.getOperand(1), Op.getOperand(2));
13767 // AVX2 variable shift intrinsics
13768 case Intrinsic::x86_avx2_psllv_d:
13769 case Intrinsic::x86_avx2_psllv_q:
13770 case Intrinsic::x86_avx2_psllv_d_256:
13771 case Intrinsic::x86_avx2_psllv_q_256:
13772 case Intrinsic::x86_avx2_psrlv_d:
13773 case Intrinsic::x86_avx2_psrlv_q:
13774 case Intrinsic::x86_avx2_psrlv_d_256:
13775 case Intrinsic::x86_avx2_psrlv_q_256:
13776 case Intrinsic::x86_avx2_psrav_d:
13777 case Intrinsic::x86_avx2_psrav_d_256: {
13780 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13781 case Intrinsic::x86_avx2_psllv_d:
13782 case Intrinsic::x86_avx2_psllv_q:
13783 case Intrinsic::x86_avx2_psllv_d_256:
13784 case Intrinsic::x86_avx2_psllv_q_256:
13787 case Intrinsic::x86_avx2_psrlv_d:
13788 case Intrinsic::x86_avx2_psrlv_q:
13789 case Intrinsic::x86_avx2_psrlv_d_256:
13790 case Intrinsic::x86_avx2_psrlv_q_256:
13793 case Intrinsic::x86_avx2_psrav_d:
13794 case Intrinsic::x86_avx2_psrav_d_256:
13798 return DAG.getNode(Opcode, dl, Op.getValueType(),
13799 Op.getOperand(1), Op.getOperand(2));
13802 case Intrinsic::x86_sse2_packssdw_128:
13803 case Intrinsic::x86_sse2_packsswb_128:
13804 case Intrinsic::x86_avx2_packssdw:
13805 case Intrinsic::x86_avx2_packsswb:
13806 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13807 Op.getOperand(1), Op.getOperand(2));
13809 case Intrinsic::x86_sse2_packuswb_128:
13810 case Intrinsic::x86_sse41_packusdw:
13811 case Intrinsic::x86_avx2_packuswb:
13812 case Intrinsic::x86_avx2_packusdw:
13813 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13814 Op.getOperand(1), Op.getOperand(2));
13816 case Intrinsic::x86_ssse3_pshuf_b_128:
13817 case Intrinsic::x86_avx2_pshuf_b:
13818 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13819 Op.getOperand(1), Op.getOperand(2));
13821 case Intrinsic::x86_sse2_pshuf_d:
13822 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13823 Op.getOperand(1), Op.getOperand(2));
13825 case Intrinsic::x86_sse2_pshufl_w:
13826 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13827 Op.getOperand(1), Op.getOperand(2));
13829 case Intrinsic::x86_sse2_pshufh_w:
13830 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13831 Op.getOperand(1), Op.getOperand(2));
13833 case Intrinsic::x86_ssse3_psign_b_128:
13834 case Intrinsic::x86_ssse3_psign_w_128:
13835 case Intrinsic::x86_ssse3_psign_d_128:
13836 case Intrinsic::x86_avx2_psign_b:
13837 case Intrinsic::x86_avx2_psign_w:
13838 case Intrinsic::x86_avx2_psign_d:
13839 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13840 Op.getOperand(1), Op.getOperand(2));
13842 case Intrinsic::x86_sse41_insertps:
13843 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13844 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13846 case Intrinsic::x86_avx_vperm2f128_ps_256:
13847 case Intrinsic::x86_avx_vperm2f128_pd_256:
13848 case Intrinsic::x86_avx_vperm2f128_si_256:
13849 case Intrinsic::x86_avx2_vperm2i128:
13850 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13851 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13853 case Intrinsic::x86_avx2_permd:
13854 case Intrinsic::x86_avx2_permps:
13855 // Operands intentionally swapped. Mask is last operand to intrinsic,
13856 // but second operand for node/instruction.
13857 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13858 Op.getOperand(2), Op.getOperand(1));
13860 case Intrinsic::x86_sse_sqrt_ps:
13861 case Intrinsic::x86_sse2_sqrt_pd:
13862 case Intrinsic::x86_avx_sqrt_ps_256:
13863 case Intrinsic::x86_avx_sqrt_pd_256:
13864 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13866 // ptest and testp intrinsics. The intrinsic these come from are designed to
13867 // return an integer value, not just an instruction so lower it to the ptest
13868 // or testp pattern and a setcc for the result.
13869 case Intrinsic::x86_sse41_ptestz:
13870 case Intrinsic::x86_sse41_ptestc:
13871 case Intrinsic::x86_sse41_ptestnzc:
13872 case Intrinsic::x86_avx_ptestz_256:
13873 case Intrinsic::x86_avx_ptestc_256:
13874 case Intrinsic::x86_avx_ptestnzc_256:
13875 case Intrinsic::x86_avx_vtestz_ps:
13876 case Intrinsic::x86_avx_vtestc_ps:
13877 case Intrinsic::x86_avx_vtestnzc_ps:
13878 case Intrinsic::x86_avx_vtestz_pd:
13879 case Intrinsic::x86_avx_vtestc_pd:
13880 case Intrinsic::x86_avx_vtestnzc_pd:
13881 case Intrinsic::x86_avx_vtestz_ps_256:
13882 case Intrinsic::x86_avx_vtestc_ps_256:
13883 case Intrinsic::x86_avx_vtestnzc_ps_256:
13884 case Intrinsic::x86_avx_vtestz_pd_256:
13885 case Intrinsic::x86_avx_vtestc_pd_256:
13886 case Intrinsic::x86_avx_vtestnzc_pd_256: {
13887 bool IsTestPacked = false;
13890 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13891 case Intrinsic::x86_avx_vtestz_ps:
13892 case Intrinsic::x86_avx_vtestz_pd:
13893 case Intrinsic::x86_avx_vtestz_ps_256:
13894 case Intrinsic::x86_avx_vtestz_pd_256:
13895 IsTestPacked = true; // Fallthrough
13896 case Intrinsic::x86_sse41_ptestz:
13897 case Intrinsic::x86_avx_ptestz_256:
13899 X86CC = X86::COND_E;
13901 case Intrinsic::x86_avx_vtestc_ps:
13902 case Intrinsic::x86_avx_vtestc_pd:
13903 case Intrinsic::x86_avx_vtestc_ps_256:
13904 case Intrinsic::x86_avx_vtestc_pd_256:
13905 IsTestPacked = true; // Fallthrough
13906 case Intrinsic::x86_sse41_ptestc:
13907 case Intrinsic::x86_avx_ptestc_256:
13909 X86CC = X86::COND_B;
13911 case Intrinsic::x86_avx_vtestnzc_ps:
13912 case Intrinsic::x86_avx_vtestnzc_pd:
13913 case Intrinsic::x86_avx_vtestnzc_ps_256:
13914 case Intrinsic::x86_avx_vtestnzc_pd_256:
13915 IsTestPacked = true; // Fallthrough
13916 case Intrinsic::x86_sse41_ptestnzc:
13917 case Intrinsic::x86_avx_ptestnzc_256:
13919 X86CC = X86::COND_A;
13923 SDValue LHS = Op.getOperand(1);
13924 SDValue RHS = Op.getOperand(2);
13925 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13926 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13927 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13928 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13929 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13931 case Intrinsic::x86_avx512_kortestz_w:
13932 case Intrinsic::x86_avx512_kortestc_w: {
13933 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13934 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13935 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13936 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13937 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13938 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13939 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13942 // SSE/AVX shift intrinsics
13943 case Intrinsic::x86_sse2_psll_w:
13944 case Intrinsic::x86_sse2_psll_d:
13945 case Intrinsic::x86_sse2_psll_q:
13946 case Intrinsic::x86_avx2_psll_w:
13947 case Intrinsic::x86_avx2_psll_d:
13948 case Intrinsic::x86_avx2_psll_q:
13949 case Intrinsic::x86_sse2_psrl_w:
13950 case Intrinsic::x86_sse2_psrl_d:
13951 case Intrinsic::x86_sse2_psrl_q:
13952 case Intrinsic::x86_avx2_psrl_w:
13953 case Intrinsic::x86_avx2_psrl_d:
13954 case Intrinsic::x86_avx2_psrl_q:
13955 case Intrinsic::x86_sse2_psra_w:
13956 case Intrinsic::x86_sse2_psra_d:
13957 case Intrinsic::x86_avx2_psra_w:
13958 case Intrinsic::x86_avx2_psra_d: {
13961 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13962 case Intrinsic::x86_sse2_psll_w:
13963 case Intrinsic::x86_sse2_psll_d:
13964 case Intrinsic::x86_sse2_psll_q:
13965 case Intrinsic::x86_avx2_psll_w:
13966 case Intrinsic::x86_avx2_psll_d:
13967 case Intrinsic::x86_avx2_psll_q:
13968 Opcode = X86ISD::VSHL;
13970 case Intrinsic::x86_sse2_psrl_w:
13971 case Intrinsic::x86_sse2_psrl_d:
13972 case Intrinsic::x86_sse2_psrl_q:
13973 case Intrinsic::x86_avx2_psrl_w:
13974 case Intrinsic::x86_avx2_psrl_d:
13975 case Intrinsic::x86_avx2_psrl_q:
13976 Opcode = X86ISD::VSRL;
13978 case Intrinsic::x86_sse2_psra_w:
13979 case Intrinsic::x86_sse2_psra_d:
13980 case Intrinsic::x86_avx2_psra_w:
13981 case Intrinsic::x86_avx2_psra_d:
13982 Opcode = X86ISD::VSRA;
13985 return DAG.getNode(Opcode, dl, Op.getValueType(),
13986 Op.getOperand(1), Op.getOperand(2));
13989 // SSE/AVX immediate shift intrinsics
13990 case Intrinsic::x86_sse2_pslli_w:
13991 case Intrinsic::x86_sse2_pslli_d:
13992 case Intrinsic::x86_sse2_pslli_q:
13993 case Intrinsic::x86_avx2_pslli_w:
13994 case Intrinsic::x86_avx2_pslli_d:
13995 case Intrinsic::x86_avx2_pslli_q:
13996 case Intrinsic::x86_sse2_psrli_w:
13997 case Intrinsic::x86_sse2_psrli_d:
13998 case Intrinsic::x86_sse2_psrli_q:
13999 case Intrinsic::x86_avx2_psrli_w:
14000 case Intrinsic::x86_avx2_psrli_d:
14001 case Intrinsic::x86_avx2_psrli_q:
14002 case Intrinsic::x86_sse2_psrai_w:
14003 case Intrinsic::x86_sse2_psrai_d:
14004 case Intrinsic::x86_avx2_psrai_w:
14005 case Intrinsic::x86_avx2_psrai_d: {
14008 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14009 case Intrinsic::x86_sse2_pslli_w:
14010 case Intrinsic::x86_sse2_pslli_d:
14011 case Intrinsic::x86_sse2_pslli_q:
14012 case Intrinsic::x86_avx2_pslli_w:
14013 case Intrinsic::x86_avx2_pslli_d:
14014 case Intrinsic::x86_avx2_pslli_q:
14015 Opcode = X86ISD::VSHLI;
14017 case Intrinsic::x86_sse2_psrli_w:
14018 case Intrinsic::x86_sse2_psrli_d:
14019 case Intrinsic::x86_sse2_psrli_q:
14020 case Intrinsic::x86_avx2_psrli_w:
14021 case Intrinsic::x86_avx2_psrli_d:
14022 case Intrinsic::x86_avx2_psrli_q:
14023 Opcode = X86ISD::VSRLI;
14025 case Intrinsic::x86_sse2_psrai_w:
14026 case Intrinsic::x86_sse2_psrai_d:
14027 case Intrinsic::x86_avx2_psrai_w:
14028 case Intrinsic::x86_avx2_psrai_d:
14029 Opcode = X86ISD::VSRAI;
14032 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14033 Op.getOperand(1), Op.getOperand(2), DAG);
14036 case Intrinsic::x86_sse42_pcmpistria128:
14037 case Intrinsic::x86_sse42_pcmpestria128:
14038 case Intrinsic::x86_sse42_pcmpistric128:
14039 case Intrinsic::x86_sse42_pcmpestric128:
14040 case Intrinsic::x86_sse42_pcmpistrio128:
14041 case Intrinsic::x86_sse42_pcmpestrio128:
14042 case Intrinsic::x86_sse42_pcmpistris128:
14043 case Intrinsic::x86_sse42_pcmpestris128:
14044 case Intrinsic::x86_sse42_pcmpistriz128:
14045 case Intrinsic::x86_sse42_pcmpestriz128: {
14049 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14050 case Intrinsic::x86_sse42_pcmpistria128:
14051 Opcode = X86ISD::PCMPISTRI;
14052 X86CC = X86::COND_A;
14054 case Intrinsic::x86_sse42_pcmpestria128:
14055 Opcode = X86ISD::PCMPESTRI;
14056 X86CC = X86::COND_A;
14058 case Intrinsic::x86_sse42_pcmpistric128:
14059 Opcode = X86ISD::PCMPISTRI;
14060 X86CC = X86::COND_B;
14062 case Intrinsic::x86_sse42_pcmpestric128:
14063 Opcode = X86ISD::PCMPESTRI;
14064 X86CC = X86::COND_B;
14066 case Intrinsic::x86_sse42_pcmpistrio128:
14067 Opcode = X86ISD::PCMPISTRI;
14068 X86CC = X86::COND_O;
14070 case Intrinsic::x86_sse42_pcmpestrio128:
14071 Opcode = X86ISD::PCMPESTRI;
14072 X86CC = X86::COND_O;
14074 case Intrinsic::x86_sse42_pcmpistris128:
14075 Opcode = X86ISD::PCMPISTRI;
14076 X86CC = X86::COND_S;
14078 case Intrinsic::x86_sse42_pcmpestris128:
14079 Opcode = X86ISD::PCMPESTRI;
14080 X86CC = X86::COND_S;
14082 case Intrinsic::x86_sse42_pcmpistriz128:
14083 Opcode = X86ISD::PCMPISTRI;
14084 X86CC = X86::COND_E;
14086 case Intrinsic::x86_sse42_pcmpestriz128:
14087 Opcode = X86ISD::PCMPESTRI;
14088 X86CC = X86::COND_E;
14091 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14092 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14093 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14094 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14095 DAG.getConstant(X86CC, MVT::i8),
14096 SDValue(PCMP.getNode(), 1));
14097 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14100 case Intrinsic::x86_sse42_pcmpistri128:
14101 case Intrinsic::x86_sse42_pcmpestri128: {
14103 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14104 Opcode = X86ISD::PCMPISTRI;
14106 Opcode = X86ISD::PCMPESTRI;
14108 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14109 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14110 return DAG.getNode(Opcode, dl, VTs, NewOps);
14112 case Intrinsic::x86_fma_vfmadd_ps:
14113 case Intrinsic::x86_fma_vfmadd_pd:
14114 case Intrinsic::x86_fma_vfmsub_ps:
14115 case Intrinsic::x86_fma_vfmsub_pd:
14116 case Intrinsic::x86_fma_vfnmadd_ps:
14117 case Intrinsic::x86_fma_vfnmadd_pd:
14118 case Intrinsic::x86_fma_vfnmsub_ps:
14119 case Intrinsic::x86_fma_vfnmsub_pd:
14120 case Intrinsic::x86_fma_vfmaddsub_ps:
14121 case Intrinsic::x86_fma_vfmaddsub_pd:
14122 case Intrinsic::x86_fma_vfmsubadd_ps:
14123 case Intrinsic::x86_fma_vfmsubadd_pd:
14124 case Intrinsic::x86_fma_vfmadd_ps_256:
14125 case Intrinsic::x86_fma_vfmadd_pd_256:
14126 case Intrinsic::x86_fma_vfmsub_ps_256:
14127 case Intrinsic::x86_fma_vfmsub_pd_256:
14128 case Intrinsic::x86_fma_vfnmadd_ps_256:
14129 case Intrinsic::x86_fma_vfnmadd_pd_256:
14130 case Intrinsic::x86_fma_vfnmsub_ps_256:
14131 case Intrinsic::x86_fma_vfnmsub_pd_256:
14132 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14133 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14134 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14135 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14136 case Intrinsic::x86_fma_vfmadd_ps_512:
14137 case Intrinsic::x86_fma_vfmadd_pd_512:
14138 case Intrinsic::x86_fma_vfmsub_ps_512:
14139 case Intrinsic::x86_fma_vfmsub_pd_512:
14140 case Intrinsic::x86_fma_vfnmadd_ps_512:
14141 case Intrinsic::x86_fma_vfnmadd_pd_512:
14142 case Intrinsic::x86_fma_vfnmsub_ps_512:
14143 case Intrinsic::x86_fma_vfnmsub_pd_512:
14144 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14145 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14146 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14147 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14150 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14151 case Intrinsic::x86_fma_vfmadd_ps:
14152 case Intrinsic::x86_fma_vfmadd_pd:
14153 case Intrinsic::x86_fma_vfmadd_ps_256:
14154 case Intrinsic::x86_fma_vfmadd_pd_256:
14155 case Intrinsic::x86_fma_vfmadd_ps_512:
14156 case Intrinsic::x86_fma_vfmadd_pd_512:
14157 Opc = X86ISD::FMADD;
14159 case Intrinsic::x86_fma_vfmsub_ps:
14160 case Intrinsic::x86_fma_vfmsub_pd:
14161 case Intrinsic::x86_fma_vfmsub_ps_256:
14162 case Intrinsic::x86_fma_vfmsub_pd_256:
14163 case Intrinsic::x86_fma_vfmsub_ps_512:
14164 case Intrinsic::x86_fma_vfmsub_pd_512:
14165 Opc = X86ISD::FMSUB;
14167 case Intrinsic::x86_fma_vfnmadd_ps:
14168 case Intrinsic::x86_fma_vfnmadd_pd:
14169 case Intrinsic::x86_fma_vfnmadd_ps_256:
14170 case Intrinsic::x86_fma_vfnmadd_pd_256:
14171 case Intrinsic::x86_fma_vfnmadd_ps_512:
14172 case Intrinsic::x86_fma_vfnmadd_pd_512:
14173 Opc = X86ISD::FNMADD;
14175 case Intrinsic::x86_fma_vfnmsub_ps:
14176 case Intrinsic::x86_fma_vfnmsub_pd:
14177 case Intrinsic::x86_fma_vfnmsub_ps_256:
14178 case Intrinsic::x86_fma_vfnmsub_pd_256:
14179 case Intrinsic::x86_fma_vfnmsub_ps_512:
14180 case Intrinsic::x86_fma_vfnmsub_pd_512:
14181 Opc = X86ISD::FNMSUB;
14183 case Intrinsic::x86_fma_vfmaddsub_ps:
14184 case Intrinsic::x86_fma_vfmaddsub_pd:
14185 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14186 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14187 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14188 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14189 Opc = X86ISD::FMADDSUB;
14191 case Intrinsic::x86_fma_vfmsubadd_ps:
14192 case Intrinsic::x86_fma_vfmsubadd_pd:
14193 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14194 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14195 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14196 case Intrinsic::x86_fma_vfmsubadd_pd_512:
14197 Opc = X86ISD::FMSUBADD;
14201 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14202 Op.getOperand(2), Op.getOperand(3));
14207 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14208 SDValue Src, SDValue Mask, SDValue Base,
14209 SDValue Index, SDValue ScaleOp, SDValue Chain,
14210 const X86Subtarget * Subtarget) {
14212 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14213 assert(C && "Invalid scale type");
14214 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14215 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14216 Index.getSimpleValueType().getVectorNumElements());
14218 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14220 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14222 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14223 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14224 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14225 SDValue Segment = DAG.getRegister(0, MVT::i32);
14226 if (Src.getOpcode() == ISD::UNDEF)
14227 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14228 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14229 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14230 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14231 return DAG.getMergeValues(RetOps, dl);
14234 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14235 SDValue Src, SDValue Mask, SDValue Base,
14236 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14238 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14239 assert(C && "Invalid scale type");
14240 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14241 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14242 SDValue Segment = DAG.getRegister(0, MVT::i32);
14243 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14244 Index.getSimpleValueType().getVectorNumElements());
14246 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14248 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14250 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14251 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14252 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14253 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14254 return SDValue(Res, 1);
14257 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14258 SDValue Mask, SDValue Base, SDValue Index,
14259 SDValue ScaleOp, SDValue Chain) {
14261 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14262 assert(C && "Invalid scale type");
14263 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14264 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14265 SDValue Segment = DAG.getRegister(0, MVT::i32);
14267 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14269 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14271 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14273 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14274 //SDVTList VTs = DAG.getVTList(MVT::Other);
14275 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14276 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14277 return SDValue(Res, 0);
14280 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14281 // read performance monitor counters (x86_rdpmc).
14282 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14283 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14284 SmallVectorImpl<SDValue> &Results) {
14285 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14286 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14289 // The ECX register is used to select the index of the performance counter
14291 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14293 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14295 // Reads the content of a 64-bit performance counter and returns it in the
14296 // registers EDX:EAX.
14297 if (Subtarget->is64Bit()) {
14298 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14299 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14302 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14303 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14306 Chain = HI.getValue(1);
14308 if (Subtarget->is64Bit()) {
14309 // The EAX register is loaded with the low-order 32 bits. The EDX register
14310 // is loaded with the supported high-order bits of the counter.
14311 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14312 DAG.getConstant(32, MVT::i8));
14313 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14314 Results.push_back(Chain);
14318 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14319 SDValue Ops[] = { LO, HI };
14320 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14321 Results.push_back(Pair);
14322 Results.push_back(Chain);
14325 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14326 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14327 // also used to custom lower READCYCLECOUNTER nodes.
14328 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14329 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14330 SmallVectorImpl<SDValue> &Results) {
14331 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14332 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14335 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14336 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14337 // and the EAX register is loaded with the low-order 32 bits.
14338 if (Subtarget->is64Bit()) {
14339 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14340 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14343 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14344 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14347 SDValue Chain = HI.getValue(1);
14349 if (Opcode == X86ISD::RDTSCP_DAG) {
14350 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14352 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14353 // the ECX register. Add 'ecx' explicitly to the chain.
14354 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14356 // Explicitly store the content of ECX at the location passed in input
14357 // to the 'rdtscp' intrinsic.
14358 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14359 MachinePointerInfo(), false, false, 0);
14362 if (Subtarget->is64Bit()) {
14363 // The EDX register is loaded with the high-order 32 bits of the MSR, and
14364 // the EAX register is loaded with the low-order 32 bits.
14365 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14366 DAG.getConstant(32, MVT::i8));
14367 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14368 Results.push_back(Chain);
14372 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14373 SDValue Ops[] = { LO, HI };
14374 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14375 Results.push_back(Pair);
14376 Results.push_back(Chain);
14379 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14380 SelectionDAG &DAG) {
14381 SmallVector<SDValue, 2> Results;
14383 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14385 return DAG.getMergeValues(Results, DL);
14388 enum IntrinsicType {
14389 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14392 struct IntrinsicData {
14393 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14394 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14395 IntrinsicType Type;
14400 std::map < unsigned, IntrinsicData> IntrMap;
14401 static void InitIntinsicsMap() {
14402 static bool Initialized = false;
14405 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14406 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14407 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14408 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14409 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14410 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14411 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14412 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14413 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14414 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14415 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
14416 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14417 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
14418 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14419 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
14420 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14421 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
14422 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14424 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14425 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14426 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
14427 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14428 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
14429 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14430 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
14431 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14432 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
14433 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14434 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
14435 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14436 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
14437 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14438 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
14439 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14441 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
14442 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14443 X86::VGATHERPF1QPSm)));
14444 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
14445 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14446 X86::VGATHERPF1QPDm)));
14447 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
14448 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14449 X86::VGATHERPF1DPDm)));
14450 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
14451 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14452 X86::VGATHERPF1DPSm)));
14453 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
14454 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14455 X86::VSCATTERPF1QPSm)));
14456 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
14457 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14458 X86::VSCATTERPF1QPDm)));
14459 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
14460 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14461 X86::VSCATTERPF1DPDm)));
14462 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
14463 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14464 X86::VSCATTERPF1DPSm)));
14465 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14466 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14467 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14468 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14469 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14470 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14471 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14472 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14473 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14474 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14475 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14476 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14477 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14478 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
14479 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14480 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
14481 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14482 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
14483 IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14484 IntrinsicData(RDPMC, X86ISD::RDPMC_DAG, 0)));
14485 Initialized = true;
14488 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14489 SelectionDAG &DAG) {
14490 InitIntinsicsMap();
14491 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14492 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14493 if (itr == IntrMap.end())
14497 IntrinsicData Intr = itr->second;
14498 switch(Intr.Type) {
14501 // Emit the node with the right value type.
14502 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14503 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14505 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14506 // Otherwise return the value from Rand, which is always 0, casted to i32.
14507 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14508 DAG.getConstant(1, Op->getValueType(1)),
14509 DAG.getConstant(X86::COND_B, MVT::i32),
14510 SDValue(Result.getNode(), 1) };
14511 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14512 DAG.getVTList(Op->getValueType(1), MVT::Glue),
14515 // Return { result, isValid, chain }.
14516 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14517 SDValue(Result.getNode(), 2));
14520 //gather(v1, mask, index, base, scale);
14521 SDValue Chain = Op.getOperand(0);
14522 SDValue Src = Op.getOperand(2);
14523 SDValue Base = Op.getOperand(3);
14524 SDValue Index = Op.getOperand(4);
14525 SDValue Mask = Op.getOperand(5);
14526 SDValue Scale = Op.getOperand(6);
14527 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14531 //scatter(base, mask, index, v1, scale);
14532 SDValue Chain = Op.getOperand(0);
14533 SDValue Base = Op.getOperand(2);
14534 SDValue Mask = Op.getOperand(3);
14535 SDValue Index = Op.getOperand(4);
14536 SDValue Src = Op.getOperand(5);
14537 SDValue Scale = Op.getOperand(6);
14538 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14541 SDValue Hint = Op.getOperand(6);
14543 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14544 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14545 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14546 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14547 SDValue Chain = Op.getOperand(0);
14548 SDValue Mask = Op.getOperand(2);
14549 SDValue Index = Op.getOperand(3);
14550 SDValue Base = Op.getOperand(4);
14551 SDValue Scale = Op.getOperand(5);
14552 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14554 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14556 SmallVector<SDValue, 2> Results;
14557 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14558 return DAG.getMergeValues(Results, dl);
14560 // Read Performance Monitoring Counters.
14562 SmallVector<SDValue, 2> Results;
14563 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14564 return DAG.getMergeValues(Results, dl);
14566 // XTEST intrinsics.
14568 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14569 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14570 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14571 DAG.getConstant(X86::COND_NE, MVT::i8),
14573 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14574 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14575 Ret, SDValue(InTrans.getNode(), 1));
14578 llvm_unreachable("Unknown Intrinsic Type");
14581 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14582 SelectionDAG &DAG) const {
14583 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14584 MFI->setReturnAddressIsTaken(true);
14586 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14589 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14591 EVT PtrVT = getPointerTy();
14594 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14595 const X86RegisterInfo *RegInfo =
14596 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14597 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14598 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14599 DAG.getNode(ISD::ADD, dl, PtrVT,
14600 FrameAddr, Offset),
14601 MachinePointerInfo(), false, false, false, 0);
14604 // Just load the return address.
14605 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14606 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14607 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14610 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14611 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14612 MFI->setFrameAddressIsTaken(true);
14614 EVT VT = Op.getValueType();
14615 SDLoc dl(Op); // FIXME probably not meaningful
14616 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14617 const X86RegisterInfo *RegInfo =
14618 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14619 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14620 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14621 (FrameReg == X86::EBP && VT == MVT::i32)) &&
14622 "Invalid Frame Register!");
14623 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14625 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14626 MachinePointerInfo(),
14627 false, false, false, 0);
14631 // FIXME? Maybe this could be a TableGen attribute on some registers and
14632 // this table could be generated automatically from RegInfo.
14633 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14635 unsigned Reg = StringSwitch<unsigned>(RegName)
14636 .Case("esp", X86::ESP)
14637 .Case("rsp", X86::RSP)
14641 report_fatal_error("Invalid register name global variable");
14644 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14645 SelectionDAG &DAG) const {
14646 const X86RegisterInfo *RegInfo =
14647 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14648 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14651 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14652 SDValue Chain = Op.getOperand(0);
14653 SDValue Offset = Op.getOperand(1);
14654 SDValue Handler = Op.getOperand(2);
14657 EVT PtrVT = getPointerTy();
14658 const X86RegisterInfo *RegInfo =
14659 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14660 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14661 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14662 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14663 "Invalid Frame Register!");
14664 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14665 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14667 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14668 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14669 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14670 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14672 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14674 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14675 DAG.getRegister(StoreAddrReg, PtrVT));
14678 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14679 SelectionDAG &DAG) const {
14681 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14682 DAG.getVTList(MVT::i32, MVT::Other),
14683 Op.getOperand(0), Op.getOperand(1));
14686 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14687 SelectionDAG &DAG) const {
14689 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14690 Op.getOperand(0), Op.getOperand(1));
14693 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14694 return Op.getOperand(0);
14697 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14698 SelectionDAG &DAG) const {
14699 SDValue Root = Op.getOperand(0);
14700 SDValue Trmp = Op.getOperand(1); // trampoline
14701 SDValue FPtr = Op.getOperand(2); // nested function
14702 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14705 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14706 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14708 if (Subtarget->is64Bit()) {
14709 SDValue OutChains[6];
14711 // Large code-model.
14712 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
14713 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14715 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14716 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14718 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14720 // Load the pointer to the nested function into R11.
14721 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14722 SDValue Addr = Trmp;
14723 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14724 Addr, MachinePointerInfo(TrmpAddr),
14727 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14728 DAG.getConstant(2, MVT::i64));
14729 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14730 MachinePointerInfo(TrmpAddr, 2),
14733 // Load the 'nest' parameter value into R10.
14734 // R10 is specified in X86CallingConv.td
14735 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14736 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14737 DAG.getConstant(10, MVT::i64));
14738 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14739 Addr, MachinePointerInfo(TrmpAddr, 10),
14742 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14743 DAG.getConstant(12, MVT::i64));
14744 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14745 MachinePointerInfo(TrmpAddr, 12),
14748 // Jump to the nested function.
14749 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14750 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14751 DAG.getConstant(20, MVT::i64));
14752 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14753 Addr, MachinePointerInfo(TrmpAddr, 20),
14756 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14757 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14758 DAG.getConstant(22, MVT::i64));
14759 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14760 MachinePointerInfo(TrmpAddr, 22),
14763 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14765 const Function *Func =
14766 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14767 CallingConv::ID CC = Func->getCallingConv();
14772 llvm_unreachable("Unsupported calling convention");
14773 case CallingConv::C:
14774 case CallingConv::X86_StdCall: {
14775 // Pass 'nest' parameter in ECX.
14776 // Must be kept in sync with X86CallingConv.td
14777 NestReg = X86::ECX;
14779 // Check that ECX wasn't needed by an 'inreg' parameter.
14780 FunctionType *FTy = Func->getFunctionType();
14781 const AttributeSet &Attrs = Func->getAttributes();
14783 if (!Attrs.isEmpty() && !Func->isVarArg()) {
14784 unsigned InRegCount = 0;
14787 for (FunctionType::param_iterator I = FTy->param_begin(),
14788 E = FTy->param_end(); I != E; ++I, ++Idx)
14789 if (Attrs.hasAttribute(Idx, Attribute::InReg))
14790 // FIXME: should only count parameters that are lowered to integers.
14791 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14793 if (InRegCount > 2) {
14794 report_fatal_error("Nest register in use - reduce number of inreg"
14800 case CallingConv::X86_FastCall:
14801 case CallingConv::X86_ThisCall:
14802 case CallingConv::Fast:
14803 // Pass 'nest' parameter in EAX.
14804 // Must be kept in sync with X86CallingConv.td
14805 NestReg = X86::EAX;
14809 SDValue OutChains[4];
14810 SDValue Addr, Disp;
14812 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14813 DAG.getConstant(10, MVT::i32));
14814 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14816 // This is storing the opcode for MOV32ri.
14817 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14818 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14819 OutChains[0] = DAG.getStore(Root, dl,
14820 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14821 Trmp, MachinePointerInfo(TrmpAddr),
14824 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14825 DAG.getConstant(1, MVT::i32));
14826 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14827 MachinePointerInfo(TrmpAddr, 1),
14830 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14831 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14832 DAG.getConstant(5, MVT::i32));
14833 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14834 MachinePointerInfo(TrmpAddr, 5),
14837 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14838 DAG.getConstant(6, MVT::i32));
14839 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14840 MachinePointerInfo(TrmpAddr, 6),
14843 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14847 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14848 SelectionDAG &DAG) const {
14850 The rounding mode is in bits 11:10 of FPSR, and has the following
14852 00 Round to nearest
14857 FLT_ROUNDS, on the other hand, expects the following:
14864 To perform the conversion, we do:
14865 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14868 MachineFunction &MF = DAG.getMachineFunction();
14869 const TargetMachine &TM = MF.getTarget();
14870 const TargetFrameLowering &TFI = *TM.getFrameLowering();
14871 unsigned StackAlignment = TFI.getStackAlignment();
14872 MVT VT = Op.getSimpleValueType();
14875 // Save FP Control Word to stack slot
14876 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14877 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14879 MachineMemOperand *MMO =
14880 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14881 MachineMemOperand::MOStore, 2, 2);
14883 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14884 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14885 DAG.getVTList(MVT::Other),
14886 Ops, MVT::i16, MMO);
14888 // Load FP Control Word from stack slot
14889 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14890 MachinePointerInfo(), false, false, false, 0);
14892 // Transform as necessary
14894 DAG.getNode(ISD::SRL, DL, MVT::i16,
14895 DAG.getNode(ISD::AND, DL, MVT::i16,
14896 CWD, DAG.getConstant(0x800, MVT::i16)),
14897 DAG.getConstant(11, MVT::i8));
14899 DAG.getNode(ISD::SRL, DL, MVT::i16,
14900 DAG.getNode(ISD::AND, DL, MVT::i16,
14901 CWD, DAG.getConstant(0x400, MVT::i16)),
14902 DAG.getConstant(9, MVT::i8));
14905 DAG.getNode(ISD::AND, DL, MVT::i16,
14906 DAG.getNode(ISD::ADD, DL, MVT::i16,
14907 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14908 DAG.getConstant(1, MVT::i16)),
14909 DAG.getConstant(3, MVT::i16));
14911 return DAG.getNode((VT.getSizeInBits() < 16 ?
14912 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14915 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14916 MVT VT = Op.getSimpleValueType();
14918 unsigned NumBits = VT.getSizeInBits();
14921 Op = Op.getOperand(0);
14922 if (VT == MVT::i8) {
14923 // Zero extend to i32 since there is not an i8 bsr.
14925 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14928 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14929 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14930 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14932 // If src is zero (i.e. bsr sets ZF), returns NumBits.
14935 DAG.getConstant(NumBits+NumBits-1, OpVT),
14936 DAG.getConstant(X86::COND_E, MVT::i8),
14939 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14941 // Finally xor with NumBits-1.
14942 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14945 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14949 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14950 MVT VT = Op.getSimpleValueType();
14952 unsigned NumBits = VT.getSizeInBits();
14955 Op = Op.getOperand(0);
14956 if (VT == MVT::i8) {
14957 // Zero extend to i32 since there is not an i8 bsr.
14959 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14962 // Issue a bsr (scan bits in reverse).
14963 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14964 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14966 // And xor with NumBits-1.
14967 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14970 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14974 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14975 MVT VT = Op.getSimpleValueType();
14976 unsigned NumBits = VT.getSizeInBits();
14978 Op = Op.getOperand(0);
14980 // Issue a bsf (scan bits forward) which also sets EFLAGS.
14981 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14982 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14984 // If src is zero (i.e. bsf sets ZF), returns NumBits.
14987 DAG.getConstant(NumBits, VT),
14988 DAG.getConstant(X86::COND_E, MVT::i8),
14991 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
14994 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
14995 // ones, and then concatenate the result back.
14996 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
14997 MVT VT = Op.getSimpleValueType();
14999 assert(VT.is256BitVector() && VT.isInteger() &&
15000 "Unsupported value type for operation");
15002 unsigned NumElems = VT.getVectorNumElements();
15005 // Extract the LHS vectors
15006 SDValue LHS = Op.getOperand(0);
15007 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15008 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15010 // Extract the RHS vectors
15011 SDValue RHS = Op.getOperand(1);
15012 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15013 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15015 MVT EltVT = VT.getVectorElementType();
15016 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15018 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15019 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15020 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15023 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15024 assert(Op.getSimpleValueType().is256BitVector() &&
15025 Op.getSimpleValueType().isInteger() &&
15026 "Only handle AVX 256-bit vector integer operation");
15027 return Lower256IntArith(Op, DAG);
15030 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15031 assert(Op.getSimpleValueType().is256BitVector() &&
15032 Op.getSimpleValueType().isInteger() &&
15033 "Only handle AVX 256-bit vector integer operation");
15034 return Lower256IntArith(Op, DAG);
15037 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15038 SelectionDAG &DAG) {
15040 MVT VT = Op.getSimpleValueType();
15042 // Decompose 256-bit ops into smaller 128-bit ops.
15043 if (VT.is256BitVector() && !Subtarget->hasInt256())
15044 return Lower256IntArith(Op, DAG);
15046 SDValue A = Op.getOperand(0);
15047 SDValue B = Op.getOperand(1);
15049 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15050 if (VT == MVT::v4i32) {
15051 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15052 "Should not custom lower when pmuldq is available!");
15054 // Extract the odd parts.
15055 static const int UnpackMask[] = { 1, -1, 3, -1 };
15056 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15057 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15059 // Multiply the even parts.
15060 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15061 // Now multiply odd parts.
15062 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15064 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15065 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15067 // Merge the two vectors back together with a shuffle. This expands into 2
15069 static const int ShufMask[] = { 0, 4, 2, 6 };
15070 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15073 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15074 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15076 // Ahi = psrlqi(a, 32);
15077 // Bhi = psrlqi(b, 32);
15079 // AloBlo = pmuludq(a, b);
15080 // AloBhi = pmuludq(a, Bhi);
15081 // AhiBlo = pmuludq(Ahi, b);
15083 // AloBhi = psllqi(AloBhi, 32);
15084 // AhiBlo = psllqi(AhiBlo, 32);
15085 // return AloBlo + AloBhi + AhiBlo;
15087 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15088 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15090 // Bit cast to 32-bit vectors for MULUDQ
15091 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15092 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15093 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15094 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15095 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15096 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15098 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15099 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15100 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15102 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15103 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15105 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15106 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15109 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15110 assert(Subtarget->isTargetWin64() && "Unexpected target");
15111 EVT VT = Op.getValueType();
15112 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15113 "Unexpected return type for lowering");
15117 switch (Op->getOpcode()) {
15118 default: llvm_unreachable("Unexpected request for libcall!");
15119 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15120 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15121 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15122 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15123 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15124 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15128 SDValue InChain = DAG.getEntryNode();
15130 TargetLowering::ArgListTy Args;
15131 TargetLowering::ArgListEntry Entry;
15132 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15133 EVT ArgVT = Op->getOperand(i).getValueType();
15134 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15135 "Unexpected argument type for lowering");
15136 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15137 Entry.Node = StackPtr;
15138 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15140 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15141 Entry.Ty = PointerType::get(ArgTy,0);
15142 Entry.isSExt = false;
15143 Entry.isZExt = false;
15144 Args.push_back(Entry);
15147 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15150 TargetLowering::CallLoweringInfo CLI(DAG);
15151 CLI.setDebugLoc(dl).setChain(InChain)
15152 .setCallee(getLibcallCallingConv(LC),
15153 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15154 Callee, std::move(Args), 0)
15155 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15157 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15158 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15161 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15162 SelectionDAG &DAG) {
15163 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15164 EVT VT = Op0.getValueType();
15167 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15168 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15170 // PMULxD operations multiply each even value (starting at 0) of LHS with
15171 // the related value of RHS and produce a widen result.
15172 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15173 // => <2 x i64> <ae|cg>
15175 // In other word, to have all the results, we need to perform two PMULxD:
15176 // 1. one with the even values.
15177 // 2. one with the odd values.
15178 // To achieve #2, with need to place the odd values at an even position.
15180 // Place the odd value at an even position (basically, shift all values 1
15181 // step to the left):
15182 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15183 // <a|b|c|d> => <b|undef|d|undef>
15184 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15185 // <e|f|g|h> => <f|undef|h|undef>
15186 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15188 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15190 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15191 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15193 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15194 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15195 // => <2 x i64> <ae|cg>
15196 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15197 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15198 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15199 // => <2 x i64> <bf|dh>
15200 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15201 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15203 // Shuffle it back into the right order.
15204 // The internal representation is big endian.
15205 // In other words, a i64 bitcasted to 2 x i32 has its high part at index 0
15206 // and its low part at index 1.
15207 // Moreover, we have: Mul1 = <ae|cg> ; Mul2 = <bf|dh>
15208 // Vector index 0 1 ; 2 3
15209 // We want <ae|bf|cg|dh>
15210 // Vector index 0 2 1 3
15211 // Since each element is seen as 2 x i32, we get:
15212 // high_mask[i] = 2 x vector_index[i]
15213 // low_mask[i] = 2 x vector_index[i] + 1
15214 // where vector_index = {0, Size/2, 1, Size/2 + 1, ...,
15215 // Size/2 - 1, Size/2 + Size/2 - 1}
15216 // where Size is the number of element of the final vector.
15217 SDValue Highs, Lows;
15218 if (VT == MVT::v8i32) {
15219 const int HighMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15220 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15221 const int LowMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15222 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15224 const int HighMask[] = {0, 4, 2, 6};
15225 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15226 const int LowMask[] = {1, 5, 3, 7};
15227 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15230 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15231 // unsigned multiply.
15232 if (IsSigned && !Subtarget->hasSSE41()) {
15234 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15235 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15236 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15237 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15238 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15240 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15241 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15244 // The low part of a MUL_LOHI is supposed to be the first value and the
15245 // high part the second value.
15246 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Lows, Highs);
15249 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15250 const X86Subtarget *Subtarget) {
15251 MVT VT = Op.getSimpleValueType();
15253 SDValue R = Op.getOperand(0);
15254 SDValue Amt = Op.getOperand(1);
15256 // Optimize shl/srl/sra with constant shift amount.
15257 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15258 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15259 uint64_t ShiftAmt = ShiftConst->getZExtValue();
15261 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15262 (Subtarget->hasInt256() &&
15263 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15264 (Subtarget->hasAVX512() &&
15265 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15266 if (Op.getOpcode() == ISD::SHL)
15267 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15269 if (Op.getOpcode() == ISD::SRL)
15270 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15272 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15273 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15277 if (VT == MVT::v16i8) {
15278 if (Op.getOpcode() == ISD::SHL) {
15279 // Make a large shift.
15280 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15281 MVT::v8i16, R, ShiftAmt,
15283 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15284 // Zero out the rightmost bits.
15285 SmallVector<SDValue, 16> V(16,
15286 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15288 return DAG.getNode(ISD::AND, dl, VT, SHL,
15289 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15291 if (Op.getOpcode() == ISD::SRL) {
15292 // Make a large shift.
15293 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15294 MVT::v8i16, R, ShiftAmt,
15296 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15297 // Zero out the leftmost bits.
15298 SmallVector<SDValue, 16> V(16,
15299 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15301 return DAG.getNode(ISD::AND, dl, VT, SRL,
15302 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15304 if (Op.getOpcode() == ISD::SRA) {
15305 if (ShiftAmt == 7) {
15306 // R s>> 7 === R s< 0
15307 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15308 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15311 // R s>> a === ((R u>> a) ^ m) - m
15312 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15313 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15315 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15316 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15317 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15320 llvm_unreachable("Unknown shift opcode.");
15323 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15324 if (Op.getOpcode() == ISD::SHL) {
15325 // Make a large shift.
15326 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15327 MVT::v16i16, R, ShiftAmt,
15329 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15330 // Zero out the rightmost bits.
15331 SmallVector<SDValue, 32> V(32,
15332 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15334 return DAG.getNode(ISD::AND, dl, VT, SHL,
15335 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15337 if (Op.getOpcode() == ISD::SRL) {
15338 // Make a large shift.
15339 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15340 MVT::v16i16, R, ShiftAmt,
15342 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15343 // Zero out the leftmost bits.
15344 SmallVector<SDValue, 32> V(32,
15345 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15347 return DAG.getNode(ISD::AND, dl, VT, SRL,
15348 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15350 if (Op.getOpcode() == ISD::SRA) {
15351 if (ShiftAmt == 7) {
15352 // R s>> 7 === R s< 0
15353 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15354 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15357 // R s>> a === ((R u>> a) ^ m) - m
15358 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15359 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15361 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15362 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15363 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15366 llvm_unreachable("Unknown shift opcode.");
15371 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15372 if (!Subtarget->is64Bit() &&
15373 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15374 Amt.getOpcode() == ISD::BITCAST &&
15375 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15376 Amt = Amt.getOperand(0);
15377 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15378 VT.getVectorNumElements();
15379 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15380 uint64_t ShiftAmt = 0;
15381 for (unsigned i = 0; i != Ratio; ++i) {
15382 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15386 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15388 // Check remaining shift amounts.
15389 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15390 uint64_t ShAmt = 0;
15391 for (unsigned j = 0; j != Ratio; ++j) {
15392 ConstantSDNode *C =
15393 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15397 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15399 if (ShAmt != ShiftAmt)
15402 switch (Op.getOpcode()) {
15404 llvm_unreachable("Unknown shift opcode!");
15406 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15409 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15412 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15420 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15421 const X86Subtarget* Subtarget) {
15422 MVT VT = Op.getSimpleValueType();
15424 SDValue R = Op.getOperand(0);
15425 SDValue Amt = Op.getOperand(1);
15427 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15428 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15429 (Subtarget->hasInt256() &&
15430 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15431 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15432 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15434 EVT EltVT = VT.getVectorElementType();
15436 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15437 unsigned NumElts = VT.getVectorNumElements();
15439 for (i = 0; i != NumElts; ++i) {
15440 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15444 for (j = i; j != NumElts; ++j) {
15445 SDValue Arg = Amt.getOperand(j);
15446 if (Arg.getOpcode() == ISD::UNDEF) continue;
15447 if (Arg != Amt.getOperand(i))
15450 if (i != NumElts && j == NumElts)
15451 BaseShAmt = Amt.getOperand(i);
15453 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15454 Amt = Amt.getOperand(0);
15455 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15456 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15457 SDValue InVec = Amt.getOperand(0);
15458 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15459 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15461 for (; i != NumElts; ++i) {
15462 SDValue Arg = InVec.getOperand(i);
15463 if (Arg.getOpcode() == ISD::UNDEF) continue;
15467 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15468 if (ConstantSDNode *C =
15469 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15470 unsigned SplatIdx =
15471 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15472 if (C->getZExtValue() == SplatIdx)
15473 BaseShAmt = InVec.getOperand(1);
15476 if (!BaseShAmt.getNode())
15477 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15478 DAG.getIntPtrConstant(0));
15482 if (BaseShAmt.getNode()) {
15483 if (EltVT.bitsGT(MVT::i32))
15484 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15485 else if (EltVT.bitsLT(MVT::i32))
15486 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15488 switch (Op.getOpcode()) {
15490 llvm_unreachable("Unknown shift opcode!");
15492 switch (VT.SimpleTy) {
15493 default: return SDValue();
15502 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15505 switch (VT.SimpleTy) {
15506 default: return SDValue();
15513 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15516 switch (VT.SimpleTy) {
15517 default: return SDValue();
15526 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15532 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15533 if (!Subtarget->is64Bit() &&
15534 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15535 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15536 Amt.getOpcode() == ISD::BITCAST &&
15537 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15538 Amt = Amt.getOperand(0);
15539 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15540 VT.getVectorNumElements();
15541 std::vector<SDValue> Vals(Ratio);
15542 for (unsigned i = 0; i != Ratio; ++i)
15543 Vals[i] = Amt.getOperand(i);
15544 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15545 for (unsigned j = 0; j != Ratio; ++j)
15546 if (Vals[j] != Amt.getOperand(i + j))
15549 switch (Op.getOpcode()) {
15551 llvm_unreachable("Unknown shift opcode!");
15553 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15555 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15557 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15564 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15565 SelectionDAG &DAG) {
15566 MVT VT = Op.getSimpleValueType();
15568 SDValue R = Op.getOperand(0);
15569 SDValue Amt = Op.getOperand(1);
15572 assert(VT.isVector() && "Custom lowering only for vector shifts!");
15573 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15575 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15579 V = LowerScalarVariableShift(Op, DAG, Subtarget);
15583 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15585 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15586 if (Subtarget->hasInt256()) {
15587 if (Op.getOpcode() == ISD::SRL &&
15588 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15589 VT == MVT::v4i64 || VT == MVT::v8i32))
15591 if (Op.getOpcode() == ISD::SHL &&
15592 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15593 VT == MVT::v4i64 || VT == MVT::v8i32))
15595 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15599 // If possible, lower this packed shift into a vector multiply instead of
15600 // expanding it into a sequence of scalar shifts.
15601 // Do this only if the vector shift count is a constant build_vector.
15602 if (Op.getOpcode() == ISD::SHL &&
15603 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15604 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15605 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15606 SmallVector<SDValue, 8> Elts;
15607 EVT SVT = VT.getScalarType();
15608 unsigned SVTBits = SVT.getSizeInBits();
15609 const APInt &One = APInt(SVTBits, 1);
15610 unsigned NumElems = VT.getVectorNumElements();
15612 for (unsigned i=0; i !=NumElems; ++i) {
15613 SDValue Op = Amt->getOperand(i);
15614 if (Op->getOpcode() == ISD::UNDEF) {
15615 Elts.push_back(Op);
15619 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15620 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15621 uint64_t ShAmt = C.getZExtValue();
15622 if (ShAmt >= SVTBits) {
15623 Elts.push_back(DAG.getUNDEF(SVT));
15626 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15628 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15629 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15632 // Lower SHL with variable shift amount.
15633 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15634 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15636 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15637 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15638 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15639 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15642 // If possible, lower this shift as a sequence of two shifts by
15643 // constant plus a MOVSS/MOVSD instead of scalarizing it.
15645 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15647 // Could be rewritten as:
15648 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15650 // The advantage is that the two shifts from the example would be
15651 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15652 // the vector shift into four scalar shifts plus four pairs of vector
15654 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15655 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15656 unsigned TargetOpcode = X86ISD::MOVSS;
15657 bool CanBeSimplified;
15658 // The splat value for the first packed shift (the 'X' from the example).
15659 SDValue Amt1 = Amt->getOperand(0);
15660 // The splat value for the second packed shift (the 'Y' from the example).
15661 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15662 Amt->getOperand(2);
15664 // See if it is possible to replace this node with a sequence of
15665 // two shifts followed by a MOVSS/MOVSD
15666 if (VT == MVT::v4i32) {
15667 // Check if it is legal to use a MOVSS.
15668 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15669 Amt2 == Amt->getOperand(3);
15670 if (!CanBeSimplified) {
15671 // Otherwise, check if we can still simplify this node using a MOVSD.
15672 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15673 Amt->getOperand(2) == Amt->getOperand(3);
15674 TargetOpcode = X86ISD::MOVSD;
15675 Amt2 = Amt->getOperand(2);
15678 // Do similar checks for the case where the machine value type
15680 CanBeSimplified = Amt1 == Amt->getOperand(1);
15681 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15682 CanBeSimplified = Amt2 == Amt->getOperand(i);
15684 if (!CanBeSimplified) {
15685 TargetOpcode = X86ISD::MOVSD;
15686 CanBeSimplified = true;
15687 Amt2 = Amt->getOperand(4);
15688 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15689 CanBeSimplified = Amt1 == Amt->getOperand(i);
15690 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15691 CanBeSimplified = Amt2 == Amt->getOperand(j);
15695 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15696 isa<ConstantSDNode>(Amt2)) {
15697 // Replace this node with two shifts followed by a MOVSS/MOVSD.
15698 EVT CastVT = MVT::v4i32;
15700 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15701 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15703 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15704 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15705 if (TargetOpcode == X86ISD::MOVSD)
15706 CastVT = MVT::v2i64;
15707 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15708 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15709 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15711 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15715 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15716 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15719 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15720 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15722 // Turn 'a' into a mask suitable for VSELECT
15723 SDValue VSelM = DAG.getConstant(0x80, VT);
15724 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15725 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15727 SDValue CM1 = DAG.getConstant(0x0f, VT);
15728 SDValue CM2 = DAG.getConstant(0x3f, VT);
15730 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15731 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15732 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15733 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15734 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15737 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15738 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15739 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15741 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15742 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15743 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15744 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15745 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15748 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15749 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15750 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15752 // return VSELECT(r, r+r, a);
15753 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15754 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15758 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15759 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15760 // solution better.
15761 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15762 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15764 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15765 R = DAG.getNode(ExtOpc, dl, NewVT, R);
15766 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15767 return DAG.getNode(ISD::TRUNCATE, dl, VT,
15768 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15771 // Decompose 256-bit shifts into smaller 128-bit shifts.
15772 if (VT.is256BitVector()) {
15773 unsigned NumElems = VT.getVectorNumElements();
15774 MVT EltVT = VT.getVectorElementType();
15775 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15777 // Extract the two vectors
15778 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15779 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15781 // Recreate the shift amount vectors
15782 SDValue Amt1, Amt2;
15783 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15784 // Constant shift amount
15785 SmallVector<SDValue, 4> Amt1Csts;
15786 SmallVector<SDValue, 4> Amt2Csts;
15787 for (unsigned i = 0; i != NumElems/2; ++i)
15788 Amt1Csts.push_back(Amt->getOperand(i));
15789 for (unsigned i = NumElems/2; i != NumElems; ++i)
15790 Amt2Csts.push_back(Amt->getOperand(i));
15792 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15793 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15795 // Variable shift amount
15796 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15797 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15800 // Issue new vector shifts for the smaller types
15801 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15802 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15804 // Concatenate the result back
15805 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15811 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15812 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15813 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15814 // looks for this combo and may remove the "setcc" instruction if the "setcc"
15815 // has only one use.
15816 SDNode *N = Op.getNode();
15817 SDValue LHS = N->getOperand(0);
15818 SDValue RHS = N->getOperand(1);
15819 unsigned BaseOp = 0;
15822 switch (Op.getOpcode()) {
15823 default: llvm_unreachable("Unknown ovf instruction!");
15825 // A subtract of one will be selected as a INC. Note that INC doesn't
15826 // set CF, so we can't do this for UADDO.
15827 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15829 BaseOp = X86ISD::INC;
15830 Cond = X86::COND_O;
15833 BaseOp = X86ISD::ADD;
15834 Cond = X86::COND_O;
15837 BaseOp = X86ISD::ADD;
15838 Cond = X86::COND_B;
15841 // A subtract of one will be selected as a DEC. Note that DEC doesn't
15842 // set CF, so we can't do this for USUBO.
15843 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15845 BaseOp = X86ISD::DEC;
15846 Cond = X86::COND_O;
15849 BaseOp = X86ISD::SUB;
15850 Cond = X86::COND_O;
15853 BaseOp = X86ISD::SUB;
15854 Cond = X86::COND_B;
15857 BaseOp = X86ISD::SMUL;
15858 Cond = X86::COND_O;
15860 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15861 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15863 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15866 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15867 DAG.getConstant(X86::COND_O, MVT::i32),
15868 SDValue(Sum.getNode(), 2));
15870 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15874 // Also sets EFLAGS.
15875 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15876 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15879 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15880 DAG.getConstant(Cond, MVT::i32),
15881 SDValue(Sum.getNode(), 1));
15883 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15886 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15887 SelectionDAG &DAG) const {
15889 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15890 MVT VT = Op.getSimpleValueType();
15892 if (!Subtarget->hasSSE2() || !VT.isVector())
15895 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15896 ExtraVT.getScalarType().getSizeInBits();
15898 switch (VT.SimpleTy) {
15899 default: return SDValue();
15902 if (!Subtarget->hasFp256())
15904 if (!Subtarget->hasInt256()) {
15905 // needs to be split
15906 unsigned NumElems = VT.getVectorNumElements();
15908 // Extract the LHS vectors
15909 SDValue LHS = Op.getOperand(0);
15910 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15911 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15913 MVT EltVT = VT.getVectorElementType();
15914 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15916 EVT ExtraEltVT = ExtraVT.getVectorElementType();
15917 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15918 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15920 SDValue Extra = DAG.getValueType(ExtraVT);
15922 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15923 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15925 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15930 SDValue Op0 = Op.getOperand(0);
15931 SDValue Op00 = Op0.getOperand(0);
15933 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15934 if (Op0.getOpcode() == ISD::BITCAST &&
15935 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15936 // (sext (vzext x)) -> (vsext x)
15937 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15938 if (Tmp1.getNode()) {
15939 EVT ExtraEltVT = ExtraVT.getVectorElementType();
15940 // This folding is only valid when the in-reg type is a vector of i8,
15942 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15943 ExtraEltVT == MVT::i32) {
15944 SDValue Tmp1Op0 = Tmp1.getOperand(0);
15945 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15946 "This optimization is invalid without a VZEXT.");
15947 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15953 // If the above didn't work, then just use Shift-Left + Shift-Right.
15954 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15956 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15962 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15963 SelectionDAG &DAG) {
15965 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15966 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15967 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15968 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15970 // The only fence that needs an instruction is a sequentially-consistent
15971 // cross-thread fence.
15972 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15973 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15974 // no-sse2). There isn't any reason to disable it if the target processor
15976 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15977 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15979 SDValue Chain = Op.getOperand(0);
15980 SDValue Zero = DAG.getConstant(0, MVT::i32);
15982 DAG.getRegister(X86::ESP, MVT::i32), // Base
15983 DAG.getTargetConstant(1, MVT::i8), // Scale
15984 DAG.getRegister(0, MVT::i32), // Index
15985 DAG.getTargetConstant(0, MVT::i32), // Disp
15986 DAG.getRegister(0, MVT::i32), // Segment.
15990 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15991 return SDValue(Res, 0);
15994 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
15995 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
15998 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
15999 SelectionDAG &DAG) {
16000 MVT T = Op.getSimpleValueType();
16004 switch(T.SimpleTy) {
16005 default: llvm_unreachable("Invalid value type!");
16006 case MVT::i8: Reg = X86::AL; size = 1; break;
16007 case MVT::i16: Reg = X86::AX; size = 2; break;
16008 case MVT::i32: Reg = X86::EAX; size = 4; break;
16010 assert(Subtarget->is64Bit() && "Node not type legal!");
16011 Reg = X86::RAX; size = 8;
16014 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16015 Op.getOperand(2), SDValue());
16016 SDValue Ops[] = { cpIn.getValue(0),
16019 DAG.getTargetConstant(size, MVT::i8),
16020 cpIn.getValue(1) };
16021 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16022 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16023 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16027 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16028 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16029 MVT::i32, cpOut.getValue(2));
16030 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16031 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16033 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16034 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16035 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16039 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16040 SelectionDAG &DAG) {
16041 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16042 MVT DstVT = Op.getSimpleValueType();
16044 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16045 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16046 if (DstVT != MVT::f64)
16047 // This conversion needs to be expanded.
16050 SDValue InVec = Op->getOperand(0);
16052 unsigned NumElts = SrcVT.getVectorNumElements();
16053 EVT SVT = SrcVT.getVectorElementType();
16055 // Widen the vector in input in the case of MVT::v2i32.
16056 // Example: from MVT::v2i32 to MVT::v4i32.
16057 SmallVector<SDValue, 16> Elts;
16058 for (unsigned i = 0, e = NumElts; i != e; ++i)
16059 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16060 DAG.getIntPtrConstant(i)));
16062 // Explicitly mark the extra elements as Undef.
16063 SDValue Undef = DAG.getUNDEF(SVT);
16064 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16065 Elts.push_back(Undef);
16067 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16068 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16069 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16070 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16071 DAG.getIntPtrConstant(0));
16074 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16075 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16076 assert((DstVT == MVT::i64 ||
16077 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16078 "Unexpected custom BITCAST");
16079 // i64 <=> MMX conversions are Legal.
16080 if (SrcVT==MVT::i64 && DstVT.isVector())
16082 if (DstVT==MVT::i64 && SrcVT.isVector())
16084 // MMX <=> MMX conversions are Legal.
16085 if (SrcVT.isVector() && DstVT.isVector())
16087 // All other conversions need to be expanded.
16091 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16092 SDNode *Node = Op.getNode();
16094 EVT T = Node->getValueType(0);
16095 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16096 DAG.getConstant(0, T), Node->getOperand(2));
16097 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16098 cast<AtomicSDNode>(Node)->getMemoryVT(),
16099 Node->getOperand(0),
16100 Node->getOperand(1), negOp,
16101 cast<AtomicSDNode>(Node)->getMemOperand(),
16102 cast<AtomicSDNode>(Node)->getOrdering(),
16103 cast<AtomicSDNode>(Node)->getSynchScope());
16106 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16107 SDNode *Node = Op.getNode();
16109 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16111 // Convert seq_cst store -> xchg
16112 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16113 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16114 // (The only way to get a 16-byte store is cmpxchg16b)
16115 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16116 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16117 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16118 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16119 cast<AtomicSDNode>(Node)->getMemoryVT(),
16120 Node->getOperand(0),
16121 Node->getOperand(1), Node->getOperand(2),
16122 cast<AtomicSDNode>(Node)->getMemOperand(),
16123 cast<AtomicSDNode>(Node)->getOrdering(),
16124 cast<AtomicSDNode>(Node)->getSynchScope());
16125 return Swap.getValue(1);
16127 // Other atomic stores have a simple pattern.
16131 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16132 EVT VT = Op.getNode()->getSimpleValueType(0);
16134 // Let legalize expand this if it isn't a legal type yet.
16135 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16138 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16141 bool ExtraOp = false;
16142 switch (Op.getOpcode()) {
16143 default: llvm_unreachable("Invalid code");
16144 case ISD::ADDC: Opc = X86ISD::ADD; break;
16145 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16146 case ISD::SUBC: Opc = X86ISD::SUB; break;
16147 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16151 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16153 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16154 Op.getOperand(1), Op.getOperand(2));
16157 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16158 SelectionDAG &DAG) {
16159 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16161 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16162 // which returns the values as { float, float } (in XMM0) or
16163 // { double, double } (which is returned in XMM0, XMM1).
16165 SDValue Arg = Op.getOperand(0);
16166 EVT ArgVT = Arg.getValueType();
16167 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16169 TargetLowering::ArgListTy Args;
16170 TargetLowering::ArgListEntry Entry;
16174 Entry.isSExt = false;
16175 Entry.isZExt = false;
16176 Args.push_back(Entry);
16178 bool isF64 = ArgVT == MVT::f64;
16179 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16180 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16181 // the results are returned via SRet in memory.
16182 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16183 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16184 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16186 Type *RetTy = isF64
16187 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16188 : (Type*)VectorType::get(ArgTy, 4);
16190 TargetLowering::CallLoweringInfo CLI(DAG);
16191 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16192 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16194 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16197 // Returned in xmm0 and xmm1.
16198 return CallResult.first;
16200 // Returned in bits 0:31 and 32:64 xmm0.
16201 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16202 CallResult.first, DAG.getIntPtrConstant(0));
16203 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16204 CallResult.first, DAG.getIntPtrConstant(1));
16205 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16206 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16209 /// LowerOperation - Provide custom lowering hooks for some operations.
16211 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16212 switch (Op.getOpcode()) {
16213 default: llvm_unreachable("Should not custom lower this!");
16214 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
16215 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16216 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16217 return LowerCMP_SWAP(Op, Subtarget, DAG);
16218 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16219 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16220 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16221 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16222 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
16223 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16224 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16225 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16226 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16227 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16228 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16229 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16230 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16231 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16232 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16233 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16234 case ISD::SHL_PARTS:
16235 case ISD::SRA_PARTS:
16236 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16237 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16238 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16239 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16240 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16241 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16242 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16243 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16244 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16245 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16246 case ISD::FABS: return LowerFABS(Op, DAG);
16247 case ISD::FNEG: return LowerFNEG(Op, DAG);
16248 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16249 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16250 case ISD::SETCC: return LowerSETCC(Op, DAG);
16251 case ISD::SELECT: return LowerSELECT(Op, DAG);
16252 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16253 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16254 case ISD::VASTART: return LowerVASTART(Op, DAG);
16255 case ISD::VAARG: return LowerVAARG(Op, DAG);
16256 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16257 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16258 case ISD::INTRINSIC_VOID:
16259 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16260 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16261 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16262 case ISD::FRAME_TO_ARGS_OFFSET:
16263 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16264 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16265 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16266 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16267 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16268 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16269 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16270 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16271 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16272 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16273 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16274 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16275 case ISD::UMUL_LOHI:
16276 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16279 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16285 case ISD::UMULO: return LowerXALUO(Op, DAG);
16286 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16287 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16291 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16292 case ISD::ADD: return LowerADD(Op, DAG);
16293 case ISD::SUB: return LowerSUB(Op, DAG);
16294 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16298 static void ReplaceATOMIC_LOAD(SDNode *Node,
16299 SmallVectorImpl<SDValue> &Results,
16300 SelectionDAG &DAG) {
16302 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16304 // Convert wide load -> cmpxchg8b/cmpxchg16b
16305 // FIXME: On 32-bit, load -> fild or movq would be more efficient
16306 // (The only way to get a 16-byte load is cmpxchg16b)
16307 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16308 SDValue Zero = DAG.getConstant(0, VT);
16309 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16311 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16312 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16313 cast<AtomicSDNode>(Node)->getMemOperand(),
16314 cast<AtomicSDNode>(Node)->getOrdering(),
16315 cast<AtomicSDNode>(Node)->getOrdering(),
16316 cast<AtomicSDNode>(Node)->getSynchScope());
16317 Results.push_back(Swap.getValue(0));
16318 Results.push_back(Swap.getValue(2));
16321 /// ReplaceNodeResults - Replace a node with an illegal result type
16322 /// with a new node built out of custom code.
16323 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16324 SmallVectorImpl<SDValue>&Results,
16325 SelectionDAG &DAG) const {
16327 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16328 switch (N->getOpcode()) {
16330 llvm_unreachable("Do not know how to custom type legalize this operation!");
16331 case ISD::SIGN_EXTEND_INREG:
16336 // We don't want to expand or promote these.
16343 case ISD::UDIVREM: {
16344 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16345 Results.push_back(V);
16348 case ISD::FP_TO_SINT:
16349 case ISD::FP_TO_UINT: {
16350 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16352 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16355 std::pair<SDValue,SDValue> Vals =
16356 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16357 SDValue FIST = Vals.first, StackSlot = Vals.second;
16358 if (FIST.getNode()) {
16359 EVT VT = N->getValueType(0);
16360 // Return a load from the stack slot.
16361 if (StackSlot.getNode())
16362 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16363 MachinePointerInfo(),
16364 false, false, false, 0));
16366 Results.push_back(FIST);
16370 case ISD::UINT_TO_FP: {
16371 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16372 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16373 N->getValueType(0) != MVT::v2f32)
16375 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16377 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16379 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16380 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16381 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16382 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16383 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16384 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16387 case ISD::FP_ROUND: {
16388 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16390 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16391 Results.push_back(V);
16394 case ISD::INTRINSIC_W_CHAIN: {
16395 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16397 default : llvm_unreachable("Do not know how to custom type "
16398 "legalize this intrinsic operation!");
16399 case Intrinsic::x86_rdtsc:
16400 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16402 case Intrinsic::x86_rdtscp:
16403 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16405 case Intrinsic::x86_rdpmc:
16406 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16409 case ISD::READCYCLECOUNTER: {
16410 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16413 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16414 EVT T = N->getValueType(0);
16415 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16416 bool Regs64bit = T == MVT::i128;
16417 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16418 SDValue cpInL, cpInH;
16419 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16420 DAG.getConstant(0, HalfT));
16421 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16422 DAG.getConstant(1, HalfT));
16423 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16424 Regs64bit ? X86::RAX : X86::EAX,
16426 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16427 Regs64bit ? X86::RDX : X86::EDX,
16428 cpInH, cpInL.getValue(1));
16429 SDValue swapInL, swapInH;
16430 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16431 DAG.getConstant(0, HalfT));
16432 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16433 DAG.getConstant(1, HalfT));
16434 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16435 Regs64bit ? X86::RBX : X86::EBX,
16436 swapInL, cpInH.getValue(1));
16437 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16438 Regs64bit ? X86::RCX : X86::ECX,
16439 swapInH, swapInL.getValue(1));
16440 SDValue Ops[] = { swapInH.getValue(0),
16442 swapInH.getValue(1) };
16443 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16444 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16445 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16446 X86ISD::LCMPXCHG8_DAG;
16447 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16448 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16449 Regs64bit ? X86::RAX : X86::EAX,
16450 HalfT, Result.getValue(1));
16451 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16452 Regs64bit ? X86::RDX : X86::EDX,
16453 HalfT, cpOutL.getValue(2));
16454 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16456 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16457 MVT::i32, cpOutH.getValue(2));
16459 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16460 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16461 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16463 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16464 Results.push_back(Success);
16465 Results.push_back(EFLAGS.getValue(1));
16468 case ISD::ATOMIC_SWAP:
16469 case ISD::ATOMIC_LOAD_ADD:
16470 case ISD::ATOMIC_LOAD_SUB:
16471 case ISD::ATOMIC_LOAD_AND:
16472 case ISD::ATOMIC_LOAD_OR:
16473 case ISD::ATOMIC_LOAD_XOR:
16474 case ISD::ATOMIC_LOAD_NAND:
16475 case ISD::ATOMIC_LOAD_MIN:
16476 case ISD::ATOMIC_LOAD_MAX:
16477 case ISD::ATOMIC_LOAD_UMIN:
16478 case ISD::ATOMIC_LOAD_UMAX:
16479 // Delegate to generic TypeLegalization. Situations we can really handle
16480 // should have already been dealt with by X86AtomicExpand.cpp.
16482 case ISD::ATOMIC_LOAD: {
16483 ReplaceATOMIC_LOAD(N, Results, DAG);
16486 case ISD::BITCAST: {
16487 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16488 EVT DstVT = N->getValueType(0);
16489 EVT SrcVT = N->getOperand(0)->getValueType(0);
16491 if (SrcVT != MVT::f64 ||
16492 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16495 unsigned NumElts = DstVT.getVectorNumElements();
16496 EVT SVT = DstVT.getVectorElementType();
16497 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16498 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16499 MVT::v2f64, N->getOperand(0));
16500 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16502 if (ExperimentalVectorWideningLegalization) {
16503 // If we are legalizing vectors by widening, we already have the desired
16504 // legal vector type, just return it.
16505 Results.push_back(ToVecInt);
16509 SmallVector<SDValue, 8> Elts;
16510 for (unsigned i = 0, e = NumElts; i != e; ++i)
16511 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16512 ToVecInt, DAG.getIntPtrConstant(i)));
16514 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16519 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16521 default: return nullptr;
16522 case X86ISD::BSF: return "X86ISD::BSF";
16523 case X86ISD::BSR: return "X86ISD::BSR";
16524 case X86ISD::SHLD: return "X86ISD::SHLD";
16525 case X86ISD::SHRD: return "X86ISD::SHRD";
16526 case X86ISD::FAND: return "X86ISD::FAND";
16527 case X86ISD::FANDN: return "X86ISD::FANDN";
16528 case X86ISD::FOR: return "X86ISD::FOR";
16529 case X86ISD::FXOR: return "X86ISD::FXOR";
16530 case X86ISD::FSRL: return "X86ISD::FSRL";
16531 case X86ISD::FILD: return "X86ISD::FILD";
16532 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
16533 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16534 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16535 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16536 case X86ISD::FLD: return "X86ISD::FLD";
16537 case X86ISD::FST: return "X86ISD::FST";
16538 case X86ISD::CALL: return "X86ISD::CALL";
16539 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
16540 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
16541 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
16542 case X86ISD::BT: return "X86ISD::BT";
16543 case X86ISD::CMP: return "X86ISD::CMP";
16544 case X86ISD::COMI: return "X86ISD::COMI";
16545 case X86ISD::UCOMI: return "X86ISD::UCOMI";
16546 case X86ISD::CMPM: return "X86ISD::CMPM";
16547 case X86ISD::CMPMU: return "X86ISD::CMPMU";
16548 case X86ISD::SETCC: return "X86ISD::SETCC";
16549 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
16550 case X86ISD::FSETCC: return "X86ISD::FSETCC";
16551 case X86ISD::CMOV: return "X86ISD::CMOV";
16552 case X86ISD::BRCOND: return "X86ISD::BRCOND";
16553 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
16554 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
16555 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
16556 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
16557 case X86ISD::Wrapper: return "X86ISD::Wrapper";
16558 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
16559 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
16560 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
16561 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
16562 case X86ISD::PINSRB: return "X86ISD::PINSRB";
16563 case X86ISD::PINSRW: return "X86ISD::PINSRW";
16564 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
16565 case X86ISD::ANDNP: return "X86ISD::ANDNP";
16566 case X86ISD::PSIGN: return "X86ISD::PSIGN";
16567 case X86ISD::BLENDV: return "X86ISD::BLENDV";
16568 case X86ISD::BLENDI: return "X86ISD::BLENDI";
16569 case X86ISD::SUBUS: return "X86ISD::SUBUS";
16570 case X86ISD::HADD: return "X86ISD::HADD";
16571 case X86ISD::HSUB: return "X86ISD::HSUB";
16572 case X86ISD::FHADD: return "X86ISD::FHADD";
16573 case X86ISD::FHSUB: return "X86ISD::FHSUB";
16574 case X86ISD::UMAX: return "X86ISD::UMAX";
16575 case X86ISD::UMIN: return "X86ISD::UMIN";
16576 case X86ISD::SMAX: return "X86ISD::SMAX";
16577 case X86ISD::SMIN: return "X86ISD::SMIN";
16578 case X86ISD::FMAX: return "X86ISD::FMAX";
16579 case X86ISD::FMIN: return "X86ISD::FMIN";
16580 case X86ISD::FMAXC: return "X86ISD::FMAXC";
16581 case X86ISD::FMINC: return "X86ISD::FMINC";
16582 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
16583 case X86ISD::FRCP: return "X86ISD::FRCP";
16584 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
16585 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
16586 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
16587 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
16588 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
16589 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
16590 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
16591 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
16592 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
16593 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
16594 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
16595 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
16596 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
16597 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
16598 case X86ISD::VZEXT: return "X86ISD::VZEXT";
16599 case X86ISD::VSEXT: return "X86ISD::VSEXT";
16600 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
16601 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
16602 case X86ISD::VINSERT: return "X86ISD::VINSERT";
16603 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
16604 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
16605 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
16606 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
16607 case X86ISD::VSHL: return "X86ISD::VSHL";
16608 case X86ISD::VSRL: return "X86ISD::VSRL";
16609 case X86ISD::VSRA: return "X86ISD::VSRA";
16610 case X86ISD::VSHLI: return "X86ISD::VSHLI";
16611 case X86ISD::VSRLI: return "X86ISD::VSRLI";
16612 case X86ISD::VSRAI: return "X86ISD::VSRAI";
16613 case X86ISD::CMPP: return "X86ISD::CMPP";
16614 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
16615 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
16616 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
16617 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
16618 case X86ISD::ADD: return "X86ISD::ADD";
16619 case X86ISD::SUB: return "X86ISD::SUB";
16620 case X86ISD::ADC: return "X86ISD::ADC";
16621 case X86ISD::SBB: return "X86ISD::SBB";
16622 case X86ISD::SMUL: return "X86ISD::SMUL";
16623 case X86ISD::UMUL: return "X86ISD::UMUL";
16624 case X86ISD::INC: return "X86ISD::INC";
16625 case X86ISD::DEC: return "X86ISD::DEC";
16626 case X86ISD::OR: return "X86ISD::OR";
16627 case X86ISD::XOR: return "X86ISD::XOR";
16628 case X86ISD::AND: return "X86ISD::AND";
16629 case X86ISD::BEXTR: return "X86ISD::BEXTR";
16630 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
16631 case X86ISD::PTEST: return "X86ISD::PTEST";
16632 case X86ISD::TESTP: return "X86ISD::TESTP";
16633 case X86ISD::TESTM: return "X86ISD::TESTM";
16634 case X86ISD::TESTNM: return "X86ISD::TESTNM";
16635 case X86ISD::KORTEST: return "X86ISD::KORTEST";
16636 case X86ISD::PACKSS: return "X86ISD::PACKSS";
16637 case X86ISD::PACKUS: return "X86ISD::PACKUS";
16638 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
16639 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
16640 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
16641 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
16642 case X86ISD::SHUFP: return "X86ISD::SHUFP";
16643 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
16644 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
16645 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
16646 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
16647 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
16648 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
16649 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
16650 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
16651 case X86ISD::MOVSD: return "X86ISD::MOVSD";
16652 case X86ISD::MOVSS: return "X86ISD::MOVSS";
16653 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
16654 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
16655 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
16656 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
16657 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
16658 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
16659 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
16660 case X86ISD::VPERMV: return "X86ISD::VPERMV";
16661 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
16662 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
16663 case X86ISD::VPERMI: return "X86ISD::VPERMI";
16664 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
16665 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
16666 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16667 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
16668 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
16669 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
16670 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
16671 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
16672 case X86ISD::SAHF: return "X86ISD::SAHF";
16673 case X86ISD::RDRAND: return "X86ISD::RDRAND";
16674 case X86ISD::RDSEED: return "X86ISD::RDSEED";
16675 case X86ISD::FMADD: return "X86ISD::FMADD";
16676 case X86ISD::FMSUB: return "X86ISD::FMSUB";
16677 case X86ISD::FNMADD: return "X86ISD::FNMADD";
16678 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
16679 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
16680 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
16681 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
16682 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
16683 case X86ISD::XTEST: return "X86ISD::XTEST";
16687 // isLegalAddressingMode - Return true if the addressing mode represented
16688 // by AM is legal for this target, for a load/store of the specified type.
16689 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16691 // X86 supports extremely general addressing modes.
16692 CodeModel::Model M = getTargetMachine().getCodeModel();
16693 Reloc::Model R = getTargetMachine().getRelocationModel();
16695 // X86 allows a sign-extended 32-bit immediate field as a displacement.
16696 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16701 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16703 // If a reference to this global requires an extra load, we can't fold it.
16704 if (isGlobalStubReference(GVFlags))
16707 // If BaseGV requires a register for the PIC base, we cannot also have a
16708 // BaseReg specified.
16709 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16712 // If lower 4G is not available, then we must use rip-relative addressing.
16713 if ((M != CodeModel::Small || R != Reloc::Static) &&
16714 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16718 switch (AM.Scale) {
16724 // These scales always work.
16729 // These scales are formed with basereg+scalereg. Only accept if there is
16734 default: // Other stuff never works.
16741 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16742 unsigned Bits = Ty->getScalarSizeInBits();
16744 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16745 // particularly cheaper than those without.
16749 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16750 // variable shifts just as cheap as scalar ones.
16751 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16754 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16755 // fully general vector.
16759 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16760 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16762 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16763 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16764 return NumBits1 > NumBits2;
16767 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16768 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16771 if (!isTypeLegal(EVT::getEVT(Ty1)))
16774 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16776 // Assuming the caller doesn't have a zeroext or signext return parameter,
16777 // truncation all the way down to i1 is valid.
16781 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16782 return isInt<32>(Imm);
16785 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16786 // Can also use sub to handle negated immediates.
16787 return isInt<32>(Imm);
16790 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16791 if (!VT1.isInteger() || !VT2.isInteger())
16793 unsigned NumBits1 = VT1.getSizeInBits();
16794 unsigned NumBits2 = VT2.getSizeInBits();
16795 return NumBits1 > NumBits2;
16798 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16799 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16800 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16803 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16804 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16805 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16808 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16809 EVT VT1 = Val.getValueType();
16810 if (isZExtFree(VT1, VT2))
16813 if (Val.getOpcode() != ISD::LOAD)
16816 if (!VT1.isSimple() || !VT1.isInteger() ||
16817 !VT2.isSimple() || !VT2.isInteger())
16820 switch (VT1.getSimpleVT().SimpleTy) {
16825 // X86 has 8, 16, and 32-bit zero-extending loads.
16833 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16834 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16837 VT = VT.getScalarType();
16839 if (!VT.isSimple())
16842 switch (VT.getSimpleVT().SimpleTy) {
16853 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16854 // i16 instructions are longer (0x66 prefix) and potentially slower.
16855 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16858 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16859 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16860 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16861 /// are assumed to be legal.
16863 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16865 if (!VT.isSimple())
16868 MVT SVT = VT.getSimpleVT();
16870 // Very little shuffling can be done for 64-bit vectors right now.
16871 if (VT.getSizeInBits() == 64)
16874 // If this is a single-input shuffle with no 128 bit lane crossings we can
16875 // lower it into pshufb.
16876 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16877 (SVT.is256BitVector() && Subtarget->hasInt256())) {
16878 bool isLegal = true;
16879 for (unsigned I = 0, E = M.size(); I != E; ++I) {
16880 if (M[I] >= (int)SVT.getVectorNumElements() ||
16881 ShuffleCrosses128bitLane(SVT, I, M[I])) {
16890 // FIXME: blends, shifts.
16891 return (SVT.getVectorNumElements() == 2 ||
16892 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16893 isMOVLMask(M, SVT) ||
16894 isMOVHLPSMask(M, SVT) ||
16895 isSHUFPMask(M, SVT) ||
16896 isPSHUFDMask(M, SVT) ||
16897 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16898 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16899 isPALIGNRMask(M, SVT, Subtarget) ||
16900 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16901 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16902 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16903 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16904 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16908 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16910 if (!VT.isSimple())
16913 MVT SVT = VT.getSimpleVT();
16914 unsigned NumElts = SVT.getVectorNumElements();
16915 // FIXME: This collection of masks seems suspect.
16918 if (NumElts == 4 && SVT.is128BitVector()) {
16919 return (isMOVLMask(Mask, SVT) ||
16920 isCommutedMOVLMask(Mask, SVT, true) ||
16921 isSHUFPMask(Mask, SVT) ||
16922 isSHUFPMask(Mask, SVT, /* Commuted */ true));
16927 //===----------------------------------------------------------------------===//
16928 // X86 Scheduler Hooks
16929 //===----------------------------------------------------------------------===//
16931 /// Utility function to emit xbegin specifying the start of an RTM region.
16932 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16933 const TargetInstrInfo *TII) {
16934 DebugLoc DL = MI->getDebugLoc();
16936 const BasicBlock *BB = MBB->getBasicBlock();
16937 MachineFunction::iterator I = MBB;
16940 // For the v = xbegin(), we generate
16951 MachineBasicBlock *thisMBB = MBB;
16952 MachineFunction *MF = MBB->getParent();
16953 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16954 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16955 MF->insert(I, mainMBB);
16956 MF->insert(I, sinkMBB);
16958 // Transfer the remainder of BB and its successor edges to sinkMBB.
16959 sinkMBB->splice(sinkMBB->begin(), MBB,
16960 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16961 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16965 // # fallthrough to mainMBB
16966 // # abortion to sinkMBB
16967 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16968 thisMBB->addSuccessor(mainMBB);
16969 thisMBB->addSuccessor(sinkMBB);
16973 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16974 mainMBB->addSuccessor(sinkMBB);
16977 // EAX is live into the sinkMBB
16978 sinkMBB->addLiveIn(X86::EAX);
16979 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16980 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16983 MI->eraseFromParent();
16987 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16988 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16989 // in the .td file.
16990 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16991 const TargetInstrInfo *TII) {
16993 switch (MI->getOpcode()) {
16994 default: llvm_unreachable("illegal opcode!");
16995 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
16996 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16997 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
16998 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16999 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17000 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17001 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17002 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17005 DebugLoc dl = MI->getDebugLoc();
17006 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17008 unsigned NumArgs = MI->getNumOperands();
17009 for (unsigned i = 1; i < NumArgs; ++i) {
17010 MachineOperand &Op = MI->getOperand(i);
17011 if (!(Op.isReg() && Op.isImplicit()))
17012 MIB.addOperand(Op);
17014 if (MI->hasOneMemOperand())
17015 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17017 BuildMI(*BB, MI, dl,
17018 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17019 .addReg(X86::XMM0);
17021 MI->eraseFromParent();
17025 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17026 // defs in an instruction pattern
17027 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17028 const TargetInstrInfo *TII) {
17030 switch (MI->getOpcode()) {
17031 default: llvm_unreachable("illegal opcode!");
17032 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17033 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17034 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17035 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17036 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17037 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17038 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17039 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17042 DebugLoc dl = MI->getDebugLoc();
17043 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17045 unsigned NumArgs = MI->getNumOperands(); // remove the results
17046 for (unsigned i = 1; i < NumArgs; ++i) {
17047 MachineOperand &Op = MI->getOperand(i);
17048 if (!(Op.isReg() && Op.isImplicit()))
17049 MIB.addOperand(Op);
17051 if (MI->hasOneMemOperand())
17052 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17054 BuildMI(*BB, MI, dl,
17055 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17058 MI->eraseFromParent();
17062 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17063 const TargetInstrInfo *TII,
17064 const X86Subtarget* Subtarget) {
17065 DebugLoc dl = MI->getDebugLoc();
17067 // Address into RAX/EAX, other two args into ECX, EDX.
17068 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17069 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17070 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17071 for (int i = 0; i < X86::AddrNumOperands; ++i)
17072 MIB.addOperand(MI->getOperand(i));
17074 unsigned ValOps = X86::AddrNumOperands;
17075 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17076 .addReg(MI->getOperand(ValOps).getReg());
17077 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17078 .addReg(MI->getOperand(ValOps+1).getReg());
17080 // The instruction doesn't actually take any operands though.
17081 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17083 MI->eraseFromParent(); // The pseudo is gone now.
17087 MachineBasicBlock *
17088 X86TargetLowering::EmitVAARG64WithCustomInserter(
17090 MachineBasicBlock *MBB) const {
17091 // Emit va_arg instruction on X86-64.
17093 // Operands to this pseudo-instruction:
17094 // 0 ) Output : destination address (reg)
17095 // 1-5) Input : va_list address (addr, i64mem)
17096 // 6 ) ArgSize : Size (in bytes) of vararg type
17097 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17098 // 8 ) Align : Alignment of type
17099 // 9 ) EFLAGS (implicit-def)
17101 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17102 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17104 unsigned DestReg = MI->getOperand(0).getReg();
17105 MachineOperand &Base = MI->getOperand(1);
17106 MachineOperand &Scale = MI->getOperand(2);
17107 MachineOperand &Index = MI->getOperand(3);
17108 MachineOperand &Disp = MI->getOperand(4);
17109 MachineOperand &Segment = MI->getOperand(5);
17110 unsigned ArgSize = MI->getOperand(6).getImm();
17111 unsigned ArgMode = MI->getOperand(7).getImm();
17112 unsigned Align = MI->getOperand(8).getImm();
17114 // Memory Reference
17115 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17116 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17117 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17119 // Machine Information
17120 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17121 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17122 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17123 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17124 DebugLoc DL = MI->getDebugLoc();
17126 // struct va_list {
17129 // i64 overflow_area (address)
17130 // i64 reg_save_area (address)
17132 // sizeof(va_list) = 24
17133 // alignment(va_list) = 8
17135 unsigned TotalNumIntRegs = 6;
17136 unsigned TotalNumXMMRegs = 8;
17137 bool UseGPOffset = (ArgMode == 1);
17138 bool UseFPOffset = (ArgMode == 2);
17139 unsigned MaxOffset = TotalNumIntRegs * 8 +
17140 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17142 /* Align ArgSize to a multiple of 8 */
17143 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17144 bool NeedsAlign = (Align > 8);
17146 MachineBasicBlock *thisMBB = MBB;
17147 MachineBasicBlock *overflowMBB;
17148 MachineBasicBlock *offsetMBB;
17149 MachineBasicBlock *endMBB;
17151 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17152 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17153 unsigned OffsetReg = 0;
17155 if (!UseGPOffset && !UseFPOffset) {
17156 // If we only pull from the overflow region, we don't create a branch.
17157 // We don't need to alter control flow.
17158 OffsetDestReg = 0; // unused
17159 OverflowDestReg = DestReg;
17161 offsetMBB = nullptr;
17162 overflowMBB = thisMBB;
17165 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17166 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17167 // If not, pull from overflow_area. (branch to overflowMBB)
17172 // offsetMBB overflowMBB
17177 // Registers for the PHI in endMBB
17178 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17179 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17181 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17182 MachineFunction *MF = MBB->getParent();
17183 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17184 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17185 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17187 MachineFunction::iterator MBBIter = MBB;
17190 // Insert the new basic blocks
17191 MF->insert(MBBIter, offsetMBB);
17192 MF->insert(MBBIter, overflowMBB);
17193 MF->insert(MBBIter, endMBB);
17195 // Transfer the remainder of MBB and its successor edges to endMBB.
17196 endMBB->splice(endMBB->begin(), thisMBB,
17197 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17198 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17200 // Make offsetMBB and overflowMBB successors of thisMBB
17201 thisMBB->addSuccessor(offsetMBB);
17202 thisMBB->addSuccessor(overflowMBB);
17204 // endMBB is a successor of both offsetMBB and overflowMBB
17205 offsetMBB->addSuccessor(endMBB);
17206 overflowMBB->addSuccessor(endMBB);
17208 // Load the offset value into a register
17209 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17210 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17214 .addDisp(Disp, UseFPOffset ? 4 : 0)
17215 .addOperand(Segment)
17216 .setMemRefs(MMOBegin, MMOEnd);
17218 // Check if there is enough room left to pull this argument.
17219 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17221 .addImm(MaxOffset + 8 - ArgSizeA8);
17223 // Branch to "overflowMBB" if offset >= max
17224 // Fall through to "offsetMBB" otherwise
17225 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17226 .addMBB(overflowMBB);
17229 // In offsetMBB, emit code to use the reg_save_area.
17231 assert(OffsetReg != 0);
17233 // Read the reg_save_area address.
17234 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17235 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17240 .addOperand(Segment)
17241 .setMemRefs(MMOBegin, MMOEnd);
17243 // Zero-extend the offset
17244 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17245 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17248 .addImm(X86::sub_32bit);
17250 // Add the offset to the reg_save_area to get the final address.
17251 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17252 .addReg(OffsetReg64)
17253 .addReg(RegSaveReg);
17255 // Compute the offset for the next argument
17256 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17257 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17259 .addImm(UseFPOffset ? 16 : 8);
17261 // Store it back into the va_list.
17262 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17266 .addDisp(Disp, UseFPOffset ? 4 : 0)
17267 .addOperand(Segment)
17268 .addReg(NextOffsetReg)
17269 .setMemRefs(MMOBegin, MMOEnd);
17272 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17277 // Emit code to use overflow area
17280 // Load the overflow_area address into a register.
17281 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17282 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17287 .addOperand(Segment)
17288 .setMemRefs(MMOBegin, MMOEnd);
17290 // If we need to align it, do so. Otherwise, just copy the address
17291 // to OverflowDestReg.
17293 // Align the overflow address
17294 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17295 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17297 // aligned_addr = (addr + (align-1)) & ~(align-1)
17298 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17299 .addReg(OverflowAddrReg)
17302 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17304 .addImm(~(uint64_t)(Align-1));
17306 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17307 .addReg(OverflowAddrReg);
17310 // Compute the next overflow address after this argument.
17311 // (the overflow address should be kept 8-byte aligned)
17312 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17313 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17314 .addReg(OverflowDestReg)
17315 .addImm(ArgSizeA8);
17317 // Store the new overflow address.
17318 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17323 .addOperand(Segment)
17324 .addReg(NextAddrReg)
17325 .setMemRefs(MMOBegin, MMOEnd);
17327 // If we branched, emit the PHI to the front of endMBB.
17329 BuildMI(*endMBB, endMBB->begin(), DL,
17330 TII->get(X86::PHI), DestReg)
17331 .addReg(OffsetDestReg).addMBB(offsetMBB)
17332 .addReg(OverflowDestReg).addMBB(overflowMBB);
17335 // Erase the pseudo instruction
17336 MI->eraseFromParent();
17341 MachineBasicBlock *
17342 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17344 MachineBasicBlock *MBB) const {
17345 // Emit code to save XMM registers to the stack. The ABI says that the
17346 // number of registers to save is given in %al, so it's theoretically
17347 // possible to do an indirect jump trick to avoid saving all of them,
17348 // however this code takes a simpler approach and just executes all
17349 // of the stores if %al is non-zero. It's less code, and it's probably
17350 // easier on the hardware branch predictor, and stores aren't all that
17351 // expensive anyway.
17353 // Create the new basic blocks. One block contains all the XMM stores,
17354 // and one block is the final destination regardless of whether any
17355 // stores were performed.
17356 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17357 MachineFunction *F = MBB->getParent();
17358 MachineFunction::iterator MBBIter = MBB;
17360 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17361 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17362 F->insert(MBBIter, XMMSaveMBB);
17363 F->insert(MBBIter, EndMBB);
17365 // Transfer the remainder of MBB and its successor edges to EndMBB.
17366 EndMBB->splice(EndMBB->begin(), MBB,
17367 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17368 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17370 // The original block will now fall through to the XMM save block.
17371 MBB->addSuccessor(XMMSaveMBB);
17372 // The XMMSaveMBB will fall through to the end block.
17373 XMMSaveMBB->addSuccessor(EndMBB);
17375 // Now add the instructions.
17376 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17377 DebugLoc DL = MI->getDebugLoc();
17379 unsigned CountReg = MI->getOperand(0).getReg();
17380 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17381 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17383 if (!Subtarget->isTargetWin64()) {
17384 // If %al is 0, branch around the XMM save block.
17385 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17386 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17387 MBB->addSuccessor(EndMBB);
17390 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17391 // that was just emitted, but clearly shouldn't be "saved".
17392 assert((MI->getNumOperands() <= 3 ||
17393 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17394 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17395 && "Expected last argument to be EFLAGS");
17396 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17397 // In the XMM save block, save all the XMM argument registers.
17398 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17399 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17400 MachineMemOperand *MMO =
17401 F->getMachineMemOperand(
17402 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17403 MachineMemOperand::MOStore,
17404 /*Size=*/16, /*Align=*/16);
17405 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17406 .addFrameIndex(RegSaveFrameIndex)
17407 .addImm(/*Scale=*/1)
17408 .addReg(/*IndexReg=*/0)
17409 .addImm(/*Disp=*/Offset)
17410 .addReg(/*Segment=*/0)
17411 .addReg(MI->getOperand(i).getReg())
17412 .addMemOperand(MMO);
17415 MI->eraseFromParent(); // The pseudo instruction is gone now.
17420 // The EFLAGS operand of SelectItr might be missing a kill marker
17421 // because there were multiple uses of EFLAGS, and ISel didn't know
17422 // which to mark. Figure out whether SelectItr should have had a
17423 // kill marker, and set it if it should. Returns the correct kill
17425 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17426 MachineBasicBlock* BB,
17427 const TargetRegisterInfo* TRI) {
17428 // Scan forward through BB for a use/def of EFLAGS.
17429 MachineBasicBlock::iterator miI(std::next(SelectItr));
17430 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17431 const MachineInstr& mi = *miI;
17432 if (mi.readsRegister(X86::EFLAGS))
17434 if (mi.definesRegister(X86::EFLAGS))
17435 break; // Should have kill-flag - update below.
17438 // If we hit the end of the block, check whether EFLAGS is live into a
17440 if (miI == BB->end()) {
17441 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17442 sEnd = BB->succ_end();
17443 sItr != sEnd; ++sItr) {
17444 MachineBasicBlock* succ = *sItr;
17445 if (succ->isLiveIn(X86::EFLAGS))
17450 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17451 // out. SelectMI should have a kill flag on EFLAGS.
17452 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17456 MachineBasicBlock *
17457 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17458 MachineBasicBlock *BB) const {
17459 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17460 DebugLoc DL = MI->getDebugLoc();
17462 // To "insert" a SELECT_CC instruction, we actually have to insert the
17463 // diamond control-flow pattern. The incoming instruction knows the
17464 // destination vreg to set, the condition code register to branch on, the
17465 // true/false values to select between, and a branch opcode to use.
17466 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17467 MachineFunction::iterator It = BB;
17473 // cmpTY ccX, r1, r2
17475 // fallthrough --> copy0MBB
17476 MachineBasicBlock *thisMBB = BB;
17477 MachineFunction *F = BB->getParent();
17478 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17479 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17480 F->insert(It, copy0MBB);
17481 F->insert(It, sinkMBB);
17483 // If the EFLAGS register isn't dead in the terminator, then claim that it's
17484 // live into the sink and copy blocks.
17485 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17486 if (!MI->killsRegister(X86::EFLAGS) &&
17487 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17488 copy0MBB->addLiveIn(X86::EFLAGS);
17489 sinkMBB->addLiveIn(X86::EFLAGS);
17492 // Transfer the remainder of BB and its successor edges to sinkMBB.
17493 sinkMBB->splice(sinkMBB->begin(), BB,
17494 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17495 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17497 // Add the true and fallthrough blocks as its successors.
17498 BB->addSuccessor(copy0MBB);
17499 BB->addSuccessor(sinkMBB);
17501 // Create the conditional branch instruction.
17503 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17504 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17507 // %FalseValue = ...
17508 // # fallthrough to sinkMBB
17509 copy0MBB->addSuccessor(sinkMBB);
17512 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17514 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17515 TII->get(X86::PHI), MI->getOperand(0).getReg())
17516 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17517 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17519 MI->eraseFromParent(); // The pseudo instruction is gone now.
17523 MachineBasicBlock *
17524 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17525 bool Is64Bit) const {
17526 MachineFunction *MF = BB->getParent();
17527 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17528 DebugLoc DL = MI->getDebugLoc();
17529 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17531 assert(MF->shouldSplitStack());
17533 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17534 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17537 // ... [Till the alloca]
17538 // If stacklet is not large enough, jump to mallocMBB
17541 // Allocate by subtracting from RSP
17542 // Jump to continueMBB
17545 // Allocate by call to runtime
17549 // [rest of original BB]
17552 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17553 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17554 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17556 MachineRegisterInfo &MRI = MF->getRegInfo();
17557 const TargetRegisterClass *AddrRegClass =
17558 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17560 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17561 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17562 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17563 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17564 sizeVReg = MI->getOperand(1).getReg(),
17565 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17567 MachineFunction::iterator MBBIter = BB;
17570 MF->insert(MBBIter, bumpMBB);
17571 MF->insert(MBBIter, mallocMBB);
17572 MF->insert(MBBIter, continueMBB);
17574 continueMBB->splice(continueMBB->begin(), BB,
17575 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17576 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17578 // Add code to the main basic block to check if the stack limit has been hit,
17579 // and if so, jump to mallocMBB otherwise to bumpMBB.
17580 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17581 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17582 .addReg(tmpSPVReg).addReg(sizeVReg);
17583 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17584 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17585 .addReg(SPLimitVReg);
17586 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17588 // bumpMBB simply decreases the stack pointer, since we know the current
17589 // stacklet has enough space.
17590 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17591 .addReg(SPLimitVReg);
17592 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17593 .addReg(SPLimitVReg);
17594 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17596 // Calls into a routine in libgcc to allocate more space from the heap.
17597 const uint32_t *RegMask =
17598 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17600 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17602 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17603 .addExternalSymbol("__morestack_allocate_stack_space")
17604 .addRegMask(RegMask)
17605 .addReg(X86::RDI, RegState::Implicit)
17606 .addReg(X86::RAX, RegState::ImplicitDefine);
17608 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17610 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17611 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17612 .addExternalSymbol("__morestack_allocate_stack_space")
17613 .addRegMask(RegMask)
17614 .addReg(X86::EAX, RegState::ImplicitDefine);
17618 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17621 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17622 .addReg(Is64Bit ? X86::RAX : X86::EAX);
17623 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17625 // Set up the CFG correctly.
17626 BB->addSuccessor(bumpMBB);
17627 BB->addSuccessor(mallocMBB);
17628 mallocMBB->addSuccessor(continueMBB);
17629 bumpMBB->addSuccessor(continueMBB);
17631 // Take care of the PHI nodes.
17632 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17633 MI->getOperand(0).getReg())
17634 .addReg(mallocPtrVReg).addMBB(mallocMBB)
17635 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17637 // Delete the original pseudo instruction.
17638 MI->eraseFromParent();
17641 return continueMBB;
17644 MachineBasicBlock *
17645 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17646 MachineBasicBlock *BB) const {
17647 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17648 DebugLoc DL = MI->getDebugLoc();
17650 assert(!Subtarget->isTargetMacho());
17652 // The lowering is pretty easy: we're just emitting the call to _alloca. The
17653 // non-trivial part is impdef of ESP.
17655 if (Subtarget->isTargetWin64()) {
17656 if (Subtarget->isTargetCygMing()) {
17657 // ___chkstk(Mingw64):
17658 // Clobbers R10, R11, RAX and EFLAGS.
17660 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17661 .addExternalSymbol("___chkstk")
17662 .addReg(X86::RAX, RegState::Implicit)
17663 .addReg(X86::RSP, RegState::Implicit)
17664 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17665 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17666 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17668 // __chkstk(MSVCRT): does not update stack pointer.
17669 // Clobbers R10, R11 and EFLAGS.
17670 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17671 .addExternalSymbol("__chkstk")
17672 .addReg(X86::RAX, RegState::Implicit)
17673 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17674 // RAX has the offset to be subtracted from RSP.
17675 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17680 const char *StackProbeSymbol =
17681 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17683 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17684 .addExternalSymbol(StackProbeSymbol)
17685 .addReg(X86::EAX, RegState::Implicit)
17686 .addReg(X86::ESP, RegState::Implicit)
17687 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17688 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17689 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17692 MI->eraseFromParent(); // The pseudo instruction is gone now.
17696 MachineBasicBlock *
17697 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17698 MachineBasicBlock *BB) const {
17699 // This is pretty easy. We're taking the value that we received from
17700 // our load from the relocation, sticking it in either RDI (x86-64)
17701 // or EAX and doing an indirect call. The return value will then
17702 // be in the normal return register.
17703 MachineFunction *F = BB->getParent();
17704 const X86InstrInfo *TII
17705 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17706 DebugLoc DL = MI->getDebugLoc();
17708 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17709 assert(MI->getOperand(3).isGlobal() && "This should be a global");
17711 // Get a register mask for the lowered call.
17712 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17713 // proper register mask.
17714 const uint32_t *RegMask =
17715 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17716 if (Subtarget->is64Bit()) {
17717 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17718 TII->get(X86::MOV64rm), X86::RDI)
17720 .addImm(0).addReg(0)
17721 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17722 MI->getOperand(3).getTargetFlags())
17724 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17725 addDirectMem(MIB, X86::RDI);
17726 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17727 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17728 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17729 TII->get(X86::MOV32rm), X86::EAX)
17731 .addImm(0).addReg(0)
17732 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17733 MI->getOperand(3).getTargetFlags())
17735 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17736 addDirectMem(MIB, X86::EAX);
17737 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17739 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17740 TII->get(X86::MOV32rm), X86::EAX)
17741 .addReg(TII->getGlobalBaseReg(F))
17742 .addImm(0).addReg(0)
17743 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17744 MI->getOperand(3).getTargetFlags())
17746 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17747 addDirectMem(MIB, X86::EAX);
17748 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17751 MI->eraseFromParent(); // The pseudo instruction is gone now.
17755 MachineBasicBlock *
17756 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17757 MachineBasicBlock *MBB) const {
17758 DebugLoc DL = MI->getDebugLoc();
17759 MachineFunction *MF = MBB->getParent();
17760 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17761 MachineRegisterInfo &MRI = MF->getRegInfo();
17763 const BasicBlock *BB = MBB->getBasicBlock();
17764 MachineFunction::iterator I = MBB;
17767 // Memory Reference
17768 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17769 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17772 unsigned MemOpndSlot = 0;
17774 unsigned CurOp = 0;
17776 DstReg = MI->getOperand(CurOp++).getReg();
17777 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17778 assert(RC->hasType(MVT::i32) && "Invalid destination!");
17779 unsigned mainDstReg = MRI.createVirtualRegister(RC);
17780 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17782 MemOpndSlot = CurOp;
17784 MVT PVT = getPointerTy();
17785 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17786 "Invalid Pointer Size!");
17788 // For v = setjmp(buf), we generate
17791 // buf[LabelOffset] = restoreMBB
17792 // SjLjSetup restoreMBB
17798 // v = phi(main, restore)
17803 MachineBasicBlock *thisMBB = MBB;
17804 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17805 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17806 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17807 MF->insert(I, mainMBB);
17808 MF->insert(I, sinkMBB);
17809 MF->push_back(restoreMBB);
17811 MachineInstrBuilder MIB;
17813 // Transfer the remainder of BB and its successor edges to sinkMBB.
17814 sinkMBB->splice(sinkMBB->begin(), MBB,
17815 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17816 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17819 unsigned PtrStoreOpc = 0;
17820 unsigned LabelReg = 0;
17821 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17822 Reloc::Model RM = MF->getTarget().getRelocationModel();
17823 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17824 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17826 // Prepare IP either in reg or imm.
17827 if (!UseImmLabel) {
17828 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17829 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17830 LabelReg = MRI.createVirtualRegister(PtrRC);
17831 if (Subtarget->is64Bit()) {
17832 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17836 .addMBB(restoreMBB)
17839 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17840 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17841 .addReg(XII->getGlobalBaseReg(MF))
17844 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17848 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17850 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17851 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17852 if (i == X86::AddrDisp)
17853 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17855 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17858 MIB.addReg(LabelReg);
17860 MIB.addMBB(restoreMBB);
17861 MIB.setMemRefs(MMOBegin, MMOEnd);
17863 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17864 .addMBB(restoreMBB);
17866 const X86RegisterInfo *RegInfo =
17867 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17868 MIB.addRegMask(RegInfo->getNoPreservedMask());
17869 thisMBB->addSuccessor(mainMBB);
17870 thisMBB->addSuccessor(restoreMBB);
17874 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17875 mainMBB->addSuccessor(sinkMBB);
17878 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17879 TII->get(X86::PHI), DstReg)
17880 .addReg(mainDstReg).addMBB(mainMBB)
17881 .addReg(restoreDstReg).addMBB(restoreMBB);
17884 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17885 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17886 restoreMBB->addSuccessor(sinkMBB);
17888 MI->eraseFromParent();
17892 MachineBasicBlock *
17893 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17894 MachineBasicBlock *MBB) const {
17895 DebugLoc DL = MI->getDebugLoc();
17896 MachineFunction *MF = MBB->getParent();
17897 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17898 MachineRegisterInfo &MRI = MF->getRegInfo();
17900 // Memory Reference
17901 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17902 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17904 MVT PVT = getPointerTy();
17905 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17906 "Invalid Pointer Size!");
17908 const TargetRegisterClass *RC =
17909 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17910 unsigned Tmp = MRI.createVirtualRegister(RC);
17911 // Since FP is only updated here but NOT referenced, it's treated as GPR.
17912 const X86RegisterInfo *RegInfo =
17913 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17914 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17915 unsigned SP = RegInfo->getStackRegister();
17917 MachineInstrBuilder MIB;
17919 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17920 const int64_t SPOffset = 2 * PVT.getStoreSize();
17922 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17923 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17926 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17927 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17928 MIB.addOperand(MI->getOperand(i));
17929 MIB.setMemRefs(MMOBegin, MMOEnd);
17931 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17932 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17933 if (i == X86::AddrDisp)
17934 MIB.addDisp(MI->getOperand(i), LabelOffset);
17936 MIB.addOperand(MI->getOperand(i));
17938 MIB.setMemRefs(MMOBegin, MMOEnd);
17940 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17941 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17942 if (i == X86::AddrDisp)
17943 MIB.addDisp(MI->getOperand(i), SPOffset);
17945 MIB.addOperand(MI->getOperand(i));
17947 MIB.setMemRefs(MMOBegin, MMOEnd);
17949 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17951 MI->eraseFromParent();
17955 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17956 // accumulator loops. Writing back to the accumulator allows the coalescer
17957 // to remove extra copies in the loop.
17958 MachineBasicBlock *
17959 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17960 MachineBasicBlock *MBB) const {
17961 MachineOperand &AddendOp = MI->getOperand(3);
17963 // Bail out early if the addend isn't a register - we can't switch these.
17964 if (!AddendOp.isReg())
17967 MachineFunction &MF = *MBB->getParent();
17968 MachineRegisterInfo &MRI = MF.getRegInfo();
17970 // Check whether the addend is defined by a PHI:
17971 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17972 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17973 if (!AddendDef.isPHI())
17976 // Look for the following pattern:
17978 // %addend = phi [%entry, 0], [%loop, %result]
17980 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17984 // %addend = phi [%entry, 0], [%loop, %result]
17986 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17988 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17989 assert(AddendDef.getOperand(i).isReg());
17990 MachineOperand PHISrcOp = AddendDef.getOperand(i);
17991 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17992 if (&PHISrcInst == MI) {
17993 // Found a matching instruction.
17994 unsigned NewFMAOpc = 0;
17995 switch (MI->getOpcode()) {
17996 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17997 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17998 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17999 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18000 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18001 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18002 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18003 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18004 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18005 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18006 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18007 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18008 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18009 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18010 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18011 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18012 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18013 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18014 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18015 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18016 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18017 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18018 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18019 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18020 default: llvm_unreachable("Unrecognized FMA variant.");
18023 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18024 MachineInstrBuilder MIB =
18025 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18026 .addOperand(MI->getOperand(0))
18027 .addOperand(MI->getOperand(3))
18028 .addOperand(MI->getOperand(2))
18029 .addOperand(MI->getOperand(1));
18030 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18031 MI->eraseFromParent();
18038 MachineBasicBlock *
18039 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18040 MachineBasicBlock *BB) const {
18041 switch (MI->getOpcode()) {
18042 default: llvm_unreachable("Unexpected instr type to insert");
18043 case X86::TAILJMPd64:
18044 case X86::TAILJMPr64:
18045 case X86::TAILJMPm64:
18046 llvm_unreachable("TAILJMP64 would not be touched here.");
18047 case X86::TCRETURNdi64:
18048 case X86::TCRETURNri64:
18049 case X86::TCRETURNmi64:
18051 case X86::WIN_ALLOCA:
18052 return EmitLoweredWinAlloca(MI, BB);
18053 case X86::SEG_ALLOCA_32:
18054 return EmitLoweredSegAlloca(MI, BB, false);
18055 case X86::SEG_ALLOCA_64:
18056 return EmitLoweredSegAlloca(MI, BB, true);
18057 case X86::TLSCall_32:
18058 case X86::TLSCall_64:
18059 return EmitLoweredTLSCall(MI, BB);
18060 case X86::CMOV_GR8:
18061 case X86::CMOV_FR32:
18062 case X86::CMOV_FR64:
18063 case X86::CMOV_V4F32:
18064 case X86::CMOV_V2F64:
18065 case X86::CMOV_V2I64:
18066 case X86::CMOV_V8F32:
18067 case X86::CMOV_V4F64:
18068 case X86::CMOV_V4I64:
18069 case X86::CMOV_V16F32:
18070 case X86::CMOV_V8F64:
18071 case X86::CMOV_V8I64:
18072 case X86::CMOV_GR16:
18073 case X86::CMOV_GR32:
18074 case X86::CMOV_RFP32:
18075 case X86::CMOV_RFP64:
18076 case X86::CMOV_RFP80:
18077 return EmitLoweredSelect(MI, BB);
18079 case X86::FP32_TO_INT16_IN_MEM:
18080 case X86::FP32_TO_INT32_IN_MEM:
18081 case X86::FP32_TO_INT64_IN_MEM:
18082 case X86::FP64_TO_INT16_IN_MEM:
18083 case X86::FP64_TO_INT32_IN_MEM:
18084 case X86::FP64_TO_INT64_IN_MEM:
18085 case X86::FP80_TO_INT16_IN_MEM:
18086 case X86::FP80_TO_INT32_IN_MEM:
18087 case X86::FP80_TO_INT64_IN_MEM: {
18088 MachineFunction *F = BB->getParent();
18089 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18090 DebugLoc DL = MI->getDebugLoc();
18092 // Change the floating point control register to use "round towards zero"
18093 // mode when truncating to an integer value.
18094 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18095 addFrameReference(BuildMI(*BB, MI, DL,
18096 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18098 // Load the old value of the high byte of the control word...
18100 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18101 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18104 // Set the high part to be round to zero...
18105 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18108 // Reload the modified control word now...
18109 addFrameReference(BuildMI(*BB, MI, DL,
18110 TII->get(X86::FLDCW16m)), CWFrameIdx);
18112 // Restore the memory image of control word to original value
18113 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18116 // Get the X86 opcode to use.
18118 switch (MI->getOpcode()) {
18119 default: llvm_unreachable("illegal opcode!");
18120 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18121 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18122 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18123 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18124 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18125 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18126 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18127 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18128 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18132 MachineOperand &Op = MI->getOperand(0);
18134 AM.BaseType = X86AddressMode::RegBase;
18135 AM.Base.Reg = Op.getReg();
18137 AM.BaseType = X86AddressMode::FrameIndexBase;
18138 AM.Base.FrameIndex = Op.getIndex();
18140 Op = MI->getOperand(1);
18142 AM.Scale = Op.getImm();
18143 Op = MI->getOperand(2);
18145 AM.IndexReg = Op.getImm();
18146 Op = MI->getOperand(3);
18147 if (Op.isGlobal()) {
18148 AM.GV = Op.getGlobal();
18150 AM.Disp = Op.getImm();
18152 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18153 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18155 // Reload the original control word now.
18156 addFrameReference(BuildMI(*BB, MI, DL,
18157 TII->get(X86::FLDCW16m)), CWFrameIdx);
18159 MI->eraseFromParent(); // The pseudo instruction is gone now.
18162 // String/text processing lowering.
18163 case X86::PCMPISTRM128REG:
18164 case X86::VPCMPISTRM128REG:
18165 case X86::PCMPISTRM128MEM:
18166 case X86::VPCMPISTRM128MEM:
18167 case X86::PCMPESTRM128REG:
18168 case X86::VPCMPESTRM128REG:
18169 case X86::PCMPESTRM128MEM:
18170 case X86::VPCMPESTRM128MEM:
18171 assert(Subtarget->hasSSE42() &&
18172 "Target must have SSE4.2 or AVX features enabled");
18173 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18175 // String/text processing lowering.
18176 case X86::PCMPISTRIREG:
18177 case X86::VPCMPISTRIREG:
18178 case X86::PCMPISTRIMEM:
18179 case X86::VPCMPISTRIMEM:
18180 case X86::PCMPESTRIREG:
18181 case X86::VPCMPESTRIREG:
18182 case X86::PCMPESTRIMEM:
18183 case X86::VPCMPESTRIMEM:
18184 assert(Subtarget->hasSSE42() &&
18185 "Target must have SSE4.2 or AVX features enabled");
18186 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18188 // Thread synchronization.
18190 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18194 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18196 case X86::VASTART_SAVE_XMM_REGS:
18197 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18199 case X86::VAARG_64:
18200 return EmitVAARG64WithCustomInserter(MI, BB);
18202 case X86::EH_SjLj_SetJmp32:
18203 case X86::EH_SjLj_SetJmp64:
18204 return emitEHSjLjSetJmp(MI, BB);
18206 case X86::EH_SjLj_LongJmp32:
18207 case X86::EH_SjLj_LongJmp64:
18208 return emitEHSjLjLongJmp(MI, BB);
18210 case TargetOpcode::STACKMAP:
18211 case TargetOpcode::PATCHPOINT:
18212 return emitPatchPoint(MI, BB);
18214 case X86::VFMADDPDr213r:
18215 case X86::VFMADDPSr213r:
18216 case X86::VFMADDSDr213r:
18217 case X86::VFMADDSSr213r:
18218 case X86::VFMSUBPDr213r:
18219 case X86::VFMSUBPSr213r:
18220 case X86::VFMSUBSDr213r:
18221 case X86::VFMSUBSSr213r:
18222 case X86::VFNMADDPDr213r:
18223 case X86::VFNMADDPSr213r:
18224 case X86::VFNMADDSDr213r:
18225 case X86::VFNMADDSSr213r:
18226 case X86::VFNMSUBPDr213r:
18227 case X86::VFNMSUBPSr213r:
18228 case X86::VFNMSUBSDr213r:
18229 case X86::VFNMSUBSSr213r:
18230 case X86::VFMADDPDr213rY:
18231 case X86::VFMADDPSr213rY:
18232 case X86::VFMSUBPDr213rY:
18233 case X86::VFMSUBPSr213rY:
18234 case X86::VFNMADDPDr213rY:
18235 case X86::VFNMADDPSr213rY:
18236 case X86::VFNMSUBPDr213rY:
18237 case X86::VFNMSUBPSr213rY:
18238 return emitFMA3Instr(MI, BB);
18242 //===----------------------------------------------------------------------===//
18243 // X86 Optimization Hooks
18244 //===----------------------------------------------------------------------===//
18246 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18249 const SelectionDAG &DAG,
18250 unsigned Depth) const {
18251 unsigned BitWidth = KnownZero.getBitWidth();
18252 unsigned Opc = Op.getOpcode();
18253 assert((Opc >= ISD::BUILTIN_OP_END ||
18254 Opc == ISD::INTRINSIC_WO_CHAIN ||
18255 Opc == ISD::INTRINSIC_W_CHAIN ||
18256 Opc == ISD::INTRINSIC_VOID) &&
18257 "Should use MaskedValueIsZero if you don't know whether Op"
18258 " is a target node!");
18260 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
18274 // These nodes' second result is a boolean.
18275 if (Op.getResNo() == 0)
18278 case X86ISD::SETCC:
18279 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18281 case ISD::INTRINSIC_WO_CHAIN: {
18282 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18283 unsigned NumLoBits = 0;
18286 case Intrinsic::x86_sse_movmsk_ps:
18287 case Intrinsic::x86_avx_movmsk_ps_256:
18288 case Intrinsic::x86_sse2_movmsk_pd:
18289 case Intrinsic::x86_avx_movmsk_pd_256:
18290 case Intrinsic::x86_mmx_pmovmskb:
18291 case Intrinsic::x86_sse2_pmovmskb_128:
18292 case Intrinsic::x86_avx2_pmovmskb: {
18293 // High bits of movmskp{s|d}, pmovmskb are known zero.
18295 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18296 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
18297 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
18298 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
18299 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
18300 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
18301 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
18302 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
18304 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18313 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18315 const SelectionDAG &,
18316 unsigned Depth) const {
18317 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18318 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18319 return Op.getValueType().getScalarType().getSizeInBits();
18325 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18326 /// node is a GlobalAddress + offset.
18327 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18328 const GlobalValue* &GA,
18329 int64_t &Offset) const {
18330 if (N->getOpcode() == X86ISD::Wrapper) {
18331 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18332 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18333 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18337 return TargetLowering::isGAPlusOffset(N, GA, Offset);
18340 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18341 /// same as extracting the high 128-bit part of 256-bit vector and then
18342 /// inserting the result into the low part of a new 256-bit vector
18343 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18344 EVT VT = SVOp->getValueType(0);
18345 unsigned NumElems = VT.getVectorNumElements();
18347 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18348 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18349 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18350 SVOp->getMaskElt(j) >= 0)
18356 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18357 /// same as extracting the low 128-bit part of 256-bit vector and then
18358 /// inserting the result into the high part of a new 256-bit vector
18359 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18360 EVT VT = SVOp->getValueType(0);
18361 unsigned NumElems = VT.getVectorNumElements();
18363 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18364 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18365 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18366 SVOp->getMaskElt(j) >= 0)
18372 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18373 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18374 TargetLowering::DAGCombinerInfo &DCI,
18375 const X86Subtarget* Subtarget) {
18377 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18378 SDValue V1 = SVOp->getOperand(0);
18379 SDValue V2 = SVOp->getOperand(1);
18380 EVT VT = SVOp->getValueType(0);
18381 unsigned NumElems = VT.getVectorNumElements();
18383 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18384 V2.getOpcode() == ISD::CONCAT_VECTORS) {
18388 // V UNDEF BUILD_VECTOR UNDEF
18390 // CONCAT_VECTOR CONCAT_VECTOR
18393 // RESULT: V + zero extended
18395 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18396 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18397 V1.getOperand(1).getOpcode() != ISD::UNDEF)
18400 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18403 // To match the shuffle mask, the first half of the mask should
18404 // be exactly the first vector, and all the rest a splat with the
18405 // first element of the second one.
18406 for (unsigned i = 0; i != NumElems/2; ++i)
18407 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18408 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18411 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18412 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18413 if (Ld->hasNUsesOfValue(1, 0)) {
18414 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18415 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18417 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18419 Ld->getPointerInfo(),
18420 Ld->getAlignment(),
18421 false/*isVolatile*/, true/*ReadMem*/,
18422 false/*WriteMem*/);
18424 // Make sure the newly-created LOAD is in the same position as Ld in
18425 // terms of dependency. We create a TokenFactor for Ld and ResNode,
18426 // and update uses of Ld's output chain to use the TokenFactor.
18427 if (Ld->hasAnyUseOfValue(1)) {
18428 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18429 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18430 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18431 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18432 SDValue(ResNode.getNode(), 1));
18435 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18439 // Emit a zeroed vector and insert the desired subvector on its
18441 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18442 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18443 return DCI.CombineTo(N, InsV);
18446 //===--------------------------------------------------------------------===//
18447 // Combine some shuffles into subvector extracts and inserts:
18450 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18451 if (isShuffleHigh128VectorInsertLow(SVOp)) {
18452 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18453 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18454 return DCI.CombineTo(N, InsV);
18457 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18458 if (isShuffleLow128VectorInsertHigh(SVOp)) {
18459 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18460 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18461 return DCI.CombineTo(N, InsV);
18467 /// \brief Get the PSHUF-style mask from PSHUF node.
18469 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18470 /// PSHUF-style masks that can be reused with such instructions.
18471 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18472 SmallVector<int, 4> Mask;
18474 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18478 switch (N.getOpcode()) {
18479 case X86ISD::PSHUFD:
18481 case X86ISD::PSHUFLW:
18484 case X86ISD::PSHUFHW:
18485 Mask.erase(Mask.begin(), Mask.begin() + 4);
18486 for (int &M : Mask)
18490 llvm_unreachable("No valid shuffle instruction found!");
18494 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18496 /// We walk up the chain and look for a combinable shuffle, skipping over
18497 /// shuffles that we could hoist this shuffle's transformation past without
18498 /// altering anything.
18499 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18501 TargetLowering::DAGCombinerInfo &DCI) {
18502 assert(N.getOpcode() == X86ISD::PSHUFD &&
18503 "Called with something other than an x86 128-bit half shuffle!");
18506 // Walk up a single-use chain looking for a combinable shuffle.
18507 SDValue V = N.getOperand(0);
18508 for (; V.hasOneUse(); V = V.getOperand(0)) {
18509 switch (V.getOpcode()) {
18511 return false; // Nothing combined!
18514 // Skip bitcasts as we always know the type for the target specific
18518 case X86ISD::PSHUFD:
18519 // Found another dword shuffle.
18522 case X86ISD::PSHUFLW:
18523 // Check that the low words (being shuffled) are the identity in the
18524 // dword shuffle, and the high words are self-contained.
18525 if (Mask[0] != 0 || Mask[1] != 1 ||
18526 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
18531 case X86ISD::PSHUFHW:
18532 // Check that the high words (being shuffled) are the identity in the
18533 // dword shuffle, and the low words are self-contained.
18534 if (Mask[2] != 2 || Mask[3] != 3 ||
18535 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
18540 case X86ISD::UNPCKL:
18541 case X86ISD::UNPCKH:
18542 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
18543 // shuffle into a preceding word shuffle.
18544 if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
18547 // Search for a half-shuffle which we can combine with.
18548 unsigned CombineOp =
18549 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18550 if (V.getOperand(0) != V.getOperand(1) ||
18551 !V->isOnlyUserOf(V.getOperand(0).getNode()))
18553 V = V.getOperand(0);
18555 switch (V.getOpcode()) {
18557 return false; // Nothing to combine.
18559 case X86ISD::PSHUFLW:
18560 case X86ISD::PSHUFHW:
18561 if (V.getOpcode() == CombineOp)
18566 V = V.getOperand(0);
18570 } while (V.hasOneUse());
18573 // Break out of the loop if we break out of the switch.
18577 if (!V.hasOneUse())
18578 // We fell out of the loop without finding a viable combining instruction.
18581 // Record the old value to use in RAUW-ing.
18584 // Merge this node's mask and our incoming mask.
18585 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18586 for (int &M : Mask)
18588 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
18589 getV4X86ShuffleImm8ForMask(Mask, DAG));
18591 // It is possible that one of the combinable shuffles was completely absorbed
18592 // by the other, just replace it and revisit all users in that case.
18593 if (Old.getNode() == V.getNode()) {
18594 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
18598 // Replace N with its operand as we're going to combine that shuffle away.
18599 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18601 // Replace the combinable shuffle with the combined one, updating all users
18602 // so that we re-evaluate the chain here.
18603 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18607 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
18609 /// We walk up the chain, skipping shuffles of the other half and looking
18610 /// through shuffles which switch halves trying to find a shuffle of the same
18611 /// pair of dwords.
18612 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
18614 TargetLowering::DAGCombinerInfo &DCI) {
18616 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
18617 "Called with something other than an x86 128-bit half shuffle!");
18619 unsigned CombineOpcode = N.getOpcode();
18621 // Walk up a single-use chain looking for a combinable shuffle.
18622 SDValue V = N.getOperand(0);
18623 for (; V.hasOneUse(); V = V.getOperand(0)) {
18624 switch (V.getOpcode()) {
18626 return false; // Nothing combined!
18629 // Skip bitcasts as we always know the type for the target specific
18633 case X86ISD::PSHUFLW:
18634 case X86ISD::PSHUFHW:
18635 if (V.getOpcode() == CombineOpcode)
18638 // Other-half shuffles are no-ops.
18641 case X86ISD::PSHUFD: {
18642 // We can only handle pshufd if the half we are combining either stays in
18643 // its half, or switches to the other half. Bail if one of these isn't
18645 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18646 int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
18647 if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
18648 (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
18651 // Map the mask through the pshufd and keep walking up the chain.
18652 for (int i = 0; i < 4; ++i)
18653 Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
18655 // Switch halves if the pshufd does.
18657 VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18661 // Break out of the loop if we break out of the switch.
18665 if (!V.hasOneUse())
18666 // We fell out of the loop without finding a viable combining instruction.
18669 // Record the old value to use in RAUW-ing.
18672 // Merge this node's mask and our incoming mask (adjusted to account for all
18673 // the pshufd instructions encountered).
18674 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18675 for (int &M : Mask)
18677 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
18678 getV4X86ShuffleImm8ForMask(Mask, DAG));
18680 // Replace N with its operand as we're going to combine that shuffle away.
18681 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18683 // Replace the combinable shuffle with the combined one, updating all users
18684 // so that we re-evaluate the chain here.
18685 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18689 /// \brief Try to combine x86 target specific shuffles.
18690 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
18691 TargetLowering::DAGCombinerInfo &DCI,
18692 const X86Subtarget *Subtarget) {
18694 MVT VT = N.getSimpleValueType();
18695 SmallVector<int, 4> Mask;
18697 switch (N.getOpcode()) {
18698 case X86ISD::PSHUFD:
18699 case X86ISD::PSHUFLW:
18700 case X86ISD::PSHUFHW:
18701 Mask = getPSHUFShuffleMask(N);
18702 assert(Mask.size() == 4);
18708 // Nuke no-op shuffles that show up after combining.
18709 if (isNoopShuffleMask(Mask))
18710 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
18712 // Look for simplifications involving one or two shuffle instructions.
18713 SDValue V = N.getOperand(0);
18714 switch (N.getOpcode()) {
18717 case X86ISD::PSHUFLW:
18718 case X86ISD::PSHUFHW:
18719 assert(VT == MVT::v8i16);
18722 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
18723 return SDValue(); // We combined away this shuffle, so we're done.
18725 // See if this reduces to a PSHUFD which is no more expensive and can
18726 // combine with more operations.
18727 if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
18728 areAdjacentMasksSequential(Mask)) {
18729 int DMask[] = {-1, -1, -1, -1};
18730 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
18731 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
18732 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
18733 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
18734 DCI.AddToWorklist(V.getNode());
18735 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
18736 getV4X86ShuffleImm8ForMask(DMask, DAG));
18737 DCI.AddToWorklist(V.getNode());
18738 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
18741 // Look for shuffle patterns which can be implemented as a single unpack.
18742 // FIXME: This doesn't handle the location of the PSHUFD generically, and
18743 // only works when we have a PSHUFD followed by two half-shuffles.
18744 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
18745 (V.getOpcode() == X86ISD::PSHUFLW ||
18746 V.getOpcode() == X86ISD::PSHUFHW) &&
18747 V.getOpcode() != N.getOpcode() &&
18749 SDValue D = V.getOperand(0);
18750 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
18751 D = D.getOperand(0);
18752 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
18753 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18754 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
18755 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
18756 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
18758 for (int i = 0; i < 4; ++i) {
18759 WordMask[i + NOffset] = Mask[i] + NOffset;
18760 WordMask[i + VOffset] = VMask[i] + VOffset;
18762 // Map the word mask through the DWord mask.
18764 for (int i = 0; i < 8; ++i)
18765 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
18766 const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
18767 const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
18768 if (std::equal(std::begin(MappedMask), std::end(MappedMask),
18769 std::begin(UnpackLoMask)) ||
18770 std::equal(std::begin(MappedMask), std::end(MappedMask),
18771 std::begin(UnpackHiMask))) {
18772 // We can replace all three shuffles with an unpack.
18773 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
18774 DCI.AddToWorklist(V.getNode());
18775 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
18777 DL, MVT::v8i16, V, V);
18784 case X86ISD::PSHUFD:
18785 if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
18786 return SDValue(); // We combined away this shuffle.
18794 /// PerformShuffleCombine - Performs several different shuffle combines.
18795 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
18796 TargetLowering::DAGCombinerInfo &DCI,
18797 const X86Subtarget *Subtarget) {
18799 SDValue N0 = N->getOperand(0);
18800 SDValue N1 = N->getOperand(1);
18801 EVT VT = N->getValueType(0);
18803 // Canonicalize shuffles that perform 'addsub' on packed float vectors
18804 // according to the rule:
18805 // (shuffle (FADD A, B), (FSUB A, B), Mask) ->
18806 // (shuffle (FSUB A, -B), (FADD A, -B), Mask)
18808 // Where 'Mask' is:
18809 // <0,5,2,7> -- for v4f32 and v4f64 shuffles;
18810 // <0,3> -- for v2f64 shuffles;
18811 // <0,9,2,11,4,13,6,15> -- for v8f32 shuffles.
18813 // This helps pattern-matching more SSE3/AVX ADDSUB instructions
18814 // during ISel stage.
18815 if (N->getOpcode() == ISD::VECTOR_SHUFFLE &&
18816 ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18817 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18818 N0->getOpcode() == ISD::FADD && N1->getOpcode() == ISD::FSUB &&
18819 // Operands to the FADD and FSUB must be the same.
18820 ((N0->getOperand(0) == N1->getOperand(0) &&
18821 N0->getOperand(1) == N1->getOperand(1)) ||
18822 // FADD is commutable. See if by commuting the operands of the FADD
18823 // we would still be able to match the operands of the FSUB dag node.
18824 (N0->getOperand(1) == N1->getOperand(0) &&
18825 N0->getOperand(0) == N1->getOperand(1))) &&
18826 N0->getOperand(0)->getOpcode() != ISD::UNDEF &&
18827 N0->getOperand(1)->getOpcode() != ISD::UNDEF) {
18829 ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
18830 unsigned NumElts = VT.getVectorNumElements();
18831 ArrayRef<int> Mask = SV->getMask();
18832 bool CanFold = true;
18834 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i)
18835 CanFold = Mask[i] == (int)((i & 1) ? i + NumElts : i);
18838 SDValue Op0 = N1->getOperand(0);
18839 SDValue Op1 = DAG.getNode(ISD::FNEG, dl, VT, N1->getOperand(1));
18840 SDValue Sub = DAG.getNode(ISD::FSUB, dl, VT, Op0, Op1);
18841 SDValue Add = DAG.getNode(ISD::FADD, dl, VT, Op0, Op1);
18842 return DAG.getVectorShuffle(VT, dl, Sub, Add, Mask);
18846 // Don't create instructions with illegal types after legalize types has run.
18847 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18848 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
18851 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
18852 if (Subtarget->hasFp256() && VT.is256BitVector() &&
18853 N->getOpcode() == ISD::VECTOR_SHUFFLE)
18854 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
18856 // During Type Legalization, when promoting illegal vector types,
18857 // the backend might introduce new shuffle dag nodes and bitcasts.
18859 // This code performs the following transformation:
18860 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
18861 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
18863 // We do this only if both the bitcast and the BINOP dag nodes have
18864 // one use. Also, perform this transformation only if the new binary
18865 // operation is legal. This is to avoid introducing dag nodes that
18866 // potentially need to be further expanded (or custom lowered) into a
18867 // less optimal sequence of dag nodes.
18868 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
18869 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
18870 N0.getOpcode() == ISD::BITCAST) {
18871 SDValue BC0 = N0.getOperand(0);
18872 EVT SVT = BC0.getValueType();
18873 unsigned Opcode = BC0.getOpcode();
18874 unsigned NumElts = VT.getVectorNumElements();
18876 if (BC0.hasOneUse() && SVT.isVector() &&
18877 SVT.getVectorNumElements() * 2 == NumElts &&
18878 TLI.isOperationLegal(Opcode, VT)) {
18879 bool CanFold = false;
18891 unsigned SVTNumElts = SVT.getVectorNumElements();
18892 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18893 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
18894 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
18895 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
18896 CanFold = SVOp->getMaskElt(i) < 0;
18899 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
18900 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
18901 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
18902 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
18907 // Only handle 128 wide vector from here on.
18908 if (!VT.is128BitVector())
18911 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
18912 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
18913 // consecutive, non-overlapping, and in the right order.
18914 SmallVector<SDValue, 16> Elts;
18915 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
18916 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
18918 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
18922 if (isTargetShuffle(N->getOpcode())) {
18924 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
18925 if (Shuffle.getNode())
18932 /// PerformTruncateCombine - Converts truncate operation to
18933 /// a sequence of vector shuffle operations.
18934 /// It is possible when we truncate 256-bit vector to 128-bit vector
18935 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
18936 TargetLowering::DAGCombinerInfo &DCI,
18937 const X86Subtarget *Subtarget) {
18941 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
18942 /// specific shuffle of a load can be folded into a single element load.
18943 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
18944 /// shuffles have been customed lowered so we need to handle those here.
18945 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
18946 TargetLowering::DAGCombinerInfo &DCI) {
18947 if (DCI.isBeforeLegalizeOps())
18950 SDValue InVec = N->getOperand(0);
18951 SDValue EltNo = N->getOperand(1);
18953 if (!isa<ConstantSDNode>(EltNo))
18956 EVT VT = InVec.getValueType();
18958 bool HasShuffleIntoBitcast = false;
18959 if (InVec.getOpcode() == ISD::BITCAST) {
18960 // Don't duplicate a load with other uses.
18961 if (!InVec.hasOneUse())
18963 EVT BCVT = InVec.getOperand(0).getValueType();
18964 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
18966 InVec = InVec.getOperand(0);
18967 HasShuffleIntoBitcast = true;
18970 if (!isTargetShuffle(InVec.getOpcode()))
18973 // Don't duplicate a load with other uses.
18974 if (!InVec.hasOneUse())
18977 SmallVector<int, 16> ShuffleMask;
18979 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18983 // Select the input vector, guarding against out of range extract vector.
18984 unsigned NumElems = VT.getVectorNumElements();
18985 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18986 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18987 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18988 : InVec.getOperand(1);
18990 // If inputs to shuffle are the same for both ops, then allow 2 uses
18991 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18993 if (LdNode.getOpcode() == ISD::BITCAST) {
18994 // Don't duplicate a load with other uses.
18995 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18998 AllowedUses = 1; // only allow 1 load use if we have a bitcast
18999 LdNode = LdNode.getOperand(0);
19002 if (!ISD::isNormalLoad(LdNode.getNode()))
19005 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19007 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19010 if (HasShuffleIntoBitcast) {
19011 // If there's a bitcast before the shuffle, check if the load type and
19012 // alignment is valid.
19013 unsigned Align = LN0->getAlignment();
19014 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19015 unsigned NewAlign = TLI.getDataLayout()->
19016 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19018 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19022 // All checks match so transform back to vector_shuffle so that DAG combiner
19023 // can finish the job
19026 // Create shuffle node taking into account the case that its a unary shuffle
19027 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19028 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19029 InVec.getOperand(0), Shuffle,
19031 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19032 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19036 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19037 /// generation and convert it from being a bunch of shuffles and extracts
19038 /// to a simple store and scalar loads to extract the elements.
19039 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19040 TargetLowering::DAGCombinerInfo &DCI) {
19041 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19042 if (NewOp.getNode())
19045 SDValue InputVector = N->getOperand(0);
19047 // Detect whether we are trying to convert from mmx to i32 and the bitcast
19048 // from mmx to v2i32 has a single usage.
19049 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19050 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19051 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19052 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19053 N->getValueType(0),
19054 InputVector.getNode()->getOperand(0));
19056 // Only operate on vectors of 4 elements, where the alternative shuffling
19057 // gets to be more expensive.
19058 if (InputVector.getValueType() != MVT::v4i32)
19061 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19062 // single use which is a sign-extend or zero-extend, and all elements are
19064 SmallVector<SDNode *, 4> Uses;
19065 unsigned ExtractedElements = 0;
19066 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19067 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19068 if (UI.getUse().getResNo() != InputVector.getResNo())
19071 SDNode *Extract = *UI;
19072 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19075 if (Extract->getValueType(0) != MVT::i32)
19077 if (!Extract->hasOneUse())
19079 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19080 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19082 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19085 // Record which element was extracted.
19086 ExtractedElements |=
19087 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19089 Uses.push_back(Extract);
19092 // If not all the elements were used, this may not be worthwhile.
19093 if (ExtractedElements != 15)
19096 // Ok, we've now decided to do the transformation.
19097 SDLoc dl(InputVector);
19099 // Store the value to a temporary stack slot.
19100 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19101 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19102 MachinePointerInfo(), false, false, 0);
19104 // Replace each use (extract) with a load of the appropriate element.
19105 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19106 UE = Uses.end(); UI != UE; ++UI) {
19107 SDNode *Extract = *UI;
19109 // cOMpute the element's address.
19110 SDValue Idx = Extract->getOperand(1);
19112 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19113 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19114 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19115 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19117 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19118 StackPtr, OffsetVal);
19120 // Load the scalar.
19121 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19122 ScalarAddr, MachinePointerInfo(),
19123 false, false, false, 0);
19125 // Replace the exact with the load.
19126 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19129 // The replacement was made in place; don't return anything.
19133 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19134 static std::pair<unsigned, bool>
19135 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19136 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19137 if (!VT.isVector())
19138 return std::make_pair(0, false);
19140 bool NeedSplit = false;
19141 switch (VT.getSimpleVT().SimpleTy) {
19142 default: return std::make_pair(0, false);
19146 if (!Subtarget->hasAVX2())
19148 if (!Subtarget->hasAVX())
19149 return std::make_pair(0, false);
19154 if (!Subtarget->hasSSE2())
19155 return std::make_pair(0, false);
19158 // SSE2 has only a small subset of the operations.
19159 bool hasUnsigned = Subtarget->hasSSE41() ||
19160 (Subtarget->hasSSE2() && VT == MVT::v16i8);
19161 bool hasSigned = Subtarget->hasSSE41() ||
19162 (Subtarget->hasSSE2() && VT == MVT::v8i16);
19164 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19167 // Check for x CC y ? x : y.
19168 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19169 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19174 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19177 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19180 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19183 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19185 // Check for x CC y ? y : x -- a min/max with reversed arms.
19186 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19187 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19192 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19195 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19198 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19201 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19205 return std::make_pair(Opc, NeedSplit);
19209 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19210 const X86Subtarget *Subtarget) {
19212 SDValue Cond = N->getOperand(0);
19213 SDValue LHS = N->getOperand(1);
19214 SDValue RHS = N->getOperand(2);
19216 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19217 SDValue CondSrc = Cond->getOperand(0);
19218 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19219 Cond = CondSrc->getOperand(0);
19222 MVT VT = N->getSimpleValueType(0);
19223 MVT EltVT = VT.getVectorElementType();
19224 unsigned NumElems = VT.getVectorNumElements();
19225 // There is no blend with immediate in AVX-512.
19226 if (VT.is512BitVector())
19229 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19231 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19234 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19237 unsigned MaskValue = 0;
19238 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19241 SmallVector<int, 8> ShuffleMask(NumElems, -1);
19242 for (unsigned i = 0; i < NumElems; ++i) {
19243 // Be sure we emit undef where we can.
19244 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19245 ShuffleMask[i] = -1;
19247 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19250 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19253 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19255 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19256 TargetLowering::DAGCombinerInfo &DCI,
19257 const X86Subtarget *Subtarget) {
19259 SDValue Cond = N->getOperand(0);
19260 // Get the LHS/RHS of the select.
19261 SDValue LHS = N->getOperand(1);
19262 SDValue RHS = N->getOperand(2);
19263 EVT VT = LHS.getValueType();
19264 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19266 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19267 // instructions match the semantics of the common C idiom x<y?x:y but not
19268 // x<=y?x:y, because of how they handle negative zero (which can be
19269 // ignored in unsafe-math mode).
19270 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19271 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19272 (Subtarget->hasSSE2() ||
19273 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19274 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19276 unsigned Opcode = 0;
19277 // Check for x CC y ? x : y.
19278 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19279 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19283 // Converting this to a min would handle NaNs incorrectly, and swapping
19284 // the operands would cause it to handle comparisons between positive
19285 // and negative zero incorrectly.
19286 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19287 if (!DAG.getTarget().Options.UnsafeFPMath &&
19288 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19290 std::swap(LHS, RHS);
19292 Opcode = X86ISD::FMIN;
19295 // Converting this to a min would handle comparisons between positive
19296 // and negative zero incorrectly.
19297 if (!DAG.getTarget().Options.UnsafeFPMath &&
19298 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19300 Opcode = X86ISD::FMIN;
19303 // Converting this to a min would handle both negative zeros and NaNs
19304 // incorrectly, but we can swap the operands to fix both.
19305 std::swap(LHS, RHS);
19309 Opcode = X86ISD::FMIN;
19313 // Converting this to a max would handle comparisons between positive
19314 // and negative zero incorrectly.
19315 if (!DAG.getTarget().Options.UnsafeFPMath &&
19316 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19318 Opcode = X86ISD::FMAX;
19321 // Converting this to a max would handle NaNs incorrectly, and swapping
19322 // the operands would cause it to handle comparisons between positive
19323 // and negative zero incorrectly.
19324 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19325 if (!DAG.getTarget().Options.UnsafeFPMath &&
19326 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19328 std::swap(LHS, RHS);
19330 Opcode = X86ISD::FMAX;
19333 // Converting this to a max would handle both negative zeros and NaNs
19334 // incorrectly, but we can swap the operands to fix both.
19335 std::swap(LHS, RHS);
19339 Opcode = X86ISD::FMAX;
19342 // Check for x CC y ? y : x -- a min/max with reversed arms.
19343 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19344 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19348 // Converting this to a min would handle comparisons between positive
19349 // and negative zero incorrectly, and swapping the operands would
19350 // cause it to handle NaNs incorrectly.
19351 if (!DAG.getTarget().Options.UnsafeFPMath &&
19352 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19353 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19355 std::swap(LHS, RHS);
19357 Opcode = X86ISD::FMIN;
19360 // Converting this to a min would handle NaNs incorrectly.
19361 if (!DAG.getTarget().Options.UnsafeFPMath &&
19362 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19364 Opcode = X86ISD::FMIN;
19367 // Converting this to a min would handle both negative zeros and NaNs
19368 // incorrectly, but we can swap the operands to fix both.
19369 std::swap(LHS, RHS);
19373 Opcode = X86ISD::FMIN;
19377 // Converting this to a max would handle NaNs incorrectly.
19378 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19380 Opcode = X86ISD::FMAX;
19383 // Converting this to a max would handle comparisons between positive
19384 // and negative zero incorrectly, and swapping the operands would
19385 // cause it to handle NaNs incorrectly.
19386 if (!DAG.getTarget().Options.UnsafeFPMath &&
19387 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19388 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19390 std::swap(LHS, RHS);
19392 Opcode = X86ISD::FMAX;
19395 // Converting this to a max would handle both negative zeros and NaNs
19396 // incorrectly, but we can swap the operands to fix both.
19397 std::swap(LHS, RHS);
19401 Opcode = X86ISD::FMAX;
19407 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19410 EVT CondVT = Cond.getValueType();
19411 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19412 CondVT.getVectorElementType() == MVT::i1) {
19413 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19414 // lowering on AVX-512. In this case we convert it to
19415 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19416 // The same situation for all 128 and 256-bit vectors of i8 and i16
19417 EVT OpVT = LHS.getValueType();
19418 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19419 (OpVT.getVectorElementType() == MVT::i8 ||
19420 OpVT.getVectorElementType() == MVT::i16)) {
19421 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19422 DCI.AddToWorklist(Cond.getNode());
19423 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19426 // If this is a select between two integer constants, try to do some
19428 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19429 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19430 // Don't do this for crazy integer types.
19431 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19432 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19433 // so that TrueC (the true value) is larger than FalseC.
19434 bool NeedsCondInvert = false;
19436 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19437 // Efficiently invertible.
19438 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
19439 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
19440 isa<ConstantSDNode>(Cond.getOperand(1))))) {
19441 NeedsCondInvert = true;
19442 std::swap(TrueC, FalseC);
19445 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
19446 if (FalseC->getAPIntValue() == 0 &&
19447 TrueC->getAPIntValue().isPowerOf2()) {
19448 if (NeedsCondInvert) // Invert the condition if needed.
19449 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19450 DAG.getConstant(1, Cond.getValueType()));
19452 // Zero extend the condition if needed.
19453 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19455 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19456 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19457 DAG.getConstant(ShAmt, MVT::i8));
19460 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19461 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19462 if (NeedsCondInvert) // Invert the condition if needed.
19463 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19464 DAG.getConstant(1, Cond.getValueType()));
19466 // Zero extend the condition if needed.
19467 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19468 FalseC->getValueType(0), Cond);
19469 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19470 SDValue(FalseC, 0));
19473 // Optimize cases that will turn into an LEA instruction. This requires
19474 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19475 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19476 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19477 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19479 bool isFastMultiplier = false;
19481 switch ((unsigned char)Diff) {
19483 case 1: // result = add base, cond
19484 case 2: // result = lea base( , cond*2)
19485 case 3: // result = lea base(cond, cond*2)
19486 case 4: // result = lea base( , cond*4)
19487 case 5: // result = lea base(cond, cond*4)
19488 case 8: // result = lea base( , cond*8)
19489 case 9: // result = lea base(cond, cond*8)
19490 isFastMultiplier = true;
19495 if (isFastMultiplier) {
19496 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19497 if (NeedsCondInvert) // Invert the condition if needed.
19498 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19499 DAG.getConstant(1, Cond.getValueType()));
19501 // Zero extend the condition if needed.
19502 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19504 // Scale the condition by the difference.
19506 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19507 DAG.getConstant(Diff, Cond.getValueType()));
19509 // Add the base if non-zero.
19510 if (FalseC->getAPIntValue() != 0)
19511 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19512 SDValue(FalseC, 0));
19519 // Canonicalize max and min:
19520 // (x > y) ? x : y -> (x >= y) ? x : y
19521 // (x < y) ? x : y -> (x <= y) ? x : y
19522 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19523 // the need for an extra compare
19524 // against zero. e.g.
19525 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19527 // testl %edi, %edi
19529 // cmovgl %edi, %eax
19533 // cmovsl %eax, %edi
19534 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19535 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19536 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19537 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19542 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19543 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19544 Cond.getOperand(0), Cond.getOperand(1), NewCC);
19545 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19550 // Early exit check
19551 if (!TLI.isTypeLegal(VT))
19554 // Match VSELECTs into subs with unsigned saturation.
19555 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19556 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
19557 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
19558 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
19559 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19561 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
19562 // left side invert the predicate to simplify logic below.
19564 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
19566 CC = ISD::getSetCCInverse(CC, true);
19567 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
19571 if (Other.getNode() && Other->getNumOperands() == 2 &&
19572 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
19573 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
19574 SDValue CondRHS = Cond->getOperand(1);
19576 // Look for a general sub with unsigned saturation first.
19577 // x >= y ? x-y : 0 --> subus x, y
19578 // x > y ? x-y : 0 --> subus x, y
19579 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
19580 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
19581 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19583 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
19584 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
19585 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
19586 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
19587 // If the RHS is a constant we have to reverse the const
19588 // canonicalization.
19589 // x > C-1 ? x+-C : 0 --> subus x, C
19590 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
19591 CondRHSConst->getAPIntValue() ==
19592 (-OpRHSConst->getAPIntValue() - 1))
19593 return DAG.getNode(
19594 X86ISD::SUBUS, DL, VT, OpLHS,
19595 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
19597 // Another special case: If C was a sign bit, the sub has been
19598 // canonicalized into a xor.
19599 // FIXME: Would it be better to use computeKnownBits to determine
19600 // whether it's safe to decanonicalize the xor?
19601 // x s< 0 ? x^C : 0 --> subus x, C
19602 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
19603 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
19604 OpRHSConst->getAPIntValue().isSignBit())
19605 // Note that we have to rebuild the RHS constant here to ensure we
19606 // don't rely on particular values of undef lanes.
19607 return DAG.getNode(
19608 X86ISD::SUBUS, DL, VT, OpLHS,
19609 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
19614 // Try to match a min/max vector operation.
19615 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
19616 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
19617 unsigned Opc = ret.first;
19618 bool NeedSplit = ret.second;
19620 if (Opc && NeedSplit) {
19621 unsigned NumElems = VT.getVectorNumElements();
19622 // Extract the LHS vectors
19623 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
19624 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
19626 // Extract the RHS vectors
19627 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
19628 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
19630 // Create min/max for each subvector
19631 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
19632 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
19634 // Merge the result
19635 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
19637 return DAG.getNode(Opc, DL, VT, LHS, RHS);
19640 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
19641 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19642 // Check if SETCC has already been promoted
19643 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
19644 // Check that condition value type matches vselect operand type
19647 assert(Cond.getValueType().isVector() &&
19648 "vector select expects a vector selector!");
19650 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
19651 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
19653 if (!TValIsAllOnes && !FValIsAllZeros) {
19654 // Try invert the condition if true value is not all 1s and false value
19656 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
19657 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
19659 if (TValIsAllZeros || FValIsAllOnes) {
19660 SDValue CC = Cond.getOperand(2);
19661 ISD::CondCode NewCC =
19662 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
19663 Cond.getOperand(0).getValueType().isInteger());
19664 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
19665 std::swap(LHS, RHS);
19666 TValIsAllOnes = FValIsAllOnes;
19667 FValIsAllZeros = TValIsAllZeros;
19671 if (TValIsAllOnes || FValIsAllZeros) {
19674 if (TValIsAllOnes && FValIsAllZeros)
19676 else if (TValIsAllOnes)
19677 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
19678 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
19679 else if (FValIsAllZeros)
19680 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
19681 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
19683 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
19687 // Try to fold this VSELECT into a MOVSS/MOVSD
19688 if (N->getOpcode() == ISD::VSELECT &&
19689 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
19690 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
19691 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
19692 bool CanFold = false;
19693 unsigned NumElems = Cond.getNumOperands();
19697 if (isZero(Cond.getOperand(0))) {
19700 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
19701 // fold (vselect <0,-1> -> (movsd A, B)
19702 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19703 CanFold = isAllOnes(Cond.getOperand(i));
19704 } else if (isAllOnes(Cond.getOperand(0))) {
19708 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
19709 // fold (vselect <-1,0> -> (movsd B, A)
19710 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19711 CanFold = isZero(Cond.getOperand(i));
19715 if (VT == MVT::v4i32 || VT == MVT::v4f32)
19716 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
19717 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
19720 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
19721 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
19722 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
19723 // (v2i64 (bitcast B)))))
19725 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
19726 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
19727 // (v2f64 (bitcast B)))))
19729 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
19730 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
19731 // (v2i64 (bitcast A)))))
19733 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
19734 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
19735 // (v2f64 (bitcast A)))))
19737 CanFold = (isZero(Cond.getOperand(0)) &&
19738 isZero(Cond.getOperand(1)) &&
19739 isAllOnes(Cond.getOperand(2)) &&
19740 isAllOnes(Cond.getOperand(3)));
19742 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
19743 isAllOnes(Cond.getOperand(1)) &&
19744 isZero(Cond.getOperand(2)) &&
19745 isZero(Cond.getOperand(3))) {
19747 std::swap(LHS, RHS);
19751 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
19752 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
19753 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
19754 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
19756 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
19762 // If we know that this node is legal then we know that it is going to be
19763 // matched by one of the SSE/AVX BLEND instructions. These instructions only
19764 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
19765 // to simplify previous instructions.
19766 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
19767 !DCI.isBeforeLegalize() &&
19768 // We explicitly check against v8i16 and v16i16 because, although
19769 // they're marked as Custom, they might only be legal when Cond is a
19770 // build_vector of constants. This will be taken care in a later
19772 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
19773 VT != MVT::v8i16)) {
19774 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
19776 // Don't optimize vector selects that map to mask-registers.
19780 // Check all uses of that condition operand to check whether it will be
19781 // consumed by non-BLEND instructions, which may depend on all bits are set
19783 for (SDNode::use_iterator I = Cond->use_begin(),
19784 E = Cond->use_end(); I != E; ++I)
19785 if (I->getOpcode() != ISD::VSELECT)
19786 // TODO: Add other opcodes eventually lowered into BLEND.
19789 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
19790 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
19792 APInt KnownZero, KnownOne;
19793 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
19794 DCI.isBeforeLegalizeOps());
19795 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
19796 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
19797 DCI.CommitTargetLoweringOpt(TLO);
19800 // We should generate an X86ISD::BLENDI from a vselect if its argument
19801 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
19802 // constants. This specific pattern gets generated when we split a
19803 // selector for a 512 bit vector in a machine without AVX512 (but with
19804 // 256-bit vectors), during legalization:
19806 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
19808 // Iff we find this pattern and the build_vectors are built from
19809 // constants, we translate the vselect into a shuffle_vector that we
19810 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
19811 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
19812 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
19813 if (Shuffle.getNode())
19820 // Check whether a boolean test is testing a boolean value generated by
19821 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
19824 // Simplify the following patterns:
19825 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
19826 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
19827 // to (Op EFLAGS Cond)
19829 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
19830 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
19831 // to (Op EFLAGS !Cond)
19833 // where Op could be BRCOND or CMOV.
19835 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
19836 // Quit if not CMP and SUB with its value result used.
19837 if (Cmp.getOpcode() != X86ISD::CMP &&
19838 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
19841 // Quit if not used as a boolean value.
19842 if (CC != X86::COND_E && CC != X86::COND_NE)
19845 // Check CMP operands. One of them should be 0 or 1 and the other should be
19846 // an SetCC or extended from it.
19847 SDValue Op1 = Cmp.getOperand(0);
19848 SDValue Op2 = Cmp.getOperand(1);
19851 const ConstantSDNode* C = nullptr;
19852 bool needOppositeCond = (CC == X86::COND_E);
19853 bool checkAgainstTrue = false; // Is it a comparison against 1?
19855 if ((C = dyn_cast<ConstantSDNode>(Op1)))
19857 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
19859 else // Quit if all operands are not constants.
19862 if (C->getZExtValue() == 1) {
19863 needOppositeCond = !needOppositeCond;
19864 checkAgainstTrue = true;
19865 } else if (C->getZExtValue() != 0)
19866 // Quit if the constant is neither 0 or 1.
19869 bool truncatedToBoolWithAnd = false;
19870 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
19871 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
19872 SetCC.getOpcode() == ISD::TRUNCATE ||
19873 SetCC.getOpcode() == ISD::AND) {
19874 if (SetCC.getOpcode() == ISD::AND) {
19876 ConstantSDNode *CS;
19877 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
19878 CS->getZExtValue() == 1)
19880 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
19881 CS->getZExtValue() == 1)
19885 SetCC = SetCC.getOperand(OpIdx);
19886 truncatedToBoolWithAnd = true;
19888 SetCC = SetCC.getOperand(0);
19891 switch (SetCC.getOpcode()) {
19892 case X86ISD::SETCC_CARRY:
19893 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
19894 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
19895 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
19896 // truncated to i1 using 'and'.
19897 if (checkAgainstTrue && !truncatedToBoolWithAnd)
19899 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
19900 "Invalid use of SETCC_CARRY!");
19902 case X86ISD::SETCC:
19903 // Set the condition code or opposite one if necessary.
19904 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
19905 if (needOppositeCond)
19906 CC = X86::GetOppositeBranchCondition(CC);
19907 return SetCC.getOperand(1);
19908 case X86ISD::CMOV: {
19909 // Check whether false/true value has canonical one, i.e. 0 or 1.
19910 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
19911 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
19912 // Quit if true value is not a constant.
19915 // Quit if false value is not a constant.
19917 SDValue Op = SetCC.getOperand(0);
19918 // Skip 'zext' or 'trunc' node.
19919 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
19920 Op.getOpcode() == ISD::TRUNCATE)
19921 Op = Op.getOperand(0);
19922 // A special case for rdrand/rdseed, where 0 is set if false cond is
19924 if ((Op.getOpcode() != X86ISD::RDRAND &&
19925 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
19928 // Quit if false value is not the constant 0 or 1.
19929 bool FValIsFalse = true;
19930 if (FVal && FVal->getZExtValue() != 0) {
19931 if (FVal->getZExtValue() != 1)
19933 // If FVal is 1, opposite cond is needed.
19934 needOppositeCond = !needOppositeCond;
19935 FValIsFalse = false;
19937 // Quit if TVal is not the constant opposite of FVal.
19938 if (FValIsFalse && TVal->getZExtValue() != 1)
19940 if (!FValIsFalse && TVal->getZExtValue() != 0)
19942 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
19943 if (needOppositeCond)
19944 CC = X86::GetOppositeBranchCondition(CC);
19945 return SetCC.getOperand(3);
19952 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
19953 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
19954 TargetLowering::DAGCombinerInfo &DCI,
19955 const X86Subtarget *Subtarget) {
19958 // If the flag operand isn't dead, don't touch this CMOV.
19959 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
19962 SDValue FalseOp = N->getOperand(0);
19963 SDValue TrueOp = N->getOperand(1);
19964 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
19965 SDValue Cond = N->getOperand(3);
19967 if (CC == X86::COND_E || CC == X86::COND_NE) {
19968 switch (Cond.getOpcode()) {
19972 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
19973 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
19974 return (CC == X86::COND_E) ? FalseOp : TrueOp;
19980 Flags = checkBoolTestSetCCCombine(Cond, CC);
19981 if (Flags.getNode() &&
19982 // Extra check as FCMOV only supports a subset of X86 cond.
19983 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
19984 SDValue Ops[] = { FalseOp, TrueOp,
19985 DAG.getConstant(CC, MVT::i8), Flags };
19986 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19989 // If this is a select between two integer constants, try to do some
19990 // optimizations. Note that the operands are ordered the opposite of SELECT
19992 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19993 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19994 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19995 // larger than FalseC (the false value).
19996 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19997 CC = X86::GetOppositeBranchCondition(CC);
19998 std::swap(TrueC, FalseC);
19999 std::swap(TrueOp, FalseOp);
20002 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
20003 // This is efficient for any integer data type (including i8/i16) and
20005 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20006 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20007 DAG.getConstant(CC, MVT::i8), Cond);
20009 // Zero extend the condition if needed.
20010 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20012 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20013 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20014 DAG.getConstant(ShAmt, MVT::i8));
20015 if (N->getNumValues() == 2) // Dead flag value?
20016 return DCI.CombineTo(N, Cond, SDValue());
20020 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
20021 // for any integer data type, including i8/i16.
20022 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20023 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20024 DAG.getConstant(CC, MVT::i8), Cond);
20026 // Zero extend the condition if needed.
20027 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20028 FalseC->getValueType(0), Cond);
20029 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20030 SDValue(FalseC, 0));
20032 if (N->getNumValues() == 2) // Dead flag value?
20033 return DCI.CombineTo(N, Cond, SDValue());
20037 // Optimize cases that will turn into an LEA instruction. This requires
20038 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20039 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20040 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20041 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20043 bool isFastMultiplier = false;
20045 switch ((unsigned char)Diff) {
20047 case 1: // result = add base, cond
20048 case 2: // result = lea base( , cond*2)
20049 case 3: // result = lea base(cond, cond*2)
20050 case 4: // result = lea base( , cond*4)
20051 case 5: // result = lea base(cond, cond*4)
20052 case 8: // result = lea base( , cond*8)
20053 case 9: // result = lea base(cond, cond*8)
20054 isFastMultiplier = true;
20059 if (isFastMultiplier) {
20060 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20061 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20062 DAG.getConstant(CC, MVT::i8), Cond);
20063 // Zero extend the condition if needed.
20064 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20066 // Scale the condition by the difference.
20068 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20069 DAG.getConstant(Diff, Cond.getValueType()));
20071 // Add the base if non-zero.
20072 if (FalseC->getAPIntValue() != 0)
20073 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20074 SDValue(FalseC, 0));
20075 if (N->getNumValues() == 2) // Dead flag value?
20076 return DCI.CombineTo(N, Cond, SDValue());
20083 // Handle these cases:
20084 // (select (x != c), e, c) -> select (x != c), e, x),
20085 // (select (x == c), c, e) -> select (x == c), x, e)
20086 // where the c is an integer constant, and the "select" is the combination
20087 // of CMOV and CMP.
20089 // The rationale for this change is that the conditional-move from a constant
20090 // needs two instructions, however, conditional-move from a register needs
20091 // only one instruction.
20093 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20094 // some instruction-combining opportunities. This opt needs to be
20095 // postponed as late as possible.
20097 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20098 // the DCI.xxxx conditions are provided to postpone the optimization as
20099 // late as possible.
20101 ConstantSDNode *CmpAgainst = nullptr;
20102 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20103 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20104 !isa<ConstantSDNode>(Cond.getOperand(0))) {
20106 if (CC == X86::COND_NE &&
20107 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20108 CC = X86::GetOppositeBranchCondition(CC);
20109 std::swap(TrueOp, FalseOp);
20112 if (CC == X86::COND_E &&
20113 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20114 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20115 DAG.getConstant(CC, MVT::i8), Cond };
20116 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20124 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20125 const X86Subtarget *Subtarget) {
20126 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20128 default: return SDValue();
20129 // SSE/AVX/AVX2 blend intrinsics.
20130 case Intrinsic::x86_avx2_pblendvb:
20131 case Intrinsic::x86_avx2_pblendw:
20132 case Intrinsic::x86_avx2_pblendd_128:
20133 case Intrinsic::x86_avx2_pblendd_256:
20134 // Don't try to simplify this intrinsic if we don't have AVX2.
20135 if (!Subtarget->hasAVX2())
20138 case Intrinsic::x86_avx_blend_pd_256:
20139 case Intrinsic::x86_avx_blend_ps_256:
20140 case Intrinsic::x86_avx_blendv_pd_256:
20141 case Intrinsic::x86_avx_blendv_ps_256:
20142 // Don't try to simplify this intrinsic if we don't have AVX.
20143 if (!Subtarget->hasAVX())
20146 case Intrinsic::x86_sse41_pblendw:
20147 case Intrinsic::x86_sse41_blendpd:
20148 case Intrinsic::x86_sse41_blendps:
20149 case Intrinsic::x86_sse41_blendvps:
20150 case Intrinsic::x86_sse41_blendvpd:
20151 case Intrinsic::x86_sse41_pblendvb: {
20152 SDValue Op0 = N->getOperand(1);
20153 SDValue Op1 = N->getOperand(2);
20154 SDValue Mask = N->getOperand(3);
20156 // Don't try to simplify this intrinsic if we don't have SSE4.1.
20157 if (!Subtarget->hasSSE41())
20160 // fold (blend A, A, Mask) -> A
20163 // fold (blend A, B, allZeros) -> A
20164 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20166 // fold (blend A, B, allOnes) -> B
20167 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20170 // Simplify the case where the mask is a constant i32 value.
20171 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20172 if (C->isNullValue())
20174 if (C->isAllOnesValue())
20181 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20182 case Intrinsic::x86_sse2_psrai_w:
20183 case Intrinsic::x86_sse2_psrai_d:
20184 case Intrinsic::x86_avx2_psrai_w:
20185 case Intrinsic::x86_avx2_psrai_d:
20186 case Intrinsic::x86_sse2_psra_w:
20187 case Intrinsic::x86_sse2_psra_d:
20188 case Intrinsic::x86_avx2_psra_w:
20189 case Intrinsic::x86_avx2_psra_d: {
20190 SDValue Op0 = N->getOperand(1);
20191 SDValue Op1 = N->getOperand(2);
20192 EVT VT = Op0.getValueType();
20193 assert(VT.isVector() && "Expected a vector type!");
20195 if (isa<BuildVectorSDNode>(Op1))
20196 Op1 = Op1.getOperand(0);
20198 if (!isa<ConstantSDNode>(Op1))
20201 EVT SVT = VT.getVectorElementType();
20202 unsigned SVTBits = SVT.getSizeInBits();
20204 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20205 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20206 uint64_t ShAmt = C.getZExtValue();
20208 // Don't try to convert this shift into a ISD::SRA if the shift
20209 // count is bigger than or equal to the element size.
20210 if (ShAmt >= SVTBits)
20213 // Trivial case: if the shift count is zero, then fold this
20214 // into the first operand.
20218 // Replace this packed shift intrinsic with a target independent
20220 SDValue Splat = DAG.getConstant(C, VT);
20221 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20226 /// PerformMulCombine - Optimize a single multiply with constant into two
20227 /// in order to implement it with two cheaper instructions, e.g.
20228 /// LEA + SHL, LEA + LEA.
20229 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20230 TargetLowering::DAGCombinerInfo &DCI) {
20231 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20234 EVT VT = N->getValueType(0);
20235 if (VT != MVT::i64)
20238 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20241 uint64_t MulAmt = C->getZExtValue();
20242 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20245 uint64_t MulAmt1 = 0;
20246 uint64_t MulAmt2 = 0;
20247 if ((MulAmt % 9) == 0) {
20249 MulAmt2 = MulAmt / 9;
20250 } else if ((MulAmt % 5) == 0) {
20252 MulAmt2 = MulAmt / 5;
20253 } else if ((MulAmt % 3) == 0) {
20255 MulAmt2 = MulAmt / 3;
20258 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20261 if (isPowerOf2_64(MulAmt2) &&
20262 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20263 // If second multiplifer is pow2, issue it first. We want the multiply by
20264 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20266 std::swap(MulAmt1, MulAmt2);
20269 if (isPowerOf2_64(MulAmt1))
20270 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20271 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20273 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20274 DAG.getConstant(MulAmt1, VT));
20276 if (isPowerOf2_64(MulAmt2))
20277 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20278 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20280 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20281 DAG.getConstant(MulAmt2, VT));
20283 // Do not add new nodes to DAG combiner worklist.
20284 DCI.CombineTo(N, NewMul, false);
20289 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20290 SDValue N0 = N->getOperand(0);
20291 SDValue N1 = N->getOperand(1);
20292 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20293 EVT VT = N0.getValueType();
20295 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20296 // since the result of setcc_c is all zero's or all ones.
20297 if (VT.isInteger() && !VT.isVector() &&
20298 N1C && N0.getOpcode() == ISD::AND &&
20299 N0.getOperand(1).getOpcode() == ISD::Constant) {
20300 SDValue N00 = N0.getOperand(0);
20301 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20302 ((N00.getOpcode() == ISD::ANY_EXTEND ||
20303 N00.getOpcode() == ISD::ZERO_EXTEND) &&
20304 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20305 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20306 APInt ShAmt = N1C->getAPIntValue();
20307 Mask = Mask.shl(ShAmt);
20309 return DAG.getNode(ISD::AND, SDLoc(N), VT,
20310 N00, DAG.getConstant(Mask, VT));
20314 // Hardware support for vector shifts is sparse which makes us scalarize the
20315 // vector operations in many cases. Also, on sandybridge ADD is faster than
20317 // (shl V, 1) -> add V,V
20318 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
20319 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
20320 assert(N0.getValueType().isVector() && "Invalid vector shift type");
20321 // We shift all of the values by one. In many cases we do not have
20322 // hardware support for this operation. This is better expressed as an ADD
20324 if (N1SplatC->getZExtValue() == 1)
20325 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20331 /// \brief Returns a vector of 0s if the node in input is a vector logical
20332 /// shift by a constant amount which is known to be bigger than or equal
20333 /// to the vector element size in bits.
20334 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20335 const X86Subtarget *Subtarget) {
20336 EVT VT = N->getValueType(0);
20338 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20339 (!Subtarget->hasInt256() ||
20340 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20343 SDValue Amt = N->getOperand(1);
20345 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
20346 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
20347 APInt ShiftAmt = AmtSplat->getAPIntValue();
20348 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20350 // SSE2/AVX2 logical shifts always return a vector of 0s
20351 // if the shift amount is bigger than or equal to
20352 // the element size. The constant shift amount will be
20353 // encoded as a 8-bit immediate.
20354 if (ShiftAmt.trunc(8).uge(MaxAmount))
20355 return getZeroVector(VT, Subtarget, DAG, DL);
20361 /// PerformShiftCombine - Combine shifts.
20362 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20363 TargetLowering::DAGCombinerInfo &DCI,
20364 const X86Subtarget *Subtarget) {
20365 if (N->getOpcode() == ISD::SHL) {
20366 SDValue V = PerformSHLCombine(N, DAG);
20367 if (V.getNode()) return V;
20370 if (N->getOpcode() != ISD::SRA) {
20371 // Try to fold this logical shift into a zero vector.
20372 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20373 if (V.getNode()) return V;
20379 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
20380 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20381 // and friends. Likewise for OR -> CMPNEQSS.
20382 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20383 TargetLowering::DAGCombinerInfo &DCI,
20384 const X86Subtarget *Subtarget) {
20387 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20388 // we're requiring SSE2 for both.
20389 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20390 SDValue N0 = N->getOperand(0);
20391 SDValue N1 = N->getOperand(1);
20392 SDValue CMP0 = N0->getOperand(1);
20393 SDValue CMP1 = N1->getOperand(1);
20396 // The SETCCs should both refer to the same CMP.
20397 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20400 SDValue CMP00 = CMP0->getOperand(0);
20401 SDValue CMP01 = CMP0->getOperand(1);
20402 EVT VT = CMP00.getValueType();
20404 if (VT == MVT::f32 || VT == MVT::f64) {
20405 bool ExpectingFlags = false;
20406 // Check for any users that want flags:
20407 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20408 !ExpectingFlags && UI != UE; ++UI)
20409 switch (UI->getOpcode()) {
20414 ExpectingFlags = true;
20416 case ISD::CopyToReg:
20417 case ISD::SIGN_EXTEND:
20418 case ISD::ZERO_EXTEND:
20419 case ISD::ANY_EXTEND:
20423 if (!ExpectingFlags) {
20424 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20425 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20427 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20428 X86::CondCode tmp = cc0;
20433 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
20434 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20435 // FIXME: need symbolic constants for these magic numbers.
20436 // See X86ATTInstPrinter.cpp:printSSECC().
20437 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20438 if (Subtarget->hasAVX512()) {
20439 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20440 CMP01, DAG.getConstant(x86cc, MVT::i8));
20441 if (N->getValueType(0) != MVT::i1)
20442 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20446 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20447 CMP00.getValueType(), CMP00, CMP01,
20448 DAG.getConstant(x86cc, MVT::i8));
20450 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20451 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20453 if (is64BitFP && !Subtarget->is64Bit()) {
20454 // On a 32-bit target, we cannot bitcast the 64-bit float to a
20455 // 64-bit integer, since that's not a legal type. Since
20456 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20457 // bits, but can do this little dance to extract the lowest 32 bits
20458 // and work with those going forward.
20459 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20461 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20463 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20464 Vector32, DAG.getIntPtrConstant(0));
20468 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20469 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20470 DAG.getConstant(1, IntVT));
20471 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20472 return OneBitOfTruth;
20480 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20481 /// so it can be folded inside ANDNP.
20482 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20483 EVT VT = N->getValueType(0);
20485 // Match direct AllOnes for 128 and 256-bit vectors
20486 if (ISD::isBuildVectorAllOnes(N))
20489 // Look through a bit convert.
20490 if (N->getOpcode() == ISD::BITCAST)
20491 N = N->getOperand(0).getNode();
20493 // Sometimes the operand may come from a insert_subvector building a 256-bit
20495 if (VT.is256BitVector() &&
20496 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20497 SDValue V1 = N->getOperand(0);
20498 SDValue V2 = N->getOperand(1);
20500 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20501 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20502 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20503 ISD::isBuildVectorAllOnes(V2.getNode()))
20510 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20511 // register. In most cases we actually compare or select YMM-sized registers
20512 // and mixing the two types creates horrible code. This method optimizes
20513 // some of the transition sequences.
20514 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20515 TargetLowering::DAGCombinerInfo &DCI,
20516 const X86Subtarget *Subtarget) {
20517 EVT VT = N->getValueType(0);
20518 if (!VT.is256BitVector())
20521 assert((N->getOpcode() == ISD::ANY_EXTEND ||
20522 N->getOpcode() == ISD::ZERO_EXTEND ||
20523 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20525 SDValue Narrow = N->getOperand(0);
20526 EVT NarrowVT = Narrow->getValueType(0);
20527 if (!NarrowVT.is128BitVector())
20530 if (Narrow->getOpcode() != ISD::XOR &&
20531 Narrow->getOpcode() != ISD::AND &&
20532 Narrow->getOpcode() != ISD::OR)
20535 SDValue N0 = Narrow->getOperand(0);
20536 SDValue N1 = Narrow->getOperand(1);
20539 // The Left side has to be a trunc.
20540 if (N0.getOpcode() != ISD::TRUNCATE)
20543 // The type of the truncated inputs.
20544 EVT WideVT = N0->getOperand(0)->getValueType(0);
20548 // The right side has to be a 'trunc' or a constant vector.
20549 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20550 ConstantSDNode *RHSConstSplat = nullptr;
20551 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
20552 RHSConstSplat = RHSBV->getConstantSplatNode();
20553 if (!RHSTrunc && !RHSConstSplat)
20556 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20558 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
20561 // Set N0 and N1 to hold the inputs to the new wide operation.
20562 N0 = N0->getOperand(0);
20563 if (RHSConstSplat) {
20564 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
20565 SDValue(RHSConstSplat, 0));
20566 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
20567 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
20568 } else if (RHSTrunc) {
20569 N1 = N1->getOperand(0);
20572 // Generate the wide operation.
20573 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
20574 unsigned Opcode = N->getOpcode();
20576 case ISD::ANY_EXTEND:
20578 case ISD::ZERO_EXTEND: {
20579 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
20580 APInt Mask = APInt::getAllOnesValue(InBits);
20581 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
20582 return DAG.getNode(ISD::AND, DL, VT,
20583 Op, DAG.getConstant(Mask, VT));
20585 case ISD::SIGN_EXTEND:
20586 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
20587 Op, DAG.getValueType(NarrowVT));
20589 llvm_unreachable("Unexpected opcode");
20593 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
20594 TargetLowering::DAGCombinerInfo &DCI,
20595 const X86Subtarget *Subtarget) {
20596 EVT VT = N->getValueType(0);
20597 if (DCI.isBeforeLegalizeOps())
20600 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20604 // Create BEXTR instructions
20605 // BEXTR is ((X >> imm) & (2**size-1))
20606 if (VT == MVT::i32 || VT == MVT::i64) {
20607 SDValue N0 = N->getOperand(0);
20608 SDValue N1 = N->getOperand(1);
20611 // Check for BEXTR.
20612 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
20613 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
20614 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
20615 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20616 if (MaskNode && ShiftNode) {
20617 uint64_t Mask = MaskNode->getZExtValue();
20618 uint64_t Shift = ShiftNode->getZExtValue();
20619 if (isMask_64(Mask)) {
20620 uint64_t MaskSize = CountPopulation_64(Mask);
20621 if (Shift + MaskSize <= VT.getSizeInBits())
20622 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
20623 DAG.getConstant(Shift | (MaskSize << 8), VT));
20631 // Want to form ANDNP nodes:
20632 // 1) In the hopes of then easily combining them with OR and AND nodes
20633 // to form PBLEND/PSIGN.
20634 // 2) To match ANDN packed intrinsics
20635 if (VT != MVT::v2i64 && VT != MVT::v4i64)
20638 SDValue N0 = N->getOperand(0);
20639 SDValue N1 = N->getOperand(1);
20642 // Check LHS for vnot
20643 if (N0.getOpcode() == ISD::XOR &&
20644 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
20645 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
20646 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
20648 // Check RHS for vnot
20649 if (N1.getOpcode() == ISD::XOR &&
20650 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
20651 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
20652 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
20657 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
20658 TargetLowering::DAGCombinerInfo &DCI,
20659 const X86Subtarget *Subtarget) {
20660 if (DCI.isBeforeLegalizeOps())
20663 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20667 SDValue N0 = N->getOperand(0);
20668 SDValue N1 = N->getOperand(1);
20669 EVT VT = N->getValueType(0);
20671 // look for psign/blend
20672 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
20673 if (!Subtarget->hasSSSE3() ||
20674 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
20677 // Canonicalize pandn to RHS
20678 if (N0.getOpcode() == X86ISD::ANDNP)
20680 // or (and (m, y), (pandn m, x))
20681 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
20682 SDValue Mask = N1.getOperand(0);
20683 SDValue X = N1.getOperand(1);
20685 if (N0.getOperand(0) == Mask)
20686 Y = N0.getOperand(1);
20687 if (N0.getOperand(1) == Mask)
20688 Y = N0.getOperand(0);
20690 // Check to see if the mask appeared in both the AND and ANDNP and
20694 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
20695 // Look through mask bitcast.
20696 if (Mask.getOpcode() == ISD::BITCAST)
20697 Mask = Mask.getOperand(0);
20698 if (X.getOpcode() == ISD::BITCAST)
20699 X = X.getOperand(0);
20700 if (Y.getOpcode() == ISD::BITCAST)
20701 Y = Y.getOperand(0);
20703 EVT MaskVT = Mask.getValueType();
20705 // Validate that the Mask operand is a vector sra node.
20706 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
20707 // there is no psrai.b
20708 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
20709 unsigned SraAmt = ~0;
20710 if (Mask.getOpcode() == ISD::SRA) {
20711 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
20712 if (auto *AmtConst = AmtBV->getConstantSplatNode())
20713 SraAmt = AmtConst->getZExtValue();
20714 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
20715 SDValue SraC = Mask.getOperand(1);
20716 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
20718 if ((SraAmt + 1) != EltBits)
20723 // Now we know we at least have a plendvb with the mask val. See if
20724 // we can form a psignb/w/d.
20725 // psign = x.type == y.type == mask.type && y = sub(0, x);
20726 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
20727 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
20728 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
20729 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
20730 "Unsupported VT for PSIGN");
20731 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
20732 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20734 // PBLENDVB only available on SSE 4.1
20735 if (!Subtarget->hasSSE41())
20738 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
20740 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
20741 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
20742 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
20743 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
20744 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20748 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
20751 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
20752 MachineFunction &MF = DAG.getMachineFunction();
20753 bool OptForSize = MF.getFunction()->getAttributes().
20754 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
20756 // SHLD/SHRD instructions have lower register pressure, but on some
20757 // platforms they have higher latency than the equivalent
20758 // series of shifts/or that would otherwise be generated.
20759 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
20760 // have higher latencies and we are not optimizing for size.
20761 if (!OptForSize && Subtarget->isSHLDSlow())
20764 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
20766 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
20768 if (!N0.hasOneUse() || !N1.hasOneUse())
20771 SDValue ShAmt0 = N0.getOperand(1);
20772 if (ShAmt0.getValueType() != MVT::i8)
20774 SDValue ShAmt1 = N1.getOperand(1);
20775 if (ShAmt1.getValueType() != MVT::i8)
20777 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
20778 ShAmt0 = ShAmt0.getOperand(0);
20779 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
20780 ShAmt1 = ShAmt1.getOperand(0);
20783 unsigned Opc = X86ISD::SHLD;
20784 SDValue Op0 = N0.getOperand(0);
20785 SDValue Op1 = N1.getOperand(0);
20786 if (ShAmt0.getOpcode() == ISD::SUB) {
20787 Opc = X86ISD::SHRD;
20788 std::swap(Op0, Op1);
20789 std::swap(ShAmt0, ShAmt1);
20792 unsigned Bits = VT.getSizeInBits();
20793 if (ShAmt1.getOpcode() == ISD::SUB) {
20794 SDValue Sum = ShAmt1.getOperand(0);
20795 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
20796 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
20797 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
20798 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
20799 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
20800 return DAG.getNode(Opc, DL, VT,
20802 DAG.getNode(ISD::TRUNCATE, DL,
20805 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
20806 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
20808 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
20809 return DAG.getNode(Opc, DL, VT,
20810 N0.getOperand(0), N1.getOperand(0),
20811 DAG.getNode(ISD::TRUNCATE, DL,
20818 // Generate NEG and CMOV for integer abs.
20819 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
20820 EVT VT = N->getValueType(0);
20822 // Since X86 does not have CMOV for 8-bit integer, we don't convert
20823 // 8-bit integer abs to NEG and CMOV.
20824 if (VT.isInteger() && VT.getSizeInBits() == 8)
20827 SDValue N0 = N->getOperand(0);
20828 SDValue N1 = N->getOperand(1);
20831 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
20832 // and change it to SUB and CMOV.
20833 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
20834 N0.getOpcode() == ISD::ADD &&
20835 N0.getOperand(1) == N1 &&
20836 N1.getOpcode() == ISD::SRA &&
20837 N1.getOperand(0) == N0.getOperand(0))
20838 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
20839 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
20840 // Generate SUB & CMOV.
20841 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
20842 DAG.getConstant(0, VT), N0.getOperand(0));
20844 SDValue Ops[] = { N0.getOperand(0), Neg,
20845 DAG.getConstant(X86::COND_GE, MVT::i8),
20846 SDValue(Neg.getNode(), 1) };
20847 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
20852 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
20853 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
20854 TargetLowering::DAGCombinerInfo &DCI,
20855 const X86Subtarget *Subtarget) {
20856 if (DCI.isBeforeLegalizeOps())
20859 if (Subtarget->hasCMov()) {
20860 SDValue RV = performIntegerAbsCombine(N, DAG);
20868 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
20869 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
20870 TargetLowering::DAGCombinerInfo &DCI,
20871 const X86Subtarget *Subtarget) {
20872 LoadSDNode *Ld = cast<LoadSDNode>(N);
20873 EVT RegVT = Ld->getValueType(0);
20874 EVT MemVT = Ld->getMemoryVT();
20876 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20877 unsigned RegSz = RegVT.getSizeInBits();
20879 // On Sandybridge unaligned 256bit loads are inefficient.
20880 ISD::LoadExtType Ext = Ld->getExtensionType();
20881 unsigned Alignment = Ld->getAlignment();
20882 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
20883 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
20884 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
20885 unsigned NumElems = RegVT.getVectorNumElements();
20889 SDValue Ptr = Ld->getBasePtr();
20890 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
20892 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20894 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20895 Ld->getPointerInfo(), Ld->isVolatile(),
20896 Ld->isNonTemporal(), Ld->isInvariant(),
20898 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20899 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20900 Ld->getPointerInfo(), Ld->isVolatile(),
20901 Ld->isNonTemporal(), Ld->isInvariant(),
20902 std::min(16U, Alignment));
20903 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20905 Load2.getValue(1));
20907 SDValue NewVec = DAG.getUNDEF(RegVT);
20908 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
20909 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
20910 return DCI.CombineTo(N, NewVec, TF, true);
20913 // If this is a vector EXT Load then attempt to optimize it using a
20914 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
20915 // expansion is still better than scalar code.
20916 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
20917 // emit a shuffle and a arithmetic shift.
20918 // TODO: It is possible to support ZExt by zeroing the undef values
20919 // during the shuffle phase or after the shuffle.
20920 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
20921 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
20922 assert(MemVT != RegVT && "Cannot extend to the same type");
20923 assert(MemVT.isVector() && "Must load a vector from memory");
20925 unsigned NumElems = RegVT.getVectorNumElements();
20926 unsigned MemSz = MemVT.getSizeInBits();
20927 assert(RegSz > MemSz && "Register size must be greater than the mem size");
20929 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
20932 // All sizes must be a power of two.
20933 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
20936 // Attempt to load the original value using scalar loads.
20937 // Find the largest scalar type that divides the total loaded size.
20938 MVT SclrLoadTy = MVT::i8;
20939 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20940 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20941 MVT Tp = (MVT::SimpleValueType)tp;
20942 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20947 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20948 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20950 SclrLoadTy = MVT::f64;
20952 // Calculate the number of scalar loads that we need to perform
20953 // in order to load our vector from memory.
20954 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20955 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
20958 unsigned loadRegZize = RegSz;
20959 if (Ext == ISD::SEXTLOAD && RegSz == 256)
20962 // Represent our vector as a sequence of elements which are the
20963 // largest scalar that we can load.
20964 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
20965 loadRegZize/SclrLoadTy.getSizeInBits());
20967 // Represent the data using the same element type that is stored in
20968 // memory. In practice, we ''widen'' MemVT.
20970 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20971 loadRegZize/MemVT.getScalarType().getSizeInBits());
20973 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20974 "Invalid vector type");
20976 // We can't shuffle using an illegal type.
20977 if (!TLI.isTypeLegal(WideVecVT))
20980 SmallVector<SDValue, 8> Chains;
20981 SDValue Ptr = Ld->getBasePtr();
20982 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20983 TLI.getPointerTy());
20984 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20986 for (unsigned i = 0; i < NumLoads; ++i) {
20987 // Perform a single load.
20988 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20989 Ptr, Ld->getPointerInfo(),
20990 Ld->isVolatile(), Ld->isNonTemporal(),
20991 Ld->isInvariant(), Ld->getAlignment());
20992 Chains.push_back(ScalarLoad.getValue(1));
20993 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20994 // another round of DAGCombining.
20996 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20998 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20999 ScalarLoad, DAG.getIntPtrConstant(i));
21001 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21004 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21006 // Bitcast the loaded value to a vector of the original element type, in
21007 // the size of the target vector type.
21008 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
21009 unsigned SizeRatio = RegSz/MemSz;
21011 if (Ext == ISD::SEXTLOAD) {
21012 // If we have SSE4.1 we can directly emit a VSEXT node.
21013 if (Subtarget->hasSSE41()) {
21014 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
21015 return DCI.CombineTo(N, Sext, TF, true);
21018 // Otherwise we'll shuffle the small elements in the high bits of the
21019 // larger type and perform an arithmetic shift. If the shift is not legal
21020 // it's better to scalarize.
21021 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
21024 // Redistribute the loaded elements into the different locations.
21025 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21026 for (unsigned i = 0; i != NumElems; ++i)
21027 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
21029 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21030 DAG.getUNDEF(WideVecVT),
21033 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
21035 // Build the arithmetic shift.
21036 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
21037 MemVT.getVectorElementType().getSizeInBits();
21038 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
21039 DAG.getConstant(Amt, RegVT));
21041 return DCI.CombineTo(N, Shuff, TF, true);
21044 // Redistribute the loaded elements into the different locations.
21045 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21046 for (unsigned i = 0; i != NumElems; ++i)
21047 ShuffleVec[i*SizeRatio] = i;
21049 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21050 DAG.getUNDEF(WideVecVT),
21053 // Bitcast to the requested type.
21054 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
21055 // Replace the original load with the new sequence
21056 // and return the new chain.
21057 return DCI.CombineTo(N, Shuff, TF, true);
21063 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21064 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21065 const X86Subtarget *Subtarget) {
21066 StoreSDNode *St = cast<StoreSDNode>(N);
21067 EVT VT = St->getValue().getValueType();
21068 EVT StVT = St->getMemoryVT();
21070 SDValue StoredVal = St->getOperand(1);
21071 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21073 // If we are saving a concatenation of two XMM registers, perform two stores.
21074 // On Sandy Bridge, 256-bit memory operations are executed by two
21075 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21076 // memory operation.
21077 unsigned Alignment = St->getAlignment();
21078 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21079 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21080 StVT == VT && !IsAligned) {
21081 unsigned NumElems = VT.getVectorNumElements();
21085 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21086 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21088 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21089 SDValue Ptr0 = St->getBasePtr();
21090 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21092 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21093 St->getPointerInfo(), St->isVolatile(),
21094 St->isNonTemporal(), Alignment);
21095 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21096 St->getPointerInfo(), St->isVolatile(),
21097 St->isNonTemporal(),
21098 std::min(16U, Alignment));
21099 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21102 // Optimize trunc store (of multiple scalars) to shuffle and store.
21103 // First, pack all of the elements in one place. Next, store to memory
21104 // in fewer chunks.
21105 if (St->isTruncatingStore() && VT.isVector()) {
21106 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21107 unsigned NumElems = VT.getVectorNumElements();
21108 assert(StVT != VT && "Cannot truncate to the same type");
21109 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21110 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21112 // From, To sizes and ElemCount must be pow of two
21113 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21114 // We are going to use the original vector elt for storing.
21115 // Accumulated smaller vector elements must be a multiple of the store size.
21116 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21118 unsigned SizeRatio = FromSz / ToSz;
21120 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21122 // Create a type on which we perform the shuffle
21123 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21124 StVT.getScalarType(), NumElems*SizeRatio);
21126 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21128 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21129 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21130 for (unsigned i = 0; i != NumElems; ++i)
21131 ShuffleVec[i] = i * SizeRatio;
21133 // Can't shuffle using an illegal type.
21134 if (!TLI.isTypeLegal(WideVecVT))
21137 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21138 DAG.getUNDEF(WideVecVT),
21140 // At this point all of the data is stored at the bottom of the
21141 // register. We now need to save it to mem.
21143 // Find the largest store unit
21144 MVT StoreType = MVT::i8;
21145 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21146 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21147 MVT Tp = (MVT::SimpleValueType)tp;
21148 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21152 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21153 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21154 (64 <= NumElems * ToSz))
21155 StoreType = MVT::f64;
21157 // Bitcast the original vector into a vector of store-size units
21158 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21159 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21160 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21161 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21162 SmallVector<SDValue, 8> Chains;
21163 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21164 TLI.getPointerTy());
21165 SDValue Ptr = St->getBasePtr();
21167 // Perform one or more big stores into memory.
21168 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21169 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21170 StoreType, ShuffWide,
21171 DAG.getIntPtrConstant(i));
21172 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21173 St->getPointerInfo(), St->isVolatile(),
21174 St->isNonTemporal(), St->getAlignment());
21175 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21176 Chains.push_back(Ch);
21179 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21182 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
21183 // the FP state in cases where an emms may be missing.
21184 // A preferable solution to the general problem is to figure out the right
21185 // places to insert EMMS. This qualifies as a quick hack.
21187 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21188 if (VT.getSizeInBits() != 64)
21191 const Function *F = DAG.getMachineFunction().getFunction();
21192 bool NoImplicitFloatOps = F->getAttributes().
21193 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21194 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21195 && Subtarget->hasSSE2();
21196 if ((VT.isVector() ||
21197 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21198 isa<LoadSDNode>(St->getValue()) &&
21199 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21200 St->getChain().hasOneUse() && !St->isVolatile()) {
21201 SDNode* LdVal = St->getValue().getNode();
21202 LoadSDNode *Ld = nullptr;
21203 int TokenFactorIndex = -1;
21204 SmallVector<SDValue, 8> Ops;
21205 SDNode* ChainVal = St->getChain().getNode();
21206 // Must be a store of a load. We currently handle two cases: the load
21207 // is a direct child, and it's under an intervening TokenFactor. It is
21208 // possible to dig deeper under nested TokenFactors.
21209 if (ChainVal == LdVal)
21210 Ld = cast<LoadSDNode>(St->getChain());
21211 else if (St->getValue().hasOneUse() &&
21212 ChainVal->getOpcode() == ISD::TokenFactor) {
21213 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21214 if (ChainVal->getOperand(i).getNode() == LdVal) {
21215 TokenFactorIndex = i;
21216 Ld = cast<LoadSDNode>(St->getValue());
21218 Ops.push_back(ChainVal->getOperand(i));
21222 if (!Ld || !ISD::isNormalLoad(Ld))
21225 // If this is not the MMX case, i.e. we are just turning i64 load/store
21226 // into f64 load/store, avoid the transformation if there are multiple
21227 // uses of the loaded value.
21228 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21233 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21234 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21236 if (Subtarget->is64Bit() || F64IsLegal) {
21237 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21238 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21239 Ld->getPointerInfo(), Ld->isVolatile(),
21240 Ld->isNonTemporal(), Ld->isInvariant(),
21241 Ld->getAlignment());
21242 SDValue NewChain = NewLd.getValue(1);
21243 if (TokenFactorIndex != -1) {
21244 Ops.push_back(NewChain);
21245 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21247 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21248 St->getPointerInfo(),
21249 St->isVolatile(), St->isNonTemporal(),
21250 St->getAlignment());
21253 // Otherwise, lower to two pairs of 32-bit loads / stores.
21254 SDValue LoAddr = Ld->getBasePtr();
21255 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21256 DAG.getConstant(4, MVT::i32));
21258 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21259 Ld->getPointerInfo(),
21260 Ld->isVolatile(), Ld->isNonTemporal(),
21261 Ld->isInvariant(), Ld->getAlignment());
21262 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21263 Ld->getPointerInfo().getWithOffset(4),
21264 Ld->isVolatile(), Ld->isNonTemporal(),
21266 MinAlign(Ld->getAlignment(), 4));
21268 SDValue NewChain = LoLd.getValue(1);
21269 if (TokenFactorIndex != -1) {
21270 Ops.push_back(LoLd);
21271 Ops.push_back(HiLd);
21272 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21275 LoAddr = St->getBasePtr();
21276 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21277 DAG.getConstant(4, MVT::i32));
21279 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21280 St->getPointerInfo(),
21281 St->isVolatile(), St->isNonTemporal(),
21282 St->getAlignment());
21283 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21284 St->getPointerInfo().getWithOffset(4),
21286 St->isNonTemporal(),
21287 MinAlign(St->getAlignment(), 4));
21288 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21293 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21294 /// and return the operands for the horizontal operation in LHS and RHS. A
21295 /// horizontal operation performs the binary operation on successive elements
21296 /// of its first operand, then on successive elements of its second operand,
21297 /// returning the resulting values in a vector. For example, if
21298 /// A = < float a0, float a1, float a2, float a3 >
21300 /// B = < float b0, float b1, float b2, float b3 >
21301 /// then the result of doing a horizontal operation on A and B is
21302 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21303 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21304 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21305 /// set to A, RHS to B, and the routine returns 'true'.
21306 /// Note that the binary operation should have the property that if one of the
21307 /// operands is UNDEF then the result is UNDEF.
21308 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21309 // Look for the following pattern: if
21310 // A = < float a0, float a1, float a2, float a3 >
21311 // B = < float b0, float b1, float b2, float b3 >
21313 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21314 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21315 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21316 // which is A horizontal-op B.
21318 // At least one of the operands should be a vector shuffle.
21319 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21320 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21323 MVT VT = LHS.getSimpleValueType();
21325 assert((VT.is128BitVector() || VT.is256BitVector()) &&
21326 "Unsupported vector type for horizontal add/sub");
21328 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21329 // operate independently on 128-bit lanes.
21330 unsigned NumElts = VT.getVectorNumElements();
21331 unsigned NumLanes = VT.getSizeInBits()/128;
21332 unsigned NumLaneElts = NumElts / NumLanes;
21333 assert((NumLaneElts % 2 == 0) &&
21334 "Vector type should have an even number of elements in each lane");
21335 unsigned HalfLaneElts = NumLaneElts/2;
21337 // View LHS in the form
21338 // LHS = VECTOR_SHUFFLE A, B, LMask
21339 // If LHS is not a shuffle then pretend it is the shuffle
21340 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21341 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21344 SmallVector<int, 16> LMask(NumElts);
21345 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21346 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21347 A = LHS.getOperand(0);
21348 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21349 B = LHS.getOperand(1);
21350 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21351 std::copy(Mask.begin(), Mask.end(), LMask.begin());
21353 if (LHS.getOpcode() != ISD::UNDEF)
21355 for (unsigned i = 0; i != NumElts; ++i)
21359 // Likewise, view RHS in the form
21360 // RHS = VECTOR_SHUFFLE C, D, RMask
21362 SmallVector<int, 16> RMask(NumElts);
21363 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21364 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21365 C = RHS.getOperand(0);
21366 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21367 D = RHS.getOperand(1);
21368 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21369 std::copy(Mask.begin(), Mask.end(), RMask.begin());
21371 if (RHS.getOpcode() != ISD::UNDEF)
21373 for (unsigned i = 0; i != NumElts; ++i)
21377 // Check that the shuffles are both shuffling the same vectors.
21378 if (!(A == C && B == D) && !(A == D && B == C))
21381 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21382 if (!A.getNode() && !B.getNode())
21385 // If A and B occur in reverse order in RHS, then "swap" them (which means
21386 // rewriting the mask).
21388 CommuteVectorShuffleMask(RMask, NumElts);
21390 // At this point LHS and RHS are equivalent to
21391 // LHS = VECTOR_SHUFFLE A, B, LMask
21392 // RHS = VECTOR_SHUFFLE A, B, RMask
21393 // Check that the masks correspond to performing a horizontal operation.
21394 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21395 for (unsigned i = 0; i != NumLaneElts; ++i) {
21396 int LIdx = LMask[i+l], RIdx = RMask[i+l];
21398 // Ignore any UNDEF components.
21399 if (LIdx < 0 || RIdx < 0 ||
21400 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21401 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21404 // Check that successive elements are being operated on. If not, this is
21405 // not a horizontal operation.
21406 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21407 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21408 if (!(LIdx == Index && RIdx == Index + 1) &&
21409 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21414 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21415 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21419 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21420 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21421 const X86Subtarget *Subtarget) {
21422 EVT VT = N->getValueType(0);
21423 SDValue LHS = N->getOperand(0);
21424 SDValue RHS = N->getOperand(1);
21426 // Try to synthesize horizontal adds from adds of shuffles.
21427 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21428 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21429 isHorizontalBinOp(LHS, RHS, true))
21430 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21434 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21435 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21436 const X86Subtarget *Subtarget) {
21437 EVT VT = N->getValueType(0);
21438 SDValue LHS = N->getOperand(0);
21439 SDValue RHS = N->getOperand(1);
21441 // Try to synthesize horizontal subs from subs of shuffles.
21442 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21443 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21444 isHorizontalBinOp(LHS, RHS, false))
21445 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21449 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21450 /// X86ISD::FXOR nodes.
21451 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21452 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21453 // F[X]OR(0.0, x) -> x
21454 // F[X]OR(x, 0.0) -> x
21455 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21456 if (C->getValueAPF().isPosZero())
21457 return N->getOperand(1);
21458 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21459 if (C->getValueAPF().isPosZero())
21460 return N->getOperand(0);
21464 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21465 /// X86ISD::FMAX nodes.
21466 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21467 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21469 // Only perform optimizations if UnsafeMath is used.
21470 if (!DAG.getTarget().Options.UnsafeFPMath)
21473 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21474 // into FMINC and FMAXC, which are Commutative operations.
21475 unsigned NewOp = 0;
21476 switch (N->getOpcode()) {
21477 default: llvm_unreachable("unknown opcode");
21478 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
21479 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
21482 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21483 N->getOperand(0), N->getOperand(1));
21486 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21487 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21488 // FAND(0.0, x) -> 0.0
21489 // FAND(x, 0.0) -> 0.0
21490 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21491 if (C->getValueAPF().isPosZero())
21492 return N->getOperand(0);
21493 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21494 if (C->getValueAPF().isPosZero())
21495 return N->getOperand(1);
21499 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21500 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21501 // FANDN(x, 0.0) -> 0.0
21502 // FANDN(0.0, x) -> x
21503 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21504 if (C->getValueAPF().isPosZero())
21505 return N->getOperand(1);
21506 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21507 if (C->getValueAPF().isPosZero())
21508 return N->getOperand(1);
21512 static SDValue PerformBTCombine(SDNode *N,
21514 TargetLowering::DAGCombinerInfo &DCI) {
21515 // BT ignores high bits in the bit index operand.
21516 SDValue Op1 = N->getOperand(1);
21517 if (Op1.hasOneUse()) {
21518 unsigned BitWidth = Op1.getValueSizeInBits();
21519 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21520 APInt KnownZero, KnownOne;
21521 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21522 !DCI.isBeforeLegalizeOps());
21523 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21524 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21525 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21526 DCI.CommitTargetLoweringOpt(TLO);
21531 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21532 SDValue Op = N->getOperand(0);
21533 if (Op.getOpcode() == ISD::BITCAST)
21534 Op = Op.getOperand(0);
21535 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21536 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21537 VT.getVectorElementType().getSizeInBits() ==
21538 OpVT.getVectorElementType().getSizeInBits()) {
21539 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21544 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21545 const X86Subtarget *Subtarget) {
21546 EVT VT = N->getValueType(0);
21547 if (!VT.isVector())
21550 SDValue N0 = N->getOperand(0);
21551 SDValue N1 = N->getOperand(1);
21552 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21555 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21556 // both SSE and AVX2 since there is no sign-extended shift right
21557 // operation on a vector with 64-bit elements.
21558 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21559 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21560 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21561 N0.getOpcode() == ISD::SIGN_EXTEND)) {
21562 SDValue N00 = N0.getOperand(0);
21564 // EXTLOAD has a better solution on AVX2,
21565 // it may be replaced with X86ISD::VSEXT node.
21566 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21567 if (!ISD::isNormalLoad(N00.getNode()))
21570 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21571 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21573 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21579 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21580 TargetLowering::DAGCombinerInfo &DCI,
21581 const X86Subtarget *Subtarget) {
21582 if (!DCI.isBeforeLegalizeOps())
21585 if (!Subtarget->hasFp256())
21588 EVT VT = N->getValueType(0);
21589 if (VT.isVector() && VT.getSizeInBits() == 256) {
21590 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21598 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21599 const X86Subtarget* Subtarget) {
21601 EVT VT = N->getValueType(0);
21603 // Let legalize expand this if it isn't a legal type yet.
21604 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21607 EVT ScalarVT = VT.getScalarType();
21608 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21609 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21612 SDValue A = N->getOperand(0);
21613 SDValue B = N->getOperand(1);
21614 SDValue C = N->getOperand(2);
21616 bool NegA = (A.getOpcode() == ISD::FNEG);
21617 bool NegB = (B.getOpcode() == ISD::FNEG);
21618 bool NegC = (C.getOpcode() == ISD::FNEG);
21620 // Negative multiplication when NegA xor NegB
21621 bool NegMul = (NegA != NegB);
21623 A = A.getOperand(0);
21625 B = B.getOperand(0);
21627 C = C.getOperand(0);
21631 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21633 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21635 return DAG.getNode(Opcode, dl, VT, A, B, C);
21638 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21639 TargetLowering::DAGCombinerInfo &DCI,
21640 const X86Subtarget *Subtarget) {
21641 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
21642 // (and (i32 x86isd::setcc_carry), 1)
21643 // This eliminates the zext. This transformation is necessary because
21644 // ISD::SETCC is always legalized to i8.
21646 SDValue N0 = N->getOperand(0);
21647 EVT VT = N->getValueType(0);
21649 if (N0.getOpcode() == ISD::AND &&
21651 N0.getOperand(0).hasOneUse()) {
21652 SDValue N00 = N0.getOperand(0);
21653 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21654 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21655 if (!C || C->getZExtValue() != 1)
21657 return DAG.getNode(ISD::AND, dl, VT,
21658 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21659 N00.getOperand(0), N00.getOperand(1)),
21660 DAG.getConstant(1, VT));
21664 if (N0.getOpcode() == ISD::TRUNCATE &&
21666 N0.getOperand(0).hasOneUse()) {
21667 SDValue N00 = N0.getOperand(0);
21668 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21669 return DAG.getNode(ISD::AND, dl, VT,
21670 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21671 N00.getOperand(0), N00.getOperand(1)),
21672 DAG.getConstant(1, VT));
21675 if (VT.is256BitVector()) {
21676 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21684 // Optimize x == -y --> x+y == 0
21685 // x != -y --> x+y != 0
21686 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21687 const X86Subtarget* Subtarget) {
21688 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21689 SDValue LHS = N->getOperand(0);
21690 SDValue RHS = N->getOperand(1);
21691 EVT VT = N->getValueType(0);
21694 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21695 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21696 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21697 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21698 LHS.getValueType(), RHS, LHS.getOperand(1));
21699 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21700 addV, DAG.getConstant(0, addV.getValueType()), CC);
21702 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
21703 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
21704 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
21705 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21706 RHS.getValueType(), LHS, RHS.getOperand(1));
21707 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21708 addV, DAG.getConstant(0, addV.getValueType()), CC);
21711 if (VT.getScalarType() == MVT::i1) {
21712 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
21713 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
21714 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
21715 if (!IsSEXT0 && !IsVZero0)
21717 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
21718 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
21719 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
21721 if (!IsSEXT1 && !IsVZero1)
21724 if (IsSEXT0 && IsVZero1) {
21725 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
21726 if (CC == ISD::SETEQ)
21727 return DAG.getNOT(DL, LHS.getOperand(0), VT);
21728 return LHS.getOperand(0);
21730 if (IsSEXT1 && IsVZero0) {
21731 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
21732 if (CC == ISD::SETEQ)
21733 return DAG.getNOT(DL, RHS.getOperand(0), VT);
21734 return RHS.getOperand(0);
21741 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
21742 const X86Subtarget *Subtarget) {
21744 MVT VT = N->getOperand(1)->getSimpleValueType(0);
21745 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
21746 "X86insertps is only defined for v4x32");
21748 SDValue Ld = N->getOperand(1);
21749 if (MayFoldLoad(Ld)) {
21750 // Extract the countS bits from the immediate so we can get the proper
21751 // address when narrowing the vector load to a specific element.
21752 // When the second source op is a memory address, interps doesn't use
21753 // countS and just gets an f32 from that address.
21754 unsigned DestIndex =
21755 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
21756 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
21760 // Create this as a scalar to vector to match the instruction pattern.
21761 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
21762 // countS bits are ignored when loading from memory on insertps, which
21763 // means we don't need to explicitly set them to 0.
21764 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
21765 LoadScalarToVector, N->getOperand(2));
21768 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
21769 // as "sbb reg,reg", since it can be extended without zext and produces
21770 // an all-ones bit which is more useful than 0/1 in some cases.
21771 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
21774 return DAG.getNode(ISD::AND, DL, VT,
21775 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21776 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
21777 DAG.getConstant(1, VT));
21778 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
21779 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
21780 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21781 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
21784 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
21785 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
21786 TargetLowering::DAGCombinerInfo &DCI,
21787 const X86Subtarget *Subtarget) {
21789 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
21790 SDValue EFLAGS = N->getOperand(1);
21792 if (CC == X86::COND_A) {
21793 // Try to convert COND_A into COND_B in an attempt to facilitate
21794 // materializing "setb reg".
21796 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
21797 // cannot take an immediate as its first operand.
21799 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
21800 EFLAGS.getValueType().isInteger() &&
21801 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
21802 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
21803 EFLAGS.getNode()->getVTList(),
21804 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
21805 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
21806 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
21810 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
21811 // a zext and produces an all-ones bit which is more useful than 0/1 in some
21813 if (CC == X86::COND_B)
21814 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
21818 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21819 if (Flags.getNode()) {
21820 SDValue Cond = DAG.getConstant(CC, MVT::i8);
21821 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
21827 // Optimize branch condition evaluation.
21829 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
21830 TargetLowering::DAGCombinerInfo &DCI,
21831 const X86Subtarget *Subtarget) {
21833 SDValue Chain = N->getOperand(0);
21834 SDValue Dest = N->getOperand(1);
21835 SDValue EFLAGS = N->getOperand(3);
21836 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
21840 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21841 if (Flags.getNode()) {
21842 SDValue Cond = DAG.getConstant(CC, MVT::i8);
21843 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
21850 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
21851 const X86TargetLowering *XTLI) {
21852 SDValue Op0 = N->getOperand(0);
21853 EVT InVT = Op0->getValueType(0);
21855 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21856 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21858 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21859 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21860 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21863 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21864 // a 32-bit target where SSE doesn't support i64->FP operations.
21865 if (Op0.getOpcode() == ISD::LOAD) {
21866 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21867 EVT VT = Ld->getValueType(0);
21868 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21869 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21870 !XTLI->getSubtarget()->is64Bit() &&
21872 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21873 Ld->getChain(), Op0, DAG);
21874 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21881 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21882 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21883 X86TargetLowering::DAGCombinerInfo &DCI) {
21884 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21885 // the result is either zero or one (depending on the input carry bit).
21886 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21887 if (X86::isZeroNode(N->getOperand(0)) &&
21888 X86::isZeroNode(N->getOperand(1)) &&
21889 // We don't have a good way to replace an EFLAGS use, so only do this when
21891 SDValue(N, 1).use_empty()) {
21893 EVT VT = N->getValueType(0);
21894 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21895 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21896 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21897 DAG.getConstant(X86::COND_B,MVT::i8),
21899 DAG.getConstant(1, VT));
21900 return DCI.CombineTo(N, Res1, CarryOut);
21906 // fold (add Y, (sete X, 0)) -> adc 0, Y
21907 // (add Y, (setne X, 0)) -> sbb -1, Y
21908 // (sub (sete X, 0), Y) -> sbb 0, Y
21909 // (sub (setne X, 0), Y) -> adc -1, Y
21910 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
21913 // Look through ZExts.
21914 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
21915 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
21918 SDValue SetCC = Ext.getOperand(0);
21919 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
21922 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
21923 if (CC != X86::COND_E && CC != X86::COND_NE)
21926 SDValue Cmp = SetCC.getOperand(1);
21927 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
21928 !X86::isZeroNode(Cmp.getOperand(1)) ||
21929 !Cmp.getOperand(0).getValueType().isInteger())
21932 SDValue CmpOp0 = Cmp.getOperand(0);
21933 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
21934 DAG.getConstant(1, CmpOp0.getValueType()));
21936 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
21937 if (CC == X86::COND_NE)
21938 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
21939 DL, OtherVal.getValueType(), OtherVal,
21940 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
21941 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
21942 DL, OtherVal.getValueType(), OtherVal,
21943 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
21946 /// PerformADDCombine - Do target-specific dag combines on integer adds.
21947 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
21948 const X86Subtarget *Subtarget) {
21949 EVT VT = N->getValueType(0);
21950 SDValue Op0 = N->getOperand(0);
21951 SDValue Op1 = N->getOperand(1);
21953 // Try to synthesize horizontal adds from adds of shuffles.
21954 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21955 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21956 isHorizontalBinOp(Op0, Op1, true))
21957 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
21959 return OptimizeConditionalInDecrement(N, DAG);
21962 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
21963 const X86Subtarget *Subtarget) {
21964 SDValue Op0 = N->getOperand(0);
21965 SDValue Op1 = N->getOperand(1);
21967 // X86 can't encode an immediate LHS of a sub. See if we can push the
21968 // negation into a preceding instruction.
21969 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
21970 // If the RHS of the sub is a XOR with one use and a constant, invert the
21971 // immediate. Then add one to the LHS of the sub so we can turn
21972 // X-Y -> X+~Y+1, saving one register.
21973 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
21974 isa<ConstantSDNode>(Op1.getOperand(1))) {
21975 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
21976 EVT VT = Op0.getValueType();
21977 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
21979 DAG.getConstant(~XorC, VT));
21980 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
21981 DAG.getConstant(C->getAPIntValue()+1, VT));
21985 // Try to synthesize horizontal adds from adds of shuffles.
21986 EVT VT = N->getValueType(0);
21987 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21988 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21989 isHorizontalBinOp(Op0, Op1, true))
21990 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
21992 return OptimizeConditionalInDecrement(N, DAG);
21995 /// performVZEXTCombine - Performs build vector combines
21996 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
21997 TargetLowering::DAGCombinerInfo &DCI,
21998 const X86Subtarget *Subtarget) {
21999 // (vzext (bitcast (vzext (x)) -> (vzext x)
22000 SDValue In = N->getOperand(0);
22001 while (In.getOpcode() == ISD::BITCAST)
22002 In = In.getOperand(0);
22004 if (In.getOpcode() != X86ISD::VZEXT)
22007 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22011 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22012 DAGCombinerInfo &DCI) const {
22013 SelectionDAG &DAG = DCI.DAG;
22014 switch (N->getOpcode()) {
22016 case ISD::EXTRACT_VECTOR_ELT:
22017 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22019 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22020 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22021 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
22022 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
22023 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
22024 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
22027 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
22028 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
22029 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
22030 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
22031 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
22032 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
22033 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
22034 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
22035 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
22037 case X86ISD::FOR: return PerformFORCombine(N, DAG);
22039 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
22040 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
22041 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
22042 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
22043 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
22044 case ISD::ANY_EXTEND:
22045 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
22046 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
22047 case ISD::SIGN_EXTEND_INREG:
22048 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22049 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22050 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
22051 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22052 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22053 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
22054 case X86ISD::SHUFP: // Handle all target specific shuffles
22055 case X86ISD::PALIGNR:
22056 case X86ISD::UNPCKH:
22057 case X86ISD::UNPCKL:
22058 case X86ISD::MOVHLPS:
22059 case X86ISD::MOVLHPS:
22060 case X86ISD::PSHUFD:
22061 case X86ISD::PSHUFHW:
22062 case X86ISD::PSHUFLW:
22063 case X86ISD::MOVSS:
22064 case X86ISD::MOVSD:
22065 case X86ISD::VPERMILP:
22066 case X86ISD::VPERM2X128:
22067 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22068 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
22069 case ISD::INTRINSIC_WO_CHAIN:
22070 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22071 case X86ISD::INSERTPS:
22072 return PerformINSERTPSCombine(N, DAG, Subtarget);
22073 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22079 /// isTypeDesirableForOp - Return true if the target has native support for
22080 /// the specified value type and it is 'desirable' to use the type for the
22081 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22082 /// instruction encodings are longer and some i16 instructions are slow.
22083 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22084 if (!isTypeLegal(VT))
22086 if (VT != MVT::i16)
22093 case ISD::SIGN_EXTEND:
22094 case ISD::ZERO_EXTEND:
22095 case ISD::ANY_EXTEND:
22108 /// IsDesirableToPromoteOp - This method query the target whether it is
22109 /// beneficial for dag combiner to promote the specified node. If true, it
22110 /// should return the desired promotion type by reference.
22111 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22112 EVT VT = Op.getValueType();
22113 if (VT != MVT::i16)
22116 bool Promote = false;
22117 bool Commute = false;
22118 switch (Op.getOpcode()) {
22121 LoadSDNode *LD = cast<LoadSDNode>(Op);
22122 // If the non-extending load has a single use and it's not live out, then it
22123 // might be folded.
22124 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22125 Op.hasOneUse()*/) {
22126 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22127 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22128 // The only case where we'd want to promote LOAD (rather then it being
22129 // promoted as an operand is when it's only use is liveout.
22130 if (UI->getOpcode() != ISD::CopyToReg)
22137 case ISD::SIGN_EXTEND:
22138 case ISD::ZERO_EXTEND:
22139 case ISD::ANY_EXTEND:
22144 SDValue N0 = Op.getOperand(0);
22145 // Look out for (store (shl (load), x)).
22146 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22159 SDValue N0 = Op.getOperand(0);
22160 SDValue N1 = Op.getOperand(1);
22161 if (!Commute && MayFoldLoad(N1))
22163 // Avoid disabling potential load folding opportunities.
22164 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22166 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22176 //===----------------------------------------------------------------------===//
22177 // X86 Inline Assembly Support
22178 //===----------------------------------------------------------------------===//
22181 // Helper to match a string separated by whitespace.
22182 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22183 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22185 for (unsigned i = 0, e = args.size(); i != e; ++i) {
22186 StringRef piece(*args[i]);
22187 if (!s.startswith(piece)) // Check if the piece matches.
22190 s = s.substr(piece.size());
22191 StringRef::size_type pos = s.find_first_not_of(" \t");
22192 if (pos == 0) // We matched a prefix.
22200 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22203 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22205 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22206 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22207 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22208 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22210 if (AsmPieces.size() == 3)
22212 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22219 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22220 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22222 std::string AsmStr = IA->getAsmString();
22224 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22225 if (!Ty || Ty->getBitWidth() % 16 != 0)
22228 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22229 SmallVector<StringRef, 4> AsmPieces;
22230 SplitString(AsmStr, AsmPieces, ";\n");
22232 switch (AsmPieces.size()) {
22233 default: return false;
22235 // FIXME: this should verify that we are targeting a 486 or better. If not,
22236 // we will turn this bswap into something that will be lowered to logical
22237 // ops instead of emitting the bswap asm. For now, we don't support 486 or
22238 // lower so don't worry about this.
22240 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22241 matchAsm(AsmPieces[0], "bswapl", "$0") ||
22242 matchAsm(AsmPieces[0], "bswapq", "$0") ||
22243 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22244 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22245 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22246 // No need to check constraints, nothing other than the equivalent of
22247 // "=r,0" would be valid here.
22248 return IntrinsicLowering::LowerToByteSwap(CI);
22251 // rorw $$8, ${0:w} --> llvm.bswap.i16
22252 if (CI->getType()->isIntegerTy(16) &&
22253 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22254 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22255 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22257 const std::string &ConstraintsStr = IA->getConstraintString();
22258 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22259 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22260 if (clobbersFlagRegisters(AsmPieces))
22261 return IntrinsicLowering::LowerToByteSwap(CI);
22265 if (CI->getType()->isIntegerTy(32) &&
22266 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22267 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22268 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22269 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22271 const std::string &ConstraintsStr = IA->getConstraintString();
22272 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22273 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22274 if (clobbersFlagRegisters(AsmPieces))
22275 return IntrinsicLowering::LowerToByteSwap(CI);
22278 if (CI->getType()->isIntegerTy(64)) {
22279 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22280 if (Constraints.size() >= 2 &&
22281 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22282 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22283 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
22284 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22285 matchAsm(AsmPieces[1], "bswap", "%edx") &&
22286 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22287 return IntrinsicLowering::LowerToByteSwap(CI);
22295 /// getConstraintType - Given a constraint letter, return the type of
22296 /// constraint it is for this target.
22297 X86TargetLowering::ConstraintType
22298 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22299 if (Constraint.size() == 1) {
22300 switch (Constraint[0]) {
22311 return C_RegisterClass;
22335 return TargetLowering::getConstraintType(Constraint);
22338 /// Examine constraint type and operand type and determine a weight value.
22339 /// This object must already have been set up with the operand type
22340 /// and the current alternative constraint selected.
22341 TargetLowering::ConstraintWeight
22342 X86TargetLowering::getSingleConstraintMatchWeight(
22343 AsmOperandInfo &info, const char *constraint) const {
22344 ConstraintWeight weight = CW_Invalid;
22345 Value *CallOperandVal = info.CallOperandVal;
22346 // If we don't have a value, we can't do a match,
22347 // but allow it at the lowest weight.
22348 if (!CallOperandVal)
22350 Type *type = CallOperandVal->getType();
22351 // Look at the constraint type.
22352 switch (*constraint) {
22354 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22365 if (CallOperandVal->getType()->isIntegerTy())
22366 weight = CW_SpecificReg;
22371 if (type->isFloatingPointTy())
22372 weight = CW_SpecificReg;
22375 if (type->isX86_MMXTy() && Subtarget->hasMMX())
22376 weight = CW_SpecificReg;
22380 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22381 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22382 weight = CW_Register;
22385 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22386 if (C->getZExtValue() <= 31)
22387 weight = CW_Constant;
22391 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22392 if (C->getZExtValue() <= 63)
22393 weight = CW_Constant;
22397 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22398 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22399 weight = CW_Constant;
22403 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22404 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22405 weight = CW_Constant;
22409 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22410 if (C->getZExtValue() <= 3)
22411 weight = CW_Constant;
22415 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22416 if (C->getZExtValue() <= 0xff)
22417 weight = CW_Constant;
22422 if (dyn_cast<ConstantFP>(CallOperandVal)) {
22423 weight = CW_Constant;
22427 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22428 if ((C->getSExtValue() >= -0x80000000LL) &&
22429 (C->getSExtValue() <= 0x7fffffffLL))
22430 weight = CW_Constant;
22434 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22435 if (C->getZExtValue() <= 0xffffffff)
22436 weight = CW_Constant;
22443 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22444 /// with another that has more specific requirements based on the type of the
22445 /// corresponding operand.
22446 const char *X86TargetLowering::
22447 LowerXConstraint(EVT ConstraintVT) const {
22448 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22449 // 'f' like normal targets.
22450 if (ConstraintVT.isFloatingPoint()) {
22451 if (Subtarget->hasSSE2())
22453 if (Subtarget->hasSSE1())
22457 return TargetLowering::LowerXConstraint(ConstraintVT);
22460 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22461 /// vector. If it is invalid, don't add anything to Ops.
22462 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22463 std::string &Constraint,
22464 std::vector<SDValue>&Ops,
22465 SelectionDAG &DAG) const {
22468 // Only support length 1 constraints for now.
22469 if (Constraint.length() > 1) return;
22471 char ConstraintLetter = Constraint[0];
22472 switch (ConstraintLetter) {
22475 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22476 if (C->getZExtValue() <= 31) {
22477 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22483 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22484 if (C->getZExtValue() <= 63) {
22485 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22491 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22492 if (isInt<8>(C->getSExtValue())) {
22493 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22499 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22500 if (C->getZExtValue() <= 255) {
22501 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22507 // 32-bit signed value
22508 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22509 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22510 C->getSExtValue())) {
22511 // Widen to 64 bits here to get it sign extended.
22512 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22515 // FIXME gcc accepts some relocatable values here too, but only in certain
22516 // memory models; it's complicated.
22521 // 32-bit unsigned value
22522 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22523 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22524 C->getZExtValue())) {
22525 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22529 // FIXME gcc accepts some relocatable values here too, but only in certain
22530 // memory models; it's complicated.
22534 // Literal immediates are always ok.
22535 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22536 // Widen to 64 bits here to get it sign extended.
22537 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22541 // In any sort of PIC mode addresses need to be computed at runtime by
22542 // adding in a register or some sort of table lookup. These can't
22543 // be used as immediates.
22544 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22547 // If we are in non-pic codegen mode, we allow the address of a global (with
22548 // an optional displacement) to be used with 'i'.
22549 GlobalAddressSDNode *GA = nullptr;
22550 int64_t Offset = 0;
22552 // Match either (GA), (GA+C), (GA+C1+C2), etc.
22554 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22555 Offset += GA->getOffset();
22557 } else if (Op.getOpcode() == ISD::ADD) {
22558 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22559 Offset += C->getZExtValue();
22560 Op = Op.getOperand(0);
22563 } else if (Op.getOpcode() == ISD::SUB) {
22564 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22565 Offset += -C->getZExtValue();
22566 Op = Op.getOperand(0);
22571 // Otherwise, this isn't something we can handle, reject it.
22575 const GlobalValue *GV = GA->getGlobal();
22576 // If we require an extra load to get this address, as in PIC mode, we
22577 // can't accept it.
22578 if (isGlobalStubReference(
22579 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22582 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22583 GA->getValueType(0), Offset);
22588 if (Result.getNode()) {
22589 Ops.push_back(Result);
22592 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22595 std::pair<unsigned, const TargetRegisterClass*>
22596 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22598 // First, see if this is a constraint that directly corresponds to an LLVM
22600 if (Constraint.size() == 1) {
22601 // GCC Constraint Letters
22602 switch (Constraint[0]) {
22604 // TODO: Slight differences here in allocation order and leaving
22605 // RIP in the class. Do they matter any more here than they do
22606 // in the normal allocation?
22607 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22608 if (Subtarget->is64Bit()) {
22609 if (VT == MVT::i32 || VT == MVT::f32)
22610 return std::make_pair(0U, &X86::GR32RegClass);
22611 if (VT == MVT::i16)
22612 return std::make_pair(0U, &X86::GR16RegClass);
22613 if (VT == MVT::i8 || VT == MVT::i1)
22614 return std::make_pair(0U, &X86::GR8RegClass);
22615 if (VT == MVT::i64 || VT == MVT::f64)
22616 return std::make_pair(0U, &X86::GR64RegClass);
22619 // 32-bit fallthrough
22620 case 'Q': // Q_REGS
22621 if (VT == MVT::i32 || VT == MVT::f32)
22622 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22623 if (VT == MVT::i16)
22624 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22625 if (VT == MVT::i8 || VT == MVT::i1)
22626 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22627 if (VT == MVT::i64)
22628 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22630 case 'r': // GENERAL_REGS
22631 case 'l': // INDEX_REGS
22632 if (VT == MVT::i8 || VT == MVT::i1)
22633 return std::make_pair(0U, &X86::GR8RegClass);
22634 if (VT == MVT::i16)
22635 return std::make_pair(0U, &X86::GR16RegClass);
22636 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22637 return std::make_pair(0U, &X86::GR32RegClass);
22638 return std::make_pair(0U, &X86::GR64RegClass);
22639 case 'R': // LEGACY_REGS
22640 if (VT == MVT::i8 || VT == MVT::i1)
22641 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22642 if (VT == MVT::i16)
22643 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22644 if (VT == MVT::i32 || !Subtarget->is64Bit())
22645 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
22646 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
22647 case 'f': // FP Stack registers.
22648 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
22649 // value to the correct fpstack register class.
22650 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
22651 return std::make_pair(0U, &X86::RFP32RegClass);
22652 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
22653 return std::make_pair(0U, &X86::RFP64RegClass);
22654 return std::make_pair(0U, &X86::RFP80RegClass);
22655 case 'y': // MMX_REGS if MMX allowed.
22656 if (!Subtarget->hasMMX()) break;
22657 return std::make_pair(0U, &X86::VR64RegClass);
22658 case 'Y': // SSE_REGS if SSE2 allowed
22659 if (!Subtarget->hasSSE2()) break;
22661 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
22662 if (!Subtarget->hasSSE1()) break;
22664 switch (VT.SimpleTy) {
22666 // Scalar SSE types.
22669 return std::make_pair(0U, &X86::FR32RegClass);
22672 return std::make_pair(0U, &X86::FR64RegClass);
22680 return std::make_pair(0U, &X86::VR128RegClass);
22688 return std::make_pair(0U, &X86::VR256RegClass);
22693 return std::make_pair(0U, &X86::VR512RegClass);
22699 // Use the default implementation in TargetLowering to convert the register
22700 // constraint into a member of a register class.
22701 std::pair<unsigned, const TargetRegisterClass*> Res;
22702 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
22704 // Not found as a standard register?
22706 // Map st(0) -> st(7) -> ST0
22707 if (Constraint.size() == 7 && Constraint[0] == '{' &&
22708 tolower(Constraint[1]) == 's' &&
22709 tolower(Constraint[2]) == 't' &&
22710 Constraint[3] == '(' &&
22711 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
22712 Constraint[5] == ')' &&
22713 Constraint[6] == '}') {
22715 Res.first = X86::ST0+Constraint[4]-'0';
22716 Res.second = &X86::RFP80RegClass;
22720 // GCC allows "st(0)" to be called just plain "st".
22721 if (StringRef("{st}").equals_lower(Constraint)) {
22722 Res.first = X86::ST0;
22723 Res.second = &X86::RFP80RegClass;
22728 if (StringRef("{flags}").equals_lower(Constraint)) {
22729 Res.first = X86::EFLAGS;
22730 Res.second = &X86::CCRRegClass;
22734 // 'A' means EAX + EDX.
22735 if (Constraint == "A") {
22736 Res.first = X86::EAX;
22737 Res.second = &X86::GR32_ADRegClass;
22743 // Otherwise, check to see if this is a register class of the wrong value
22744 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
22745 // turn into {ax},{dx}.
22746 if (Res.second->hasType(VT))
22747 return Res; // Correct type already, nothing to do.
22749 // All of the single-register GCC register classes map their values onto
22750 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
22751 // really want an 8-bit or 32-bit register, map to the appropriate register
22752 // class and return the appropriate register.
22753 if (Res.second == &X86::GR16RegClass) {
22754 if (VT == MVT::i8 || VT == MVT::i1) {
22755 unsigned DestReg = 0;
22756 switch (Res.first) {
22758 case X86::AX: DestReg = X86::AL; break;
22759 case X86::DX: DestReg = X86::DL; break;
22760 case X86::CX: DestReg = X86::CL; break;
22761 case X86::BX: DestReg = X86::BL; break;
22764 Res.first = DestReg;
22765 Res.second = &X86::GR8RegClass;
22767 } else if (VT == MVT::i32 || VT == MVT::f32) {
22768 unsigned DestReg = 0;
22769 switch (Res.first) {
22771 case X86::AX: DestReg = X86::EAX; break;
22772 case X86::DX: DestReg = X86::EDX; break;
22773 case X86::CX: DestReg = X86::ECX; break;
22774 case X86::BX: DestReg = X86::EBX; break;
22775 case X86::SI: DestReg = X86::ESI; break;
22776 case X86::DI: DestReg = X86::EDI; break;
22777 case X86::BP: DestReg = X86::EBP; break;
22778 case X86::SP: DestReg = X86::ESP; break;
22781 Res.first = DestReg;
22782 Res.second = &X86::GR32RegClass;
22784 } else if (VT == MVT::i64 || VT == MVT::f64) {
22785 unsigned DestReg = 0;
22786 switch (Res.first) {
22788 case X86::AX: DestReg = X86::RAX; break;
22789 case X86::DX: DestReg = X86::RDX; break;
22790 case X86::CX: DestReg = X86::RCX; break;
22791 case X86::BX: DestReg = X86::RBX; break;
22792 case X86::SI: DestReg = X86::RSI; break;
22793 case X86::DI: DestReg = X86::RDI; break;
22794 case X86::BP: DestReg = X86::RBP; break;
22795 case X86::SP: DestReg = X86::RSP; break;
22798 Res.first = DestReg;
22799 Res.second = &X86::GR64RegClass;
22802 } else if (Res.second == &X86::FR32RegClass ||
22803 Res.second == &X86::FR64RegClass ||
22804 Res.second == &X86::VR128RegClass ||
22805 Res.second == &X86::VR256RegClass ||
22806 Res.second == &X86::FR32XRegClass ||
22807 Res.second == &X86::FR64XRegClass ||
22808 Res.second == &X86::VR128XRegClass ||
22809 Res.second == &X86::VR256XRegClass ||
22810 Res.second == &X86::VR512RegClass) {
22811 // Handle references to XMM physical registers that got mapped into the
22812 // wrong class. This can happen with constraints like {xmm0} where the
22813 // target independent register mapper will just pick the first match it can
22814 // find, ignoring the required type.
22816 if (VT == MVT::f32 || VT == MVT::i32)
22817 Res.second = &X86::FR32RegClass;
22818 else if (VT == MVT::f64 || VT == MVT::i64)
22819 Res.second = &X86::FR64RegClass;
22820 else if (X86::VR128RegClass.hasType(VT))
22821 Res.second = &X86::VR128RegClass;
22822 else if (X86::VR256RegClass.hasType(VT))
22823 Res.second = &X86::VR256RegClass;
22824 else if (X86::VR512RegClass.hasType(VT))
22825 Res.second = &X86::VR512RegClass;
22831 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
22833 // Scaling factors are not free at all.
22834 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
22835 // will take 2 allocations in the out of order engine instead of 1
22836 // for plain addressing mode, i.e. inst (reg1).
22838 // vaddps (%rsi,%drx), %ymm0, %ymm1
22839 // Requires two allocations (one for the load, one for the computation)
22841 // vaddps (%rsi), %ymm0, %ymm1
22842 // Requires just 1 allocation, i.e., freeing allocations for other operations
22843 // and having less micro operations to execute.
22845 // For some X86 architectures, this is even worse because for instance for
22846 // stores, the complex addressing mode forces the instruction to use the
22847 // "load" ports instead of the dedicated "store" port.
22848 // E.g., on Haswell:
22849 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
22850 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
22851 if (isLegalAddressingMode(AM, Ty))
22852 // Scale represents reg2 * scale, thus account for 1
22853 // as soon as we use a second register.
22854 return AM.Scale != 0;
22858 bool X86TargetLowering::isTargetFTOL() const {
22859 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();