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"
52 #include "X86IntrinsicsInfo.h"
58 #define DEBUG_TYPE "x86-isel"
60 STATISTIC(NumTailCalls, "Number of tail calls");
62 static cl::opt<bool> ExperimentalVectorWideningLegalization(
63 "x86-experimental-vector-widening-legalization", cl::init(false),
64 cl::desc("Enable an experimental vector type legalization through widening "
65 "rather than promotion."),
68 static cl::opt<bool> ExperimentalVectorShuffleLowering(
69 "x86-experimental-vector-shuffle-lowering", cl::init(false),
70 cl::desc("Enable an experimental vector shuffle lowering code path."),
73 // Forward declarations.
74 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
77 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
78 SelectionDAG &DAG, SDLoc dl,
79 unsigned vectorWidth) {
80 assert((vectorWidth == 128 || vectorWidth == 256) &&
81 "Unsupported vector width");
82 EVT VT = Vec.getValueType();
83 EVT ElVT = VT.getVectorElementType();
84 unsigned Factor = VT.getSizeInBits()/vectorWidth;
85 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
86 VT.getVectorNumElements()/Factor);
88 // Extract from UNDEF is UNDEF.
89 if (Vec.getOpcode() == ISD::UNDEF)
90 return DAG.getUNDEF(ResultVT);
92 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
93 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
95 // This is the index of the first element of the vectorWidth-bit chunk
97 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
100 // If the input is a buildvector just emit a smaller one.
101 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
102 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
103 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
106 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
107 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
113 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
114 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
115 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
116 /// instructions or a simple subregister reference. Idx is an index in the
117 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
118 /// lowering EXTRACT_VECTOR_ELT operations easier.
119 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
120 SelectionDAG &DAG, SDLoc dl) {
121 assert((Vec.getValueType().is256BitVector() ||
122 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
123 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
126 /// Generate a DAG to grab 256-bits from a 512-bit vector.
127 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
128 SelectionDAG &DAG, SDLoc dl) {
129 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
130 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
133 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
134 unsigned IdxVal, SelectionDAG &DAG,
135 SDLoc dl, unsigned vectorWidth) {
136 assert((vectorWidth == 128 || vectorWidth == 256) &&
137 "Unsupported vector width");
138 // Inserting UNDEF is Result
139 if (Vec.getOpcode() == ISD::UNDEF)
141 EVT VT = Vec.getValueType();
142 EVT ElVT = VT.getVectorElementType();
143 EVT ResultVT = Result.getValueType();
145 // Insert the relevant vectorWidth bits.
146 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
148 // This is the index of the first element of the vectorWidth-bit chunk
150 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
153 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
154 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
157 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
158 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
159 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
160 /// simple superregister reference. Idx is an index in the 128 bits
161 /// we want. It need not be aligned to a 128-bit bounday. That makes
162 /// lowering INSERT_VECTOR_ELT operations easier.
163 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
164 unsigned IdxVal, SelectionDAG &DAG,
166 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
167 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
170 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
171 unsigned IdxVal, SelectionDAG &DAG,
173 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
174 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
177 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
178 /// instructions. This is used because creating CONCAT_VECTOR nodes of
179 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
180 /// large BUILD_VECTORS.
181 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
182 unsigned NumElems, SelectionDAG &DAG,
184 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
185 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
188 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
189 unsigned NumElems, SelectionDAG &DAG,
191 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
192 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
195 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
196 if (TT.isOSBinFormatMachO()) {
197 if (TT.getArch() == Triple::x86_64)
198 return new X86_64MachoTargetObjectFile();
199 return new TargetLoweringObjectFileMachO();
203 return new X86LinuxTargetObjectFile();
204 if (TT.isOSBinFormatELF())
205 return new TargetLoweringObjectFileELF();
206 if (TT.isKnownWindowsMSVCEnvironment())
207 return new X86WindowsTargetObjectFile();
208 if (TT.isOSBinFormatCOFF())
209 return new TargetLoweringObjectFileCOFF();
210 llvm_unreachable("unknown subtarget type");
213 // FIXME: This should stop caching the target machine as soon as
214 // we can remove resetOperationActions et al.
215 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
216 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
217 Subtarget = &TM.getSubtarget<X86Subtarget>();
218 X86ScalarSSEf64 = Subtarget->hasSSE2();
219 X86ScalarSSEf32 = Subtarget->hasSSE1();
220 TD = getDataLayout();
222 resetOperationActions();
225 void X86TargetLowering::resetOperationActions() {
226 const TargetMachine &TM = getTargetMachine();
227 static bool FirstTimeThrough = true;
229 // If none of the target options have changed, then we don't need to reset the
230 // operation actions.
231 if (!FirstTimeThrough && TO == TM.Options) return;
233 if (!FirstTimeThrough) {
234 // Reinitialize the actions.
236 FirstTimeThrough = false;
241 // Set up the TargetLowering object.
242 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
244 // X86 is weird, it always uses i8 for shift amounts and setcc results.
245 setBooleanContents(ZeroOrOneBooleanContent);
246 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
247 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
249 // For 64-bit since we have so many registers use the ILP scheduler, for
250 // 32-bit code use the register pressure specific scheduling.
251 // For Atom, always use ILP scheduling.
252 if (Subtarget->isAtom())
253 setSchedulingPreference(Sched::ILP);
254 else if (Subtarget->is64Bit())
255 setSchedulingPreference(Sched::ILP);
257 setSchedulingPreference(Sched::RegPressure);
258 const X86RegisterInfo *RegInfo =
259 TM.getSubtarget<X86Subtarget>().getRegisterInfo();
260 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
262 // Bypass expensive divides on Atom when compiling with O2
263 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
264 addBypassSlowDiv(32, 8);
265 if (Subtarget->is64Bit())
266 addBypassSlowDiv(64, 16);
269 if (Subtarget->isTargetKnownWindowsMSVC()) {
270 // Setup Windows compiler runtime calls.
271 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
272 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
273 setLibcallName(RTLIB::SREM_I64, "_allrem");
274 setLibcallName(RTLIB::UREM_I64, "_aullrem");
275 setLibcallName(RTLIB::MUL_I64, "_allmul");
276 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
277 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
278 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
279 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
280 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
282 // The _ftol2 runtime function has an unusual calling conv, which
283 // is modeled by a special pseudo-instruction.
284 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
285 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
286 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
287 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
290 if (Subtarget->isTargetDarwin()) {
291 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
292 setUseUnderscoreSetJmp(false);
293 setUseUnderscoreLongJmp(false);
294 } else if (Subtarget->isTargetWindowsGNU()) {
295 // MS runtime is weird: it exports _setjmp, but longjmp!
296 setUseUnderscoreSetJmp(true);
297 setUseUnderscoreLongJmp(false);
299 setUseUnderscoreSetJmp(true);
300 setUseUnderscoreLongJmp(true);
303 // Set up the register classes.
304 addRegisterClass(MVT::i8, &X86::GR8RegClass);
305 addRegisterClass(MVT::i16, &X86::GR16RegClass);
306 addRegisterClass(MVT::i32, &X86::GR32RegClass);
307 if (Subtarget->is64Bit())
308 addRegisterClass(MVT::i64, &X86::GR64RegClass);
310 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
312 // We don't accept any truncstore of integer registers.
313 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
314 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
315 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
316 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
317 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
318 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
320 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
322 // SETOEQ and SETUNE require checking two conditions.
323 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
324 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
325 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
326 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
327 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
328 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
330 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
332 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
333 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
334 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
336 if (Subtarget->is64Bit()) {
337 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
338 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
339 } else if (!TM.Options.UseSoftFloat) {
340 // We have an algorithm for SSE2->double, and we turn this into a
341 // 64-bit FILD followed by conditional FADD for other targets.
342 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
343 // We have an algorithm for SSE2, and we turn this into a 64-bit
344 // FILD for other targets.
345 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
348 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
350 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
351 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
353 if (!TM.Options.UseSoftFloat) {
354 // SSE has no i16 to fp conversion, only i32
355 if (X86ScalarSSEf32) {
356 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
357 // f32 and f64 cases are Legal, f80 case is not
358 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
360 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
361 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
364 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
365 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
368 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
369 // are Legal, f80 is custom lowered.
370 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
371 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
373 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
375 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
376 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
378 if (X86ScalarSSEf32) {
379 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
380 // f32 and f64 cases are Legal, f80 case is not
381 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
383 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
384 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
387 // Handle FP_TO_UINT by promoting the destination to a larger signed
389 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
390 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
391 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
393 if (Subtarget->is64Bit()) {
394 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
395 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
396 } else if (!TM.Options.UseSoftFloat) {
397 // Since AVX is a superset of SSE3, only check for SSE here.
398 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
399 // Expand FP_TO_UINT into a select.
400 // FIXME: We would like to use a Custom expander here eventually to do
401 // the optimal thing for SSE vs. the default expansion in the legalizer.
402 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
404 // With SSE3 we can use fisttpll to convert to a signed i64; without
405 // SSE, we're stuck with a fistpll.
406 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
409 if (isTargetFTOL()) {
410 // Use the _ftol2 runtime function, which has a pseudo-instruction
411 // to handle its weird calling convention.
412 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
415 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
416 if (!X86ScalarSSEf64) {
417 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
418 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
419 if (Subtarget->is64Bit()) {
420 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
421 // Without SSE, i64->f64 goes through memory.
422 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
426 // Scalar integer divide and remainder are lowered to use operations that
427 // produce two results, to match the available instructions. This exposes
428 // the two-result form to trivial CSE, which is able to combine x/y and x%y
429 // into a single instruction.
431 // Scalar integer multiply-high is also lowered to use two-result
432 // operations, to match the available instructions. However, plain multiply
433 // (low) operations are left as Legal, as there are single-result
434 // instructions for this in x86. Using the two-result multiply instructions
435 // when both high and low results are needed must be arranged by dagcombine.
436 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
438 setOperationAction(ISD::MULHS, VT, Expand);
439 setOperationAction(ISD::MULHU, VT, Expand);
440 setOperationAction(ISD::SDIV, VT, Expand);
441 setOperationAction(ISD::UDIV, VT, Expand);
442 setOperationAction(ISD::SREM, VT, Expand);
443 setOperationAction(ISD::UREM, VT, Expand);
445 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
446 setOperationAction(ISD::ADDC, VT, Custom);
447 setOperationAction(ISD::ADDE, VT, Custom);
448 setOperationAction(ISD::SUBC, VT, Custom);
449 setOperationAction(ISD::SUBE, VT, Custom);
452 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
453 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
454 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
455 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
456 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
457 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
458 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
459 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
460 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
461 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
462 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
463 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
464 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
465 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
466 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
467 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
468 if (Subtarget->is64Bit())
469 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
470 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
471 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
472 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
473 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
474 setOperationAction(ISD::FREM , MVT::f32 , Expand);
475 setOperationAction(ISD::FREM , MVT::f64 , Expand);
476 setOperationAction(ISD::FREM , MVT::f80 , Expand);
477 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
479 // Promote the i8 variants and force them on up to i32 which has a shorter
481 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
482 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
483 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
484 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
485 if (Subtarget->hasBMI()) {
486 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
487 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
488 if (Subtarget->is64Bit())
489 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
491 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
492 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
493 if (Subtarget->is64Bit())
494 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
497 if (Subtarget->hasLZCNT()) {
498 // When promoting the i8 variants, force them to i32 for a shorter
500 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
501 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
502 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
503 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
504 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
505 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
506 if (Subtarget->is64Bit())
507 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
509 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
510 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
511 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
512 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
513 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
514 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
515 if (Subtarget->is64Bit()) {
516 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
517 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
521 // Special handling for half-precision floating point conversions.
522 // If we don't have F16C support, then lower half float conversions
523 // into library calls.
524 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
525 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
526 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
529 // There's never any support for operations beyond MVT::f32.
530 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
531 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
532 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
533 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
535 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
536 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
537 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
538 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
540 if (Subtarget->hasPOPCNT()) {
541 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
543 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
544 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
545 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
546 if (Subtarget->is64Bit())
547 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
550 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
552 if (!Subtarget->hasMOVBE())
553 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
555 // These should be promoted to a larger select which is supported.
556 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
557 // X86 wants to expand cmov itself.
558 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
559 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
560 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
561 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
562 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
563 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
564 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
565 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
566 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
567 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
568 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
569 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
570 if (Subtarget->is64Bit()) {
571 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
572 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
574 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
575 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
576 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
577 // support continuation, user-level threading, and etc.. As a result, no
578 // other SjLj exception interfaces are implemented and please don't build
579 // your own exception handling based on them.
580 // LLVM/Clang supports zero-cost DWARF exception handling.
581 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
582 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
585 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
586 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
587 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
588 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
589 if (Subtarget->is64Bit())
590 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
591 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
592 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
593 if (Subtarget->is64Bit()) {
594 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
595 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
596 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
597 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
598 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
600 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
601 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
602 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
603 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
604 if (Subtarget->is64Bit()) {
605 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
606 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
607 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
610 if (Subtarget->hasSSE1())
611 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
613 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
615 // Expand certain atomics
616 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
618 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
619 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
620 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
623 if (Subtarget->hasCmpxchg16b()) {
624 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
627 // FIXME - use subtarget debug flags
628 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
629 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
630 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
633 if (Subtarget->is64Bit()) {
634 setExceptionPointerRegister(X86::RAX);
635 setExceptionSelectorRegister(X86::RDX);
637 setExceptionPointerRegister(X86::EAX);
638 setExceptionSelectorRegister(X86::EDX);
640 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
641 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
643 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
644 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
646 setOperationAction(ISD::TRAP, MVT::Other, Legal);
647 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
649 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
650 setOperationAction(ISD::VASTART , MVT::Other, Custom);
651 setOperationAction(ISD::VAEND , MVT::Other, Expand);
652 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
653 // TargetInfo::X86_64ABIBuiltinVaList
654 setOperationAction(ISD::VAARG , MVT::Other, Custom);
655 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
657 // TargetInfo::CharPtrBuiltinVaList
658 setOperationAction(ISD::VAARG , MVT::Other, Expand);
659 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
662 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
663 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
665 setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
667 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
668 // f32 and f64 use SSE.
669 // Set up the FP register classes.
670 addRegisterClass(MVT::f32, &X86::FR32RegClass);
671 addRegisterClass(MVT::f64, &X86::FR64RegClass);
673 // Use ANDPD to simulate FABS.
674 setOperationAction(ISD::FABS , MVT::f64, Custom);
675 setOperationAction(ISD::FABS , MVT::f32, Custom);
677 // Use XORP to simulate FNEG.
678 setOperationAction(ISD::FNEG , MVT::f64, Custom);
679 setOperationAction(ISD::FNEG , MVT::f32, Custom);
681 // Use ANDPD and ORPD to simulate FCOPYSIGN.
682 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
683 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
685 // Lower this to FGETSIGNx86 plus an AND.
686 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
687 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
689 // We don't support sin/cos/fmod
690 setOperationAction(ISD::FSIN , MVT::f64, Expand);
691 setOperationAction(ISD::FCOS , MVT::f64, Expand);
692 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
693 setOperationAction(ISD::FSIN , MVT::f32, Expand);
694 setOperationAction(ISD::FCOS , MVT::f32, Expand);
695 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
697 // Expand FP immediates into loads from the stack, except for the special
699 addLegalFPImmediate(APFloat(+0.0)); // xorpd
700 addLegalFPImmediate(APFloat(+0.0f)); // xorps
701 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
702 // Use SSE for f32, x87 for f64.
703 // Set up the FP register classes.
704 addRegisterClass(MVT::f32, &X86::FR32RegClass);
705 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
707 // Use ANDPS to simulate FABS.
708 setOperationAction(ISD::FABS , MVT::f32, Custom);
710 // Use XORP to simulate FNEG.
711 setOperationAction(ISD::FNEG , MVT::f32, Custom);
713 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
715 // Use ANDPS and ORPS to simulate FCOPYSIGN.
716 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
717 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
719 // We don't support sin/cos/fmod
720 setOperationAction(ISD::FSIN , MVT::f32, Expand);
721 setOperationAction(ISD::FCOS , MVT::f32, Expand);
722 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
724 // Special cases we handle for FP constants.
725 addLegalFPImmediate(APFloat(+0.0f)); // xorps
726 addLegalFPImmediate(APFloat(+0.0)); // FLD0
727 addLegalFPImmediate(APFloat(+1.0)); // FLD1
728 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
729 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
731 if (!TM.Options.UnsafeFPMath) {
732 setOperationAction(ISD::FSIN , MVT::f64, Expand);
733 setOperationAction(ISD::FCOS , MVT::f64, Expand);
734 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
736 } else if (!TM.Options.UseSoftFloat) {
737 // f32 and f64 in x87.
738 // Set up the FP register classes.
739 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
740 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
742 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
743 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
744 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
745 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
747 if (!TM.Options.UnsafeFPMath) {
748 setOperationAction(ISD::FSIN , MVT::f64, Expand);
749 setOperationAction(ISD::FSIN , MVT::f32, Expand);
750 setOperationAction(ISD::FCOS , MVT::f64, Expand);
751 setOperationAction(ISD::FCOS , MVT::f32, Expand);
752 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
753 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
755 addLegalFPImmediate(APFloat(+0.0)); // FLD0
756 addLegalFPImmediate(APFloat(+1.0)); // FLD1
757 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
758 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
759 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
760 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
761 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
762 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
765 // We don't support FMA.
766 setOperationAction(ISD::FMA, MVT::f64, Expand);
767 setOperationAction(ISD::FMA, MVT::f32, Expand);
769 // Long double always uses X87.
770 if (!TM.Options.UseSoftFloat) {
771 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
772 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
773 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
775 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
776 addLegalFPImmediate(TmpFlt); // FLD0
778 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
781 APFloat TmpFlt2(+1.0);
782 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
784 addLegalFPImmediate(TmpFlt2); // FLD1
785 TmpFlt2.changeSign();
786 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
789 if (!TM.Options.UnsafeFPMath) {
790 setOperationAction(ISD::FSIN , MVT::f80, Expand);
791 setOperationAction(ISD::FCOS , MVT::f80, Expand);
792 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
795 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
796 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
797 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
798 setOperationAction(ISD::FRINT, MVT::f80, Expand);
799 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
800 setOperationAction(ISD::FMA, MVT::f80, Expand);
803 // Always use a library call for pow.
804 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
805 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
806 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
808 setOperationAction(ISD::FLOG, MVT::f80, Expand);
809 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
810 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
811 setOperationAction(ISD::FEXP, MVT::f80, Expand);
812 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
814 // First set operation action for all vector types to either promote
815 // (for widening) or expand (for scalarization). Then we will selectively
816 // turn on ones that can be effectively codegen'd.
817 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
818 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
819 MVT VT = (MVT::SimpleValueType)i;
820 setOperationAction(ISD::ADD , VT, Expand);
821 setOperationAction(ISD::SUB , VT, Expand);
822 setOperationAction(ISD::FADD, VT, Expand);
823 setOperationAction(ISD::FNEG, VT, Expand);
824 setOperationAction(ISD::FSUB, VT, Expand);
825 setOperationAction(ISD::MUL , VT, Expand);
826 setOperationAction(ISD::FMUL, VT, Expand);
827 setOperationAction(ISD::SDIV, VT, Expand);
828 setOperationAction(ISD::UDIV, VT, Expand);
829 setOperationAction(ISD::FDIV, VT, Expand);
830 setOperationAction(ISD::SREM, VT, Expand);
831 setOperationAction(ISD::UREM, VT, Expand);
832 setOperationAction(ISD::LOAD, VT, Expand);
833 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
834 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
835 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
836 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
837 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
838 setOperationAction(ISD::FABS, VT, Expand);
839 setOperationAction(ISD::FSIN, VT, Expand);
840 setOperationAction(ISD::FSINCOS, VT, Expand);
841 setOperationAction(ISD::FCOS, VT, Expand);
842 setOperationAction(ISD::FSINCOS, VT, Expand);
843 setOperationAction(ISD::FREM, VT, Expand);
844 setOperationAction(ISD::FMA, VT, Expand);
845 setOperationAction(ISD::FPOWI, VT, Expand);
846 setOperationAction(ISD::FSQRT, VT, Expand);
847 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
848 setOperationAction(ISD::FFLOOR, VT, Expand);
849 setOperationAction(ISD::FCEIL, VT, Expand);
850 setOperationAction(ISD::FTRUNC, VT, Expand);
851 setOperationAction(ISD::FRINT, VT, Expand);
852 setOperationAction(ISD::FNEARBYINT, VT, Expand);
853 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
854 setOperationAction(ISD::MULHS, VT, Expand);
855 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
856 setOperationAction(ISD::MULHU, VT, Expand);
857 setOperationAction(ISD::SDIVREM, VT, Expand);
858 setOperationAction(ISD::UDIVREM, VT, Expand);
859 setOperationAction(ISD::FPOW, VT, Expand);
860 setOperationAction(ISD::CTPOP, VT, Expand);
861 setOperationAction(ISD::CTTZ, VT, Expand);
862 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
863 setOperationAction(ISD::CTLZ, VT, Expand);
864 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
865 setOperationAction(ISD::SHL, VT, Expand);
866 setOperationAction(ISD::SRA, VT, Expand);
867 setOperationAction(ISD::SRL, VT, Expand);
868 setOperationAction(ISD::ROTL, VT, Expand);
869 setOperationAction(ISD::ROTR, VT, Expand);
870 setOperationAction(ISD::BSWAP, VT, Expand);
871 setOperationAction(ISD::SETCC, VT, Expand);
872 setOperationAction(ISD::FLOG, VT, Expand);
873 setOperationAction(ISD::FLOG2, VT, Expand);
874 setOperationAction(ISD::FLOG10, VT, Expand);
875 setOperationAction(ISD::FEXP, VT, Expand);
876 setOperationAction(ISD::FEXP2, VT, Expand);
877 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
878 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
879 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
880 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
881 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
882 setOperationAction(ISD::TRUNCATE, VT, Expand);
883 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
884 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
885 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
886 setOperationAction(ISD::VSELECT, VT, Expand);
887 setOperationAction(ISD::SELECT_CC, VT, Expand);
888 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
889 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
890 setTruncStoreAction(VT,
891 (MVT::SimpleValueType)InnerVT, Expand);
892 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
893 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
895 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
896 // we have to deal with them whether we ask for Expansion or not. Setting
897 // Expand causes its own optimisation problems though, so leave them legal.
898 if (VT.getVectorElementType() == MVT::i1)
899 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
902 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
903 // with -msoft-float, disable use of MMX as well.
904 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
905 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
906 // No operations on x86mmx supported, everything uses intrinsics.
909 // MMX-sized vectors (other than x86mmx) are expected to be expanded
910 // into smaller operations.
911 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
912 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
913 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
914 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
915 setOperationAction(ISD::AND, MVT::v8i8, Expand);
916 setOperationAction(ISD::AND, MVT::v4i16, Expand);
917 setOperationAction(ISD::AND, MVT::v2i32, Expand);
918 setOperationAction(ISD::AND, MVT::v1i64, Expand);
919 setOperationAction(ISD::OR, MVT::v8i8, Expand);
920 setOperationAction(ISD::OR, MVT::v4i16, Expand);
921 setOperationAction(ISD::OR, MVT::v2i32, Expand);
922 setOperationAction(ISD::OR, MVT::v1i64, Expand);
923 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
924 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
925 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
926 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
927 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
928 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
929 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
930 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
931 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
932 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
933 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
934 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
935 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
936 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
937 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
938 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
939 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
941 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
942 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
944 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
945 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
946 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
947 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
948 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
949 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
950 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
951 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
952 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
953 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
954 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
955 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
958 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
959 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
961 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
962 // registers cannot be used even for integer operations.
963 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
964 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
965 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
966 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
968 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
969 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
970 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
971 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
972 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
973 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
974 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
975 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
976 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
977 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
978 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
979 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
980 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
981 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
982 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
983 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
984 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
985 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
986 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
987 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
988 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
989 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
991 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
992 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
993 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
994 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
996 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
997 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
998 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
999 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1000 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1002 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1003 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1004 MVT VT = (MVT::SimpleValueType)i;
1005 // Do not attempt to custom lower non-power-of-2 vectors
1006 if (!isPowerOf2_32(VT.getVectorNumElements()))
1008 // Do not attempt to custom lower non-128-bit vectors
1009 if (!VT.is128BitVector())
1011 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1012 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1013 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1016 // We support custom legalizing of sext and anyext loads for specific
1017 // memory vector types which we can load as a scalar (or sequence of
1018 // scalars) and extend in-register to a legal 128-bit vector type. For sext
1019 // loads these must work with a single scalar load.
1020 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1021 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1022 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1023 setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1024 setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1025 setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1026 setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1027 setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1028 setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1030 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1031 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1032 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1033 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1034 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1035 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1037 if (Subtarget->is64Bit()) {
1038 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1039 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1042 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1043 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1044 MVT VT = (MVT::SimpleValueType)i;
1046 // Do not attempt to promote non-128-bit vectors
1047 if (!VT.is128BitVector())
1050 setOperationAction(ISD::AND, VT, Promote);
1051 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1052 setOperationAction(ISD::OR, VT, Promote);
1053 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1054 setOperationAction(ISD::XOR, VT, Promote);
1055 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1056 setOperationAction(ISD::LOAD, VT, Promote);
1057 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1058 setOperationAction(ISD::SELECT, VT, Promote);
1059 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1062 // Custom lower v2i64 and v2f64 selects.
1063 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1064 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1065 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1066 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1068 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1069 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1071 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1072 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1073 // As there is no 64-bit GPR available, we need build a special custom
1074 // sequence to convert from v2i32 to v2f32.
1075 if (!Subtarget->is64Bit())
1076 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1078 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1079 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1081 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1083 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1084 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1085 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1088 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1089 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1090 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1091 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1092 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1093 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1094 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1095 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1096 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1097 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1098 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1100 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1101 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1102 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1103 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1104 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1105 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1106 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1107 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1108 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1109 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1111 // FIXME: Do we need to handle scalar-to-vector here?
1112 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1114 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1115 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1116 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1117 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1118 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1119 // There is no BLENDI for byte vectors. We don't need to custom lower
1120 // some vselects for now.
1121 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1123 // SSE41 brings specific instructions for doing vector sign extend even in
1124 // cases where we don't have SRA.
1125 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1126 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1127 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1129 // i8 and i16 vectors are custom because the source register and source
1130 // source memory operand types are not the same width. f32 vectors are
1131 // custom since the immediate controlling the insert encodes additional
1133 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1134 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1135 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1136 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1138 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1139 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1140 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1141 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1143 // FIXME: these should be Legal, but that's only for the case where
1144 // the index is constant. For now custom expand to deal with that.
1145 if (Subtarget->is64Bit()) {
1146 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1147 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1151 if (Subtarget->hasSSE2()) {
1152 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1153 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1155 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1156 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1158 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1159 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1161 // In the customized shift lowering, the legal cases in AVX2 will be
1163 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1164 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1166 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1167 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1169 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1172 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1173 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1174 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1175 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1176 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1177 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1178 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1180 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1181 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1182 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1184 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1185 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1186 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1187 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1188 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1189 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1190 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1191 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1192 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1193 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1194 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1195 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1197 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1198 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1199 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1200 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1201 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1202 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1203 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1204 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1205 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1206 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1207 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1208 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1210 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1211 // even though v8i16 is a legal type.
1212 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1213 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1214 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1216 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1217 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1218 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1220 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1221 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1223 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1225 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1226 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1228 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1229 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1231 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1232 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1234 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1235 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1236 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1237 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1239 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1240 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1241 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1243 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1244 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1245 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1246 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1248 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1249 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1250 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1251 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1252 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1253 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1254 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1255 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1256 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1257 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1258 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1259 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1261 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1262 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1263 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1264 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1265 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1266 setOperationAction(ISD::FMA, MVT::f32, Legal);
1267 setOperationAction(ISD::FMA, MVT::f64, Legal);
1270 if (Subtarget->hasInt256()) {
1271 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1272 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1273 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1274 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1276 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1277 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1278 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1279 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1281 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1282 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1283 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1284 // Don't lower v32i8 because there is no 128-bit byte mul
1286 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1287 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1288 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1289 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1291 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1292 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1294 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1295 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1296 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1297 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1299 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1300 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1301 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1302 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1304 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1305 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1306 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1307 // Don't lower v32i8 because there is no 128-bit byte mul
1310 // In the customized shift lowering, the legal cases in AVX2 will be
1312 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1313 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1315 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1316 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1318 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1320 // Custom lower several nodes for 256-bit types.
1321 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1322 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1323 MVT VT = (MVT::SimpleValueType)i;
1325 // Extract subvector is special because the value type
1326 // (result) is 128-bit but the source is 256-bit wide.
1327 if (VT.is128BitVector())
1328 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1330 // Do not attempt to custom lower other non-256-bit vectors
1331 if (!VT.is256BitVector())
1334 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1335 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1336 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1337 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1338 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1339 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1340 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1343 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1344 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1345 MVT VT = (MVT::SimpleValueType)i;
1347 // Do not attempt to promote non-256-bit vectors
1348 if (!VT.is256BitVector())
1351 setOperationAction(ISD::AND, VT, Promote);
1352 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1353 setOperationAction(ISD::OR, VT, Promote);
1354 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1355 setOperationAction(ISD::XOR, VT, Promote);
1356 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1357 setOperationAction(ISD::LOAD, VT, Promote);
1358 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1359 setOperationAction(ISD::SELECT, VT, Promote);
1360 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1364 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1365 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1366 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1367 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1368 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1370 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1371 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1372 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1374 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1375 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1376 setOperationAction(ISD::XOR, MVT::i1, Legal);
1377 setOperationAction(ISD::OR, MVT::i1, Legal);
1378 setOperationAction(ISD::AND, MVT::i1, Legal);
1379 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1380 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1381 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1382 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1383 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1384 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1386 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1387 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1388 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1389 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1390 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1391 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1393 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1394 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1395 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1396 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1397 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1398 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1399 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1400 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1402 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1403 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1404 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1405 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1406 if (Subtarget->is64Bit()) {
1407 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1408 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1409 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1410 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1412 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1413 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1414 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1415 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1416 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1417 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1418 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1419 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1420 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1421 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1423 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1424 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1425 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1426 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1427 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1428 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1429 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1430 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1431 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1432 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1433 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1434 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1435 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1437 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1438 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1439 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1440 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1441 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1442 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1444 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1445 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1447 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1449 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1450 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1451 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1452 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1453 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1454 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1455 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1456 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1457 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1459 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1460 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1462 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1463 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1465 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1467 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1468 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1470 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1471 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1473 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1474 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1476 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1477 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1478 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1479 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1480 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1481 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1483 if (Subtarget->hasCDI()) {
1484 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1485 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1488 // Custom lower several nodes.
1489 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1490 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1491 MVT VT = (MVT::SimpleValueType)i;
1493 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1494 // Extract subvector is special because the value type
1495 // (result) is 256/128-bit but the source is 512-bit wide.
1496 if (VT.is128BitVector() || VT.is256BitVector())
1497 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1499 if (VT.getVectorElementType() == MVT::i1)
1500 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1502 // Do not attempt to custom lower other non-512-bit vectors
1503 if (!VT.is512BitVector())
1506 if ( EltSize >= 32) {
1507 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1508 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1509 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1510 setOperationAction(ISD::VSELECT, VT, Legal);
1511 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1512 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1513 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1516 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1517 MVT VT = (MVT::SimpleValueType)i;
1519 // Do not attempt to promote non-256-bit vectors
1520 if (!VT.is512BitVector())
1523 setOperationAction(ISD::SELECT, VT, Promote);
1524 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1528 if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1529 addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1530 addRegisterClass(MVT::v64i8, &X86::VR512RegClass);
1532 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1533 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1535 setOperationAction(ISD::LOAD, MVT::v32i16, Legal);
1536 setOperationAction(ISD::LOAD, MVT::v64i8, Legal);
1537 setOperationAction(ISD::SETCC, MVT::v32i1, Custom);
1538 setOperationAction(ISD::SETCC, MVT::v64i1, Custom);
1540 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1541 const MVT VT = (MVT::SimpleValueType)i;
1543 const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1545 // Do not attempt to promote non-256-bit vectors
1546 if (!VT.is512BitVector())
1549 if ( EltSize < 32) {
1550 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1551 setOperationAction(ISD::VSELECT, VT, Legal);
1556 if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1557 addRegisterClass(MVT::v4i1, &X86::VK4RegClass);
1558 addRegisterClass(MVT::v2i1, &X86::VK2RegClass);
1560 setOperationAction(ISD::SETCC, MVT::v4i1, Custom);
1561 setOperationAction(ISD::SETCC, MVT::v2i1, Custom);
1564 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1565 // of this type with custom code.
1566 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1567 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1568 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1572 // We want to custom lower some of our intrinsics.
1573 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1574 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1575 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1576 if (!Subtarget->is64Bit())
1577 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1579 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1580 // handle type legalization for these operations here.
1582 // FIXME: We really should do custom legalization for addition and
1583 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1584 // than generic legalization for 64-bit multiplication-with-overflow, though.
1585 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1586 // Add/Sub/Mul with overflow operations are custom lowered.
1588 setOperationAction(ISD::SADDO, VT, Custom);
1589 setOperationAction(ISD::UADDO, VT, Custom);
1590 setOperationAction(ISD::SSUBO, VT, Custom);
1591 setOperationAction(ISD::USUBO, VT, Custom);
1592 setOperationAction(ISD::SMULO, VT, Custom);
1593 setOperationAction(ISD::UMULO, VT, Custom);
1596 // There are no 8-bit 3-address imul/mul instructions
1597 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1598 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1600 if (!Subtarget->is64Bit()) {
1601 // These libcalls are not available in 32-bit.
1602 setLibcallName(RTLIB::SHL_I128, nullptr);
1603 setLibcallName(RTLIB::SRL_I128, nullptr);
1604 setLibcallName(RTLIB::SRA_I128, nullptr);
1607 // Combine sin / cos into one node or libcall if possible.
1608 if (Subtarget->hasSinCos()) {
1609 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1610 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1611 if (Subtarget->isTargetDarwin()) {
1612 // For MacOSX, we don't want to the normal expansion of a libcall to
1613 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1615 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1616 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1620 if (Subtarget->isTargetWin64()) {
1621 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1622 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1623 setOperationAction(ISD::SREM, MVT::i128, Custom);
1624 setOperationAction(ISD::UREM, MVT::i128, Custom);
1625 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1626 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1629 // We have target-specific dag combine patterns for the following nodes:
1630 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1631 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1632 setTargetDAGCombine(ISD::VSELECT);
1633 setTargetDAGCombine(ISD::SELECT);
1634 setTargetDAGCombine(ISD::SHL);
1635 setTargetDAGCombine(ISD::SRA);
1636 setTargetDAGCombine(ISD::SRL);
1637 setTargetDAGCombine(ISD::OR);
1638 setTargetDAGCombine(ISD::AND);
1639 setTargetDAGCombine(ISD::ADD);
1640 setTargetDAGCombine(ISD::FADD);
1641 setTargetDAGCombine(ISD::FSUB);
1642 setTargetDAGCombine(ISD::FMA);
1643 setTargetDAGCombine(ISD::SUB);
1644 setTargetDAGCombine(ISD::LOAD);
1645 setTargetDAGCombine(ISD::STORE);
1646 setTargetDAGCombine(ISD::ZERO_EXTEND);
1647 setTargetDAGCombine(ISD::ANY_EXTEND);
1648 setTargetDAGCombine(ISD::SIGN_EXTEND);
1649 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1650 setTargetDAGCombine(ISD::TRUNCATE);
1651 setTargetDAGCombine(ISD::SINT_TO_FP);
1652 setTargetDAGCombine(ISD::SETCC);
1653 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1654 setTargetDAGCombine(ISD::BUILD_VECTOR);
1655 if (Subtarget->is64Bit())
1656 setTargetDAGCombine(ISD::MUL);
1657 setTargetDAGCombine(ISD::XOR);
1659 computeRegisterProperties();
1661 // On Darwin, -Os means optimize for size without hurting performance,
1662 // do not reduce the limit.
1663 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1664 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1665 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1666 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1667 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1668 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1669 setPrefLoopAlignment(4); // 2^4 bytes.
1671 // Predictable cmov don't hurt on atom because it's in-order.
1672 PredictableSelectIsExpensive = !Subtarget->isAtom();
1674 setPrefFunctionAlignment(4); // 2^4 bytes.
1676 verifyIntrinsicTables();
1679 // This has so far only been implemented for 64-bit MachO.
1680 bool X86TargetLowering::useLoadStackGuardNode() const {
1681 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1682 Subtarget->is64Bit();
1685 TargetLoweringBase::LegalizeTypeAction
1686 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1687 if (ExperimentalVectorWideningLegalization &&
1688 VT.getVectorNumElements() != 1 &&
1689 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1690 return TypeWidenVector;
1692 return TargetLoweringBase::getPreferredVectorAction(VT);
1695 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1697 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1699 const unsigned NumElts = VT.getVectorNumElements();
1700 const EVT EltVT = VT.getVectorElementType();
1701 if (VT.is512BitVector()) {
1702 if (Subtarget->hasAVX512())
1703 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1704 EltVT == MVT::f32 || EltVT == MVT::f64)
1706 case 8: return MVT::v8i1;
1707 case 16: return MVT::v16i1;
1709 if (Subtarget->hasBWI())
1710 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1712 case 32: return MVT::v32i1;
1713 case 64: return MVT::v64i1;
1717 if (VT.is256BitVector() || VT.is128BitVector()) {
1718 if (Subtarget->hasVLX())
1719 if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1720 EltVT == MVT::f32 || EltVT == MVT::f64)
1722 case 2: return MVT::v2i1;
1723 case 4: return MVT::v4i1;
1724 case 8: return MVT::v8i1;
1726 if (Subtarget->hasBWI() && Subtarget->hasVLX())
1727 if (EltVT == MVT::i8 || EltVT == MVT::i16)
1729 case 8: return MVT::v8i1;
1730 case 16: return MVT::v16i1;
1731 case 32: return MVT::v32i1;
1735 return VT.changeVectorElementTypeToInteger();
1738 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1739 /// the desired ByVal argument alignment.
1740 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1743 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1744 if (VTy->getBitWidth() == 128)
1746 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1747 unsigned EltAlign = 0;
1748 getMaxByValAlign(ATy->getElementType(), EltAlign);
1749 if (EltAlign > MaxAlign)
1750 MaxAlign = EltAlign;
1751 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1752 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1753 unsigned EltAlign = 0;
1754 getMaxByValAlign(STy->getElementType(i), EltAlign);
1755 if (EltAlign > MaxAlign)
1756 MaxAlign = EltAlign;
1763 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1764 /// function arguments in the caller parameter area. For X86, aggregates
1765 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1766 /// are at 4-byte boundaries.
1767 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1768 if (Subtarget->is64Bit()) {
1769 // Max of 8 and alignment of type.
1770 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1777 if (Subtarget->hasSSE1())
1778 getMaxByValAlign(Ty, Align);
1782 /// getOptimalMemOpType - Returns the target specific optimal type for load
1783 /// and store operations as a result of memset, memcpy, and memmove
1784 /// lowering. If DstAlign is zero that means it's safe to destination
1785 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1786 /// means there isn't a need to check it against alignment requirement,
1787 /// probably because the source does not need to be loaded. If 'IsMemset' is
1788 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1789 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1790 /// source is constant so it does not need to be loaded.
1791 /// It returns EVT::Other if the type should be determined using generic
1792 /// target-independent logic.
1794 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1795 unsigned DstAlign, unsigned SrcAlign,
1796 bool IsMemset, bool ZeroMemset,
1798 MachineFunction &MF) const {
1799 const Function *F = MF.getFunction();
1800 if ((!IsMemset || ZeroMemset) &&
1801 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1802 Attribute::NoImplicitFloat)) {
1804 (Subtarget->isUnalignedMemAccessFast() ||
1805 ((DstAlign == 0 || DstAlign >= 16) &&
1806 (SrcAlign == 0 || SrcAlign >= 16)))) {
1808 if (Subtarget->hasInt256())
1810 if (Subtarget->hasFp256())
1813 if (Subtarget->hasSSE2())
1815 if (Subtarget->hasSSE1())
1817 } else if (!MemcpyStrSrc && Size >= 8 &&
1818 !Subtarget->is64Bit() &&
1819 Subtarget->hasSSE2()) {
1820 // Do not use f64 to lower memcpy if source is string constant. It's
1821 // better to use i32 to avoid the loads.
1825 if (Subtarget->is64Bit() && Size >= 8)
1830 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1832 return X86ScalarSSEf32;
1833 else if (VT == MVT::f64)
1834 return X86ScalarSSEf64;
1839 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1844 *Fast = Subtarget->isUnalignedMemAccessFast();
1848 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1849 /// current function. The returned value is a member of the
1850 /// MachineJumpTableInfo::JTEntryKind enum.
1851 unsigned X86TargetLowering::getJumpTableEncoding() const {
1852 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1854 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1855 Subtarget->isPICStyleGOT())
1856 return MachineJumpTableInfo::EK_Custom32;
1858 // Otherwise, use the normal jump table encoding heuristics.
1859 return TargetLowering::getJumpTableEncoding();
1863 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1864 const MachineBasicBlock *MBB,
1865 unsigned uid,MCContext &Ctx) const{
1866 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1867 Subtarget->isPICStyleGOT());
1868 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1870 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1871 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1874 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1876 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1877 SelectionDAG &DAG) const {
1878 if (!Subtarget->is64Bit())
1879 // This doesn't have SDLoc associated with it, but is not really the
1880 // same as a Register.
1881 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1885 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1886 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1888 const MCExpr *X86TargetLowering::
1889 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1890 MCContext &Ctx) const {
1891 // X86-64 uses RIP relative addressing based on the jump table label.
1892 if (Subtarget->isPICStyleRIPRel())
1893 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1895 // Otherwise, the reference is relative to the PIC base.
1896 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1899 // FIXME: Why this routine is here? Move to RegInfo!
1900 std::pair<const TargetRegisterClass*, uint8_t>
1901 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1902 const TargetRegisterClass *RRC = nullptr;
1904 switch (VT.SimpleTy) {
1906 return TargetLowering::findRepresentativeClass(VT);
1907 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1908 RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1911 RRC = &X86::VR64RegClass;
1913 case MVT::f32: case MVT::f64:
1914 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1915 case MVT::v4f32: case MVT::v2f64:
1916 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1918 RRC = &X86::VR128RegClass;
1921 return std::make_pair(RRC, Cost);
1924 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1925 unsigned &Offset) const {
1926 if (!Subtarget->isTargetLinux())
1929 if (Subtarget->is64Bit()) {
1930 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1932 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1944 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1945 unsigned DestAS) const {
1946 assert(SrcAS != DestAS && "Expected different address spaces!");
1948 return SrcAS < 256 && DestAS < 256;
1951 //===----------------------------------------------------------------------===//
1952 // Return Value Calling Convention Implementation
1953 //===----------------------------------------------------------------------===//
1955 #include "X86GenCallingConv.inc"
1958 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1959 MachineFunction &MF, bool isVarArg,
1960 const SmallVectorImpl<ISD::OutputArg> &Outs,
1961 LLVMContext &Context) const {
1962 SmallVector<CCValAssign, 16> RVLocs;
1963 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1964 return CCInfo.CheckReturn(Outs, RetCC_X86);
1967 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1968 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1973 X86TargetLowering::LowerReturn(SDValue Chain,
1974 CallingConv::ID CallConv, bool isVarArg,
1975 const SmallVectorImpl<ISD::OutputArg> &Outs,
1976 const SmallVectorImpl<SDValue> &OutVals,
1977 SDLoc dl, SelectionDAG &DAG) const {
1978 MachineFunction &MF = DAG.getMachineFunction();
1979 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1981 SmallVector<CCValAssign, 16> RVLocs;
1982 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1983 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1986 SmallVector<SDValue, 6> RetOps;
1987 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1988 // Operand #1 = Bytes To Pop
1989 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1992 // Copy the result values into the output registers.
1993 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1994 CCValAssign &VA = RVLocs[i];
1995 assert(VA.isRegLoc() && "Can only return in registers!");
1996 SDValue ValToCopy = OutVals[i];
1997 EVT ValVT = ValToCopy.getValueType();
1999 // Promote values to the appropriate types
2000 if (VA.getLocInfo() == CCValAssign::SExt)
2001 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2002 else if (VA.getLocInfo() == CCValAssign::ZExt)
2003 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2004 else if (VA.getLocInfo() == CCValAssign::AExt)
2005 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2006 else if (VA.getLocInfo() == CCValAssign::BCvt)
2007 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2009 assert(VA.getLocInfo() != CCValAssign::FPExt &&
2010 "Unexpected FP-extend for return value.");
2012 // If this is x86-64, and we disabled SSE, we can't return FP values,
2013 // or SSE or MMX vectors.
2014 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2015 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2016 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2017 report_fatal_error("SSE register return with SSE disabled");
2019 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
2020 // llvm-gcc has never done it right and no one has noticed, so this
2021 // should be OK for now.
2022 if (ValVT == MVT::f64 &&
2023 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2024 report_fatal_error("SSE2 register return with SSE2 disabled");
2026 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2027 // the RET instruction and handled by the FP Stackifier.
2028 if (VA.getLocReg() == X86::FP0 ||
2029 VA.getLocReg() == X86::FP1) {
2030 // If this is a copy from an xmm register to ST(0), use an FPExtend to
2031 // change the value to the FP stack register class.
2032 if (isScalarFPTypeInSSEReg(VA.getValVT()))
2033 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2034 RetOps.push_back(ValToCopy);
2035 // Don't emit a copytoreg.
2039 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2040 // which is returned in RAX / RDX.
2041 if (Subtarget->is64Bit()) {
2042 if (ValVT == MVT::x86mmx) {
2043 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2044 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2045 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2047 // If we don't have SSE2 available, convert to v4f32 so the generated
2048 // register is legal.
2049 if (!Subtarget->hasSSE2())
2050 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2055 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2056 Flag = Chain.getValue(1);
2057 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2060 // The x86-64 ABIs require that for returning structs by value we copy
2061 // the sret argument into %rax/%eax (depending on ABI) for the return.
2062 // Win32 requires us to put the sret argument to %eax as well.
2063 // We saved the argument into a virtual register in the entry block,
2064 // so now we copy the value out and into %rax/%eax.
2065 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2066 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2067 MachineFunction &MF = DAG.getMachineFunction();
2068 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2069 unsigned Reg = FuncInfo->getSRetReturnReg();
2071 "SRetReturnReg should have been set in LowerFormalArguments().");
2072 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2075 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2076 X86::RAX : X86::EAX;
2077 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2078 Flag = Chain.getValue(1);
2080 // RAX/EAX now acts like a return value.
2081 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2084 RetOps[0] = Chain; // Update chain.
2086 // Add the flag if we have it.
2088 RetOps.push_back(Flag);
2090 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2093 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2094 if (N->getNumValues() != 1)
2096 if (!N->hasNUsesOfValue(1, 0))
2099 SDValue TCChain = Chain;
2100 SDNode *Copy = *N->use_begin();
2101 if (Copy->getOpcode() == ISD::CopyToReg) {
2102 // If the copy has a glue operand, we conservatively assume it isn't safe to
2103 // perform a tail call.
2104 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2106 TCChain = Copy->getOperand(0);
2107 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2110 bool HasRet = false;
2111 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2113 if (UI->getOpcode() != X86ISD::RET_FLAG)
2115 // If we are returning more than one value, we can definitely
2116 // not make a tail call see PR19530
2117 if (UI->getNumOperands() > 4)
2119 if (UI->getNumOperands() == 4 &&
2120 UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2133 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2134 ISD::NodeType ExtendKind) const {
2136 // TODO: Is this also valid on 32-bit?
2137 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2138 ReturnMVT = MVT::i8;
2140 ReturnMVT = MVT::i32;
2142 EVT MinVT = getRegisterType(Context, ReturnMVT);
2143 return VT.bitsLT(MinVT) ? MinVT : VT;
2146 /// LowerCallResult - Lower the result values of a call into the
2147 /// appropriate copies out of appropriate physical registers.
2150 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2151 CallingConv::ID CallConv, bool isVarArg,
2152 const SmallVectorImpl<ISD::InputArg> &Ins,
2153 SDLoc dl, SelectionDAG &DAG,
2154 SmallVectorImpl<SDValue> &InVals) const {
2156 // Assign locations to each value returned by this call.
2157 SmallVector<CCValAssign, 16> RVLocs;
2158 bool Is64Bit = Subtarget->is64Bit();
2159 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2161 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2163 // Copy all of the result registers out of their specified physreg.
2164 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2165 CCValAssign &VA = RVLocs[i];
2166 EVT CopyVT = VA.getValVT();
2168 // If this is x86-64, and we disabled SSE, we can't return FP values
2169 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2170 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2171 report_fatal_error("SSE register return with SSE disabled");
2174 // If we prefer to use the value in xmm registers, copy it out as f80 and
2175 // use a truncate to move it from fp stack reg to xmm reg.
2176 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2177 isScalarFPTypeInSSEReg(VA.getValVT()))
2180 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2181 CopyVT, InFlag).getValue(1);
2182 SDValue Val = Chain.getValue(0);
2184 if (CopyVT != VA.getValVT())
2185 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2186 // This truncation won't change the value.
2187 DAG.getIntPtrConstant(1));
2189 InFlag = Chain.getValue(2);
2190 InVals.push_back(Val);
2196 //===----------------------------------------------------------------------===//
2197 // C & StdCall & Fast Calling Convention implementation
2198 //===----------------------------------------------------------------------===//
2199 // StdCall calling convention seems to be standard for many Windows' API
2200 // routines and around. It differs from C calling convention just a little:
2201 // callee should clean up the stack, not caller. Symbols should be also
2202 // decorated in some fancy way :) It doesn't support any vector arguments.
2203 // For info on fast calling convention see Fast Calling Convention (tail call)
2204 // implementation LowerX86_32FastCCCallTo.
2206 /// CallIsStructReturn - Determines whether a call uses struct return
2208 enum StructReturnType {
2213 static StructReturnType
2214 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2216 return NotStructReturn;
2218 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2219 if (!Flags.isSRet())
2220 return NotStructReturn;
2221 if (Flags.isInReg())
2222 return RegStructReturn;
2223 return StackStructReturn;
2226 /// ArgsAreStructReturn - Determines whether a function uses struct
2227 /// return semantics.
2228 static StructReturnType
2229 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2231 return NotStructReturn;
2233 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2234 if (!Flags.isSRet())
2235 return NotStructReturn;
2236 if (Flags.isInReg())
2237 return RegStructReturn;
2238 return StackStructReturn;
2241 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2242 /// by "Src" to address "Dst" with size and alignment information specified by
2243 /// the specific parameter attribute. The copy will be passed as a byval
2244 /// function parameter.
2246 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2247 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2249 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2251 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2252 /*isVolatile*/false, /*AlwaysInline=*/true,
2253 MachinePointerInfo(), MachinePointerInfo());
2256 /// IsTailCallConvention - Return true if the calling convention is one that
2257 /// supports tail call optimization.
2258 static bool IsTailCallConvention(CallingConv::ID CC) {
2259 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2260 CC == CallingConv::HiPE);
2263 /// \brief Return true if the calling convention is a C calling convention.
2264 static bool IsCCallConvention(CallingConv::ID CC) {
2265 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2266 CC == CallingConv::X86_64_SysV);
2269 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2270 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2274 CallingConv::ID CalleeCC = CS.getCallingConv();
2275 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2281 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2282 /// a tailcall target by changing its ABI.
2283 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2284 bool GuaranteedTailCallOpt) {
2285 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2289 X86TargetLowering::LowerMemArgument(SDValue Chain,
2290 CallingConv::ID CallConv,
2291 const SmallVectorImpl<ISD::InputArg> &Ins,
2292 SDLoc dl, SelectionDAG &DAG,
2293 const CCValAssign &VA,
2294 MachineFrameInfo *MFI,
2296 // Create the nodes corresponding to a load from this parameter slot.
2297 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2298 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2299 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2300 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2303 // If value is passed by pointer we have address passed instead of the value
2305 if (VA.getLocInfo() == CCValAssign::Indirect)
2306 ValVT = VA.getLocVT();
2308 ValVT = VA.getValVT();
2310 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2311 // changed with more analysis.
2312 // In case of tail call optimization mark all arguments mutable. Since they
2313 // could be overwritten by lowering of arguments in case of a tail call.
2314 if (Flags.isByVal()) {
2315 unsigned Bytes = Flags.getByValSize();
2316 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2317 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2318 return DAG.getFrameIndex(FI, getPointerTy());
2320 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2321 VA.getLocMemOffset(), isImmutable);
2322 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2323 return DAG.getLoad(ValVT, dl, Chain, FIN,
2324 MachinePointerInfo::getFixedStack(FI),
2325 false, false, false, 0);
2329 // FIXME: Get this from tablegen.
2330 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2331 const X86Subtarget *Subtarget) {
2332 assert(Subtarget->is64Bit());
2334 if (Subtarget->isCallingConvWin64(CallConv)) {
2335 static const MCPhysReg GPR64ArgRegsWin64[] = {
2336 X86::RCX, X86::RDX, X86::R8, X86::R9
2338 return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2341 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2342 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2344 return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2347 // FIXME: Get this from tablegen.
2348 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2349 CallingConv::ID CallConv,
2350 const X86Subtarget *Subtarget) {
2351 assert(Subtarget->is64Bit());
2352 if (Subtarget->isCallingConvWin64(CallConv)) {
2353 // The XMM registers which might contain var arg parameters are shadowed
2354 // in their paired GPR. So we only need to save the GPR to their home
2356 // TODO: __vectorcall will change this.
2360 const Function *Fn = MF.getFunction();
2361 bool NoImplicitFloatOps = Fn->getAttributes().
2362 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2363 assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2364 "SSE register cannot be used when SSE is disabled!");
2365 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2366 !Subtarget->hasSSE1())
2367 // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2371 static const MCPhysReg XMMArgRegs64Bit[] = {
2372 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2373 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2375 return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2379 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2380 CallingConv::ID CallConv,
2382 const SmallVectorImpl<ISD::InputArg> &Ins,
2385 SmallVectorImpl<SDValue> &InVals)
2387 MachineFunction &MF = DAG.getMachineFunction();
2388 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2390 const Function* Fn = MF.getFunction();
2391 if (Fn->hasExternalLinkage() &&
2392 Subtarget->isTargetCygMing() &&
2393 Fn->getName() == "main")
2394 FuncInfo->setForceFramePointer(true);
2396 MachineFrameInfo *MFI = MF.getFrameInfo();
2397 bool Is64Bit = Subtarget->is64Bit();
2398 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2400 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2401 "Var args not supported with calling convention fastcc, ghc or hipe");
2403 // Assign locations to all of the incoming arguments.
2404 SmallVector<CCValAssign, 16> ArgLocs;
2405 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2407 // Allocate shadow area for Win64
2409 CCInfo.AllocateStack(32, 8);
2411 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2413 unsigned LastVal = ~0U;
2415 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2416 CCValAssign &VA = ArgLocs[i];
2417 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2419 assert(VA.getValNo() != LastVal &&
2420 "Don't support value assigned to multiple locs yet");
2422 LastVal = VA.getValNo();
2424 if (VA.isRegLoc()) {
2425 EVT RegVT = VA.getLocVT();
2426 const TargetRegisterClass *RC;
2427 if (RegVT == MVT::i32)
2428 RC = &X86::GR32RegClass;
2429 else if (Is64Bit && RegVT == MVT::i64)
2430 RC = &X86::GR64RegClass;
2431 else if (RegVT == MVT::f32)
2432 RC = &X86::FR32RegClass;
2433 else if (RegVT == MVT::f64)
2434 RC = &X86::FR64RegClass;
2435 else if (RegVT.is512BitVector())
2436 RC = &X86::VR512RegClass;
2437 else if (RegVT.is256BitVector())
2438 RC = &X86::VR256RegClass;
2439 else if (RegVT.is128BitVector())
2440 RC = &X86::VR128RegClass;
2441 else if (RegVT == MVT::x86mmx)
2442 RC = &X86::VR64RegClass;
2443 else if (RegVT == MVT::i1)
2444 RC = &X86::VK1RegClass;
2445 else if (RegVT == MVT::v8i1)
2446 RC = &X86::VK8RegClass;
2447 else if (RegVT == MVT::v16i1)
2448 RC = &X86::VK16RegClass;
2449 else if (RegVT == MVT::v32i1)
2450 RC = &X86::VK32RegClass;
2451 else if (RegVT == MVT::v64i1)
2452 RC = &X86::VK64RegClass;
2454 llvm_unreachable("Unknown argument type!");
2456 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2457 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2459 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2460 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2462 if (VA.getLocInfo() == CCValAssign::SExt)
2463 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2464 DAG.getValueType(VA.getValVT()));
2465 else if (VA.getLocInfo() == CCValAssign::ZExt)
2466 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2467 DAG.getValueType(VA.getValVT()));
2468 else if (VA.getLocInfo() == CCValAssign::BCvt)
2469 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2471 if (VA.isExtInLoc()) {
2472 // Handle MMX values passed in XMM regs.
2473 if (RegVT.isVector())
2474 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2476 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2479 assert(VA.isMemLoc());
2480 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2483 // If value is passed via pointer - do a load.
2484 if (VA.getLocInfo() == CCValAssign::Indirect)
2485 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2486 MachinePointerInfo(), false, false, false, 0);
2488 InVals.push_back(ArgValue);
2491 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2492 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2493 // The x86-64 ABIs require that for returning structs by value we copy
2494 // the sret argument into %rax/%eax (depending on ABI) for the return.
2495 // Win32 requires us to put the sret argument to %eax as well.
2496 // Save the argument into a virtual register so that we can access it
2497 // from the return points.
2498 if (Ins[i].Flags.isSRet()) {
2499 unsigned Reg = FuncInfo->getSRetReturnReg();
2501 MVT PtrTy = getPointerTy();
2502 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2503 FuncInfo->setSRetReturnReg(Reg);
2505 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2506 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2512 unsigned StackSize = CCInfo.getNextStackOffset();
2513 // Align stack specially for tail calls.
2514 if (FuncIsMadeTailCallSafe(CallConv,
2515 MF.getTarget().Options.GuaranteedTailCallOpt))
2516 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2518 // If the function takes variable number of arguments, make a frame index for
2519 // the start of the first vararg value... for expansion of llvm.va_start. We
2520 // can skip this if there are no va_start calls.
2521 if (MFI->hasVAStart() &&
2522 (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2523 CallConv != CallingConv::X86_ThisCall))) {
2524 FuncInfo->setVarArgsFrameIndex(
2525 MFI->CreateFixedObject(1, StackSize, true));
2528 // 64-bit calling conventions support varargs and register parameters, so we
2529 // have to do extra work to spill them in the prologue or forward them to
2531 if (Is64Bit && isVarArg &&
2532 (MFI->hasVAStart() || MFI->hasMustTailInVarArgFunc())) {
2533 // Find the first unallocated argument registers.
2534 ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2535 ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2536 unsigned NumIntRegs =
2537 CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2538 unsigned NumXMMRegs =
2539 CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2540 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2541 "SSE register cannot be used when SSE is disabled!");
2543 // Gather all the live in physical registers.
2544 SmallVector<SDValue, 6> LiveGPRs;
2545 SmallVector<SDValue, 8> LiveXMMRegs;
2547 for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2548 unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2550 DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2552 if (!ArgXMMs.empty()) {
2553 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2554 ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2555 for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2556 unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2557 LiveXMMRegs.push_back(
2558 DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2562 // Store them to the va_list returned by va_start.
2563 if (MFI->hasVAStart()) {
2565 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2566 // Get to the caller-allocated home save location. Add 8 to account
2567 // for the return address.
2568 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2569 FuncInfo->setRegSaveFrameIndex(
2570 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2571 // Fixup to set vararg frame on shadow area (4 x i64).
2573 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2575 // For X86-64, if there are vararg parameters that are passed via
2576 // registers, then we must store them to their spots on the stack so
2577 // they may be loaded by deferencing the result of va_next.
2578 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2579 FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2580 FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2581 ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2584 // Store the integer parameter registers.
2585 SmallVector<SDValue, 8> MemOps;
2586 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2588 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2589 for (SDValue Val : LiveGPRs) {
2590 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2591 DAG.getIntPtrConstant(Offset));
2593 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2594 MachinePointerInfo::getFixedStack(
2595 FuncInfo->getRegSaveFrameIndex(), Offset),
2597 MemOps.push_back(Store);
2601 if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2602 // Now store the XMM (fp + vector) parameter registers.
2603 SmallVector<SDValue, 12> SaveXMMOps;
2604 SaveXMMOps.push_back(Chain);
2605 SaveXMMOps.push_back(ALVal);
2606 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2607 FuncInfo->getRegSaveFrameIndex()));
2608 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2609 FuncInfo->getVarArgsFPOffset()));
2610 SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2612 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2613 MVT::Other, SaveXMMOps));
2616 if (!MemOps.empty())
2617 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2619 // Add all GPRs, al, and XMMs to the list of forwards. We will add then
2620 // to the liveout set on a musttail call.
2621 assert(MFI->hasMustTailInVarArgFunc());
2622 auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
2623 typedef X86MachineFunctionInfo::Forward Forward;
2625 for (unsigned I = 0, E = LiveGPRs.size(); I != E; ++I) {
2627 MF.getRegInfo().createVirtualRegister(&X86::GR64RegClass);
2628 Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveGPRs[I]);
2629 Forwards.push_back(Forward(VReg, ArgGPRs[NumIntRegs + I], MVT::i64));
2632 if (!ArgXMMs.empty()) {
2634 MF.getRegInfo().createVirtualRegister(&X86::GR8RegClass);
2635 Chain = DAG.getCopyToReg(Chain, dl, ALVReg, ALVal);
2636 Forwards.push_back(Forward(ALVReg, X86::AL, MVT::i8));
2638 for (unsigned I = 0, E = LiveXMMRegs.size(); I != E; ++I) {
2640 MF.getRegInfo().createVirtualRegister(&X86::VR128RegClass);
2641 Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveXMMRegs[I]);
2643 Forward(VReg, ArgXMMs[NumXMMRegs + I], MVT::v4f32));
2649 // Some CCs need callee pop.
2650 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2651 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2652 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2654 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2655 // If this is an sret function, the return should pop the hidden pointer.
2656 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2657 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2658 argsAreStructReturn(Ins) == StackStructReturn)
2659 FuncInfo->setBytesToPopOnReturn(4);
2663 // RegSaveFrameIndex is X86-64 only.
2664 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2665 if (CallConv == CallingConv::X86_FastCall ||
2666 CallConv == CallingConv::X86_ThisCall)
2667 // fastcc functions can't have varargs.
2668 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2671 FuncInfo->setArgumentStackSize(StackSize);
2677 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2678 SDValue StackPtr, SDValue Arg,
2679 SDLoc dl, SelectionDAG &DAG,
2680 const CCValAssign &VA,
2681 ISD::ArgFlagsTy Flags) const {
2682 unsigned LocMemOffset = VA.getLocMemOffset();
2683 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2684 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2685 if (Flags.isByVal())
2686 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2688 return DAG.getStore(Chain, dl, Arg, PtrOff,
2689 MachinePointerInfo::getStack(LocMemOffset),
2693 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2694 /// optimization is performed and it is required.
2696 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2697 SDValue &OutRetAddr, SDValue Chain,
2698 bool IsTailCall, bool Is64Bit,
2699 int FPDiff, SDLoc dl) const {
2700 // Adjust the Return address stack slot.
2701 EVT VT = getPointerTy();
2702 OutRetAddr = getReturnAddressFrameIndex(DAG);
2704 // Load the "old" Return address.
2705 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2706 false, false, false, 0);
2707 return SDValue(OutRetAddr.getNode(), 1);
2710 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2711 /// optimization is performed and it is required (FPDiff!=0).
2712 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2713 SDValue Chain, SDValue RetAddrFrIdx,
2714 EVT PtrVT, unsigned SlotSize,
2715 int FPDiff, SDLoc dl) {
2716 // Store the return address to the appropriate stack slot.
2717 if (!FPDiff) return Chain;
2718 // Calculate the new stack slot for the return address.
2719 int NewReturnAddrFI =
2720 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2722 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2723 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2724 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2730 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2731 SmallVectorImpl<SDValue> &InVals) const {
2732 SelectionDAG &DAG = CLI.DAG;
2734 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2735 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2736 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2737 SDValue Chain = CLI.Chain;
2738 SDValue Callee = CLI.Callee;
2739 CallingConv::ID CallConv = CLI.CallConv;
2740 bool &isTailCall = CLI.IsTailCall;
2741 bool isVarArg = CLI.IsVarArg;
2743 MachineFunction &MF = DAG.getMachineFunction();
2744 bool Is64Bit = Subtarget->is64Bit();
2745 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2746 StructReturnType SR = callIsStructReturn(Outs);
2747 bool IsSibcall = false;
2748 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2750 if (MF.getTarget().Options.DisableTailCalls)
2753 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2755 // Force this to be a tail call. The verifier rules are enough to ensure
2756 // that we can lower this successfully without moving the return address
2759 } else if (isTailCall) {
2760 // Check if it's really possible to do a tail call.
2761 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2762 isVarArg, SR != NotStructReturn,
2763 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2764 Outs, OutVals, Ins, DAG);
2766 // Sibcalls are automatically detected tailcalls which do not require
2768 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2775 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2776 "Var args not supported with calling convention fastcc, ghc or hipe");
2778 // Analyze operands of the call, assigning locations to each operand.
2779 SmallVector<CCValAssign, 16> ArgLocs;
2780 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2782 // Allocate shadow area for Win64
2784 CCInfo.AllocateStack(32, 8);
2786 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2788 // Get a count of how many bytes are to be pushed on the stack.
2789 unsigned NumBytes = CCInfo.getNextStackOffset();
2791 // This is a sibcall. The memory operands are available in caller's
2792 // own caller's stack.
2794 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2795 IsTailCallConvention(CallConv))
2796 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2799 if (isTailCall && !IsSibcall && !IsMustTail) {
2800 // Lower arguments at fp - stackoffset + fpdiff.
2801 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2803 FPDiff = NumBytesCallerPushed - NumBytes;
2805 // Set the delta of movement of the returnaddr stackslot.
2806 // But only set if delta is greater than previous delta.
2807 if (FPDiff < X86Info->getTCReturnAddrDelta())
2808 X86Info->setTCReturnAddrDelta(FPDiff);
2811 unsigned NumBytesToPush = NumBytes;
2812 unsigned NumBytesToPop = NumBytes;
2814 // If we have an inalloca argument, all stack space has already been allocated
2815 // for us and be right at the top of the stack. We don't support multiple
2816 // arguments passed in memory when using inalloca.
2817 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2819 if (!ArgLocs.back().isMemLoc())
2820 report_fatal_error("cannot use inalloca attribute on a register "
2822 if (ArgLocs.back().getLocMemOffset() != 0)
2823 report_fatal_error("any parameter with the inalloca attribute must be "
2824 "the only memory argument");
2828 Chain = DAG.getCALLSEQ_START(
2829 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2831 SDValue RetAddrFrIdx;
2832 // Load return address for tail calls.
2833 if (isTailCall && FPDiff)
2834 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2835 Is64Bit, FPDiff, dl);
2837 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2838 SmallVector<SDValue, 8> MemOpChains;
2841 // Walk the register/memloc assignments, inserting copies/loads. In the case
2842 // of tail call optimization arguments are handle later.
2843 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2844 DAG.getSubtarget().getRegisterInfo());
2845 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2846 // Skip inalloca arguments, they have already been written.
2847 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2848 if (Flags.isInAlloca())
2851 CCValAssign &VA = ArgLocs[i];
2852 EVT RegVT = VA.getLocVT();
2853 SDValue Arg = OutVals[i];
2854 bool isByVal = Flags.isByVal();
2856 // Promote the value if needed.
2857 switch (VA.getLocInfo()) {
2858 default: llvm_unreachable("Unknown loc info!");
2859 case CCValAssign::Full: break;
2860 case CCValAssign::SExt:
2861 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2863 case CCValAssign::ZExt:
2864 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2866 case CCValAssign::AExt:
2867 if (RegVT.is128BitVector()) {
2868 // Special case: passing MMX values in XMM registers.
2869 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2870 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2871 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2873 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2875 case CCValAssign::BCvt:
2876 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2878 case CCValAssign::Indirect: {
2879 // Store the argument.
2880 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2881 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2882 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2883 MachinePointerInfo::getFixedStack(FI),
2890 if (VA.isRegLoc()) {
2891 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2892 if (isVarArg && IsWin64) {
2893 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2894 // shadow reg if callee is a varargs function.
2895 unsigned ShadowReg = 0;
2896 switch (VA.getLocReg()) {
2897 case X86::XMM0: ShadowReg = X86::RCX; break;
2898 case X86::XMM1: ShadowReg = X86::RDX; break;
2899 case X86::XMM2: ShadowReg = X86::R8; break;
2900 case X86::XMM3: ShadowReg = X86::R9; break;
2903 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2905 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2906 assert(VA.isMemLoc());
2907 if (!StackPtr.getNode())
2908 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2910 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2911 dl, DAG, VA, Flags));
2915 if (!MemOpChains.empty())
2916 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2918 if (Subtarget->isPICStyleGOT()) {
2919 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2922 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2923 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2925 // If we are tail calling and generating PIC/GOT style code load the
2926 // address of the callee into ECX. The value in ecx is used as target of
2927 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2928 // for tail calls on PIC/GOT architectures. Normally we would just put the
2929 // address of GOT into ebx and then call target@PLT. But for tail calls
2930 // ebx would be restored (since ebx is callee saved) before jumping to the
2933 // Note: The actual moving to ECX is done further down.
2934 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2935 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2936 !G->getGlobal()->hasProtectedVisibility())
2937 Callee = LowerGlobalAddress(Callee, DAG);
2938 else if (isa<ExternalSymbolSDNode>(Callee))
2939 Callee = LowerExternalSymbol(Callee, DAG);
2943 if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2944 // From AMD64 ABI document:
2945 // For calls that may call functions that use varargs or stdargs
2946 // (prototype-less calls or calls to functions containing ellipsis (...) in
2947 // the declaration) %al is used as hidden argument to specify the number
2948 // of SSE registers used. The contents of %al do not need to match exactly
2949 // the number of registers, but must be an ubound on the number of SSE
2950 // registers used and is in the range 0 - 8 inclusive.
2952 // Count the number of XMM registers allocated.
2953 static const MCPhysReg XMMArgRegs[] = {
2954 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2955 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2957 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2958 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2959 && "SSE registers cannot be used when SSE is disabled");
2961 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2962 DAG.getConstant(NumXMMRegs, MVT::i8)));
2965 if (Is64Bit && isVarArg && IsMustTail) {
2966 const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2967 for (const auto &F : Forwards) {
2968 SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2969 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2973 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2974 // don't need this because the eligibility check rejects calls that require
2975 // shuffling arguments passed in memory.
2976 if (!IsSibcall && isTailCall) {
2977 // Force all the incoming stack arguments to be loaded from the stack
2978 // before any new outgoing arguments are stored to the stack, because the
2979 // outgoing stack slots may alias the incoming argument stack slots, and
2980 // the alias isn't otherwise explicit. This is slightly more conservative
2981 // than necessary, because it means that each store effectively depends
2982 // on every argument instead of just those arguments it would clobber.
2983 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2985 SmallVector<SDValue, 8> MemOpChains2;
2988 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2989 CCValAssign &VA = ArgLocs[i];
2992 assert(VA.isMemLoc());
2993 SDValue Arg = OutVals[i];
2994 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2995 // Skip inalloca arguments. They don't require any work.
2996 if (Flags.isInAlloca())
2998 // Create frame index.
2999 int32_t Offset = VA.getLocMemOffset()+FPDiff;
3000 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3001 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3002 FIN = DAG.getFrameIndex(FI, getPointerTy());
3004 if (Flags.isByVal()) {
3005 // Copy relative to framepointer.
3006 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3007 if (!StackPtr.getNode())
3008 StackPtr = DAG.getCopyFromReg(Chain, dl,
3009 RegInfo->getStackRegister(),
3011 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3013 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3017 // Store relative to framepointer.
3018 MemOpChains2.push_back(
3019 DAG.getStore(ArgChain, dl, Arg, FIN,
3020 MachinePointerInfo::getFixedStack(FI),
3025 if (!MemOpChains2.empty())
3026 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3028 // Store the return address to the appropriate stack slot.
3029 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3030 getPointerTy(), RegInfo->getSlotSize(),
3034 // Build a sequence of copy-to-reg nodes chained together with token chain
3035 // and flag operands which copy the outgoing args into registers.
3037 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3038 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3039 RegsToPass[i].second, InFlag);
3040 InFlag = Chain.getValue(1);
3043 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3044 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3045 // In the 64-bit large code model, we have to make all calls
3046 // through a register, since the call instruction's 32-bit
3047 // pc-relative offset may not be large enough to hold the whole
3049 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3050 // If the callee is a GlobalAddress node (quite common, every direct call
3051 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3054 // We should use extra load for direct calls to dllimported functions in
3056 const GlobalValue *GV = G->getGlobal();
3057 if (!GV->hasDLLImportStorageClass()) {
3058 unsigned char OpFlags = 0;
3059 bool ExtraLoad = false;
3060 unsigned WrapperKind = ISD::DELETED_NODE;
3062 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3063 // external symbols most go through the PLT in PIC mode. If the symbol
3064 // has hidden or protected visibility, or if it is static or local, then
3065 // we don't need to use the PLT - we can directly call it.
3066 if (Subtarget->isTargetELF() &&
3067 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3068 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3069 OpFlags = X86II::MO_PLT;
3070 } else if (Subtarget->isPICStyleStubAny() &&
3071 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3072 (!Subtarget->getTargetTriple().isMacOSX() ||
3073 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3074 // PC-relative references to external symbols should go through $stub,
3075 // unless we're building with the leopard linker or later, which
3076 // automatically synthesizes these stubs.
3077 OpFlags = X86II::MO_DARWIN_STUB;
3078 } else if (Subtarget->isPICStyleRIPRel() &&
3079 isa<Function>(GV) &&
3080 cast<Function>(GV)->getAttributes().
3081 hasAttribute(AttributeSet::FunctionIndex,
3082 Attribute::NonLazyBind)) {
3083 // If the function is marked as non-lazy, generate an indirect call
3084 // which loads from the GOT directly. This avoids runtime overhead
3085 // at the cost of eager binding (and one extra byte of encoding).
3086 OpFlags = X86II::MO_GOTPCREL;
3087 WrapperKind = X86ISD::WrapperRIP;
3091 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3092 G->getOffset(), OpFlags);
3094 // Add a wrapper if needed.
3095 if (WrapperKind != ISD::DELETED_NODE)
3096 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3097 // Add extra indirection if needed.
3099 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3100 MachinePointerInfo::getGOT(),
3101 false, false, false, 0);
3103 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3104 unsigned char OpFlags = 0;
3106 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3107 // external symbols should go through the PLT.
3108 if (Subtarget->isTargetELF() &&
3109 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3110 OpFlags = X86II::MO_PLT;
3111 } else if (Subtarget->isPICStyleStubAny() &&
3112 (!Subtarget->getTargetTriple().isMacOSX() ||
3113 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3114 // PC-relative references to external symbols should go through $stub,
3115 // unless we're building with the leopard linker or later, which
3116 // automatically synthesizes these stubs.
3117 OpFlags = X86II::MO_DARWIN_STUB;
3120 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3124 // Returns a chain & a flag for retval copy to use.
3125 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3126 SmallVector<SDValue, 8> Ops;
3128 if (!IsSibcall && isTailCall) {
3129 Chain = DAG.getCALLSEQ_END(Chain,
3130 DAG.getIntPtrConstant(NumBytesToPop, true),
3131 DAG.getIntPtrConstant(0, true), InFlag, dl);
3132 InFlag = Chain.getValue(1);
3135 Ops.push_back(Chain);
3136 Ops.push_back(Callee);
3139 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3141 // Add argument registers to the end of the list so that they are known live
3143 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3144 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3145 RegsToPass[i].second.getValueType()));
3147 // Add a register mask operand representing the call-preserved registers.
3148 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3149 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3150 assert(Mask && "Missing call preserved mask for calling convention");
3151 Ops.push_back(DAG.getRegisterMask(Mask));
3153 if (InFlag.getNode())
3154 Ops.push_back(InFlag);
3158 //// If this is the first return lowered for this function, add the regs
3159 //// to the liveout set for the function.
3160 // This isn't right, although it's probably harmless on x86; liveouts
3161 // should be computed from returns not tail calls. Consider a void
3162 // function making a tail call to a function returning int.
3163 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3166 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3167 InFlag = Chain.getValue(1);
3169 // Create the CALLSEQ_END node.
3170 unsigned NumBytesForCalleeToPop;
3171 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3172 DAG.getTarget().Options.GuaranteedTailCallOpt))
3173 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3174 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3175 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3176 SR == StackStructReturn)
3177 // If this is a call to a struct-return function, the callee
3178 // pops the hidden struct pointer, so we have to push it back.
3179 // This is common for Darwin/X86, Linux & Mingw32 targets.
3180 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3181 NumBytesForCalleeToPop = 4;
3183 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3185 // Returns a flag for retval copy to use.
3187 Chain = DAG.getCALLSEQ_END(Chain,
3188 DAG.getIntPtrConstant(NumBytesToPop, true),
3189 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3192 InFlag = Chain.getValue(1);
3195 // Handle result values, copying them out of physregs into vregs that we
3197 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3198 Ins, dl, DAG, InVals);
3201 //===----------------------------------------------------------------------===//
3202 // Fast Calling Convention (tail call) implementation
3203 //===----------------------------------------------------------------------===//
3205 // Like std call, callee cleans arguments, convention except that ECX is
3206 // reserved for storing the tail called function address. Only 2 registers are
3207 // free for argument passing (inreg). Tail call optimization is performed
3209 // * tailcallopt is enabled
3210 // * caller/callee are fastcc
3211 // On X86_64 architecture with GOT-style position independent code only local
3212 // (within module) calls are supported at the moment.
3213 // To keep the stack aligned according to platform abi the function
3214 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3215 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3216 // If a tail called function callee has more arguments than the caller the
3217 // caller needs to make sure that there is room to move the RETADDR to. This is
3218 // achieved by reserving an area the size of the argument delta right after the
3219 // original RETADDR, but before the saved framepointer or the spilled registers
3220 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3232 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3233 /// for a 16 byte align requirement.
3235 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3236 SelectionDAG& DAG) const {
3237 MachineFunction &MF = DAG.getMachineFunction();
3238 const TargetMachine &TM = MF.getTarget();
3239 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3240 TM.getSubtargetImpl()->getRegisterInfo());
3241 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3242 unsigned StackAlignment = TFI.getStackAlignment();
3243 uint64_t AlignMask = StackAlignment - 1;
3244 int64_t Offset = StackSize;
3245 unsigned SlotSize = RegInfo->getSlotSize();
3246 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3247 // Number smaller than 12 so just add the difference.
3248 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3250 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3251 Offset = ((~AlignMask) & Offset) + StackAlignment +
3252 (StackAlignment-SlotSize);
3257 /// MatchingStackOffset - Return true if the given stack call argument is
3258 /// already available in the same position (relatively) of the caller's
3259 /// incoming argument stack.
3261 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3262 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3263 const X86InstrInfo *TII) {
3264 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3266 if (Arg.getOpcode() == ISD::CopyFromReg) {
3267 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3268 if (!TargetRegisterInfo::isVirtualRegister(VR))
3270 MachineInstr *Def = MRI->getVRegDef(VR);
3273 if (!Flags.isByVal()) {
3274 if (!TII->isLoadFromStackSlot(Def, FI))
3277 unsigned Opcode = Def->getOpcode();
3278 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3279 Def->getOperand(1).isFI()) {
3280 FI = Def->getOperand(1).getIndex();
3281 Bytes = Flags.getByValSize();
3285 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3286 if (Flags.isByVal())
3287 // ByVal argument is passed in as a pointer but it's now being
3288 // dereferenced. e.g.
3289 // define @foo(%struct.X* %A) {
3290 // tail call @bar(%struct.X* byval %A)
3293 SDValue Ptr = Ld->getBasePtr();
3294 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3297 FI = FINode->getIndex();
3298 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3299 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3300 FI = FINode->getIndex();
3301 Bytes = Flags.getByValSize();
3305 assert(FI != INT_MAX);
3306 if (!MFI->isFixedObjectIndex(FI))
3308 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3311 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3312 /// for tail call optimization. Targets which want to do tail call
3313 /// optimization should implement this function.
3315 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3316 CallingConv::ID CalleeCC,
3318 bool isCalleeStructRet,
3319 bool isCallerStructRet,
3321 const SmallVectorImpl<ISD::OutputArg> &Outs,
3322 const SmallVectorImpl<SDValue> &OutVals,
3323 const SmallVectorImpl<ISD::InputArg> &Ins,
3324 SelectionDAG &DAG) const {
3325 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3328 // If -tailcallopt is specified, make fastcc functions tail-callable.
3329 const MachineFunction &MF = DAG.getMachineFunction();
3330 const Function *CallerF = MF.getFunction();
3332 // If the function return type is x86_fp80 and the callee return type is not,
3333 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3334 // perform a tailcall optimization here.
3335 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3338 CallingConv::ID CallerCC = CallerF->getCallingConv();
3339 bool CCMatch = CallerCC == CalleeCC;
3340 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3341 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3343 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3344 if (IsTailCallConvention(CalleeCC) && CCMatch)
3349 // Look for obvious safe cases to perform tail call optimization that do not
3350 // require ABI changes. This is what gcc calls sibcall.
3352 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3353 // emit a special epilogue.
3354 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3355 DAG.getSubtarget().getRegisterInfo());
3356 if (RegInfo->needsStackRealignment(MF))
3359 // Also avoid sibcall optimization if either caller or callee uses struct
3360 // return semantics.
3361 if (isCalleeStructRet || isCallerStructRet)
3364 // An stdcall/thiscall caller is expected to clean up its arguments; the
3365 // callee isn't going to do that.
3366 // FIXME: this is more restrictive than needed. We could produce a tailcall
3367 // when the stack adjustment matches. For example, with a thiscall that takes
3368 // only one argument.
3369 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3370 CallerCC == CallingConv::X86_ThisCall))
3373 // Do not sibcall optimize vararg calls unless all arguments are passed via
3375 if (isVarArg && !Outs.empty()) {
3377 // Optimizing for varargs on Win64 is unlikely to be safe without
3378 // additional testing.
3379 if (IsCalleeWin64 || IsCallerWin64)
3382 SmallVector<CCValAssign, 16> ArgLocs;
3383 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3386 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3387 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3388 if (!ArgLocs[i].isRegLoc())
3392 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3393 // stack. Therefore, if it's not used by the call it is not safe to optimize
3394 // this into a sibcall.
3395 bool Unused = false;
3396 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3403 SmallVector<CCValAssign, 16> RVLocs;
3404 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3406 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3407 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3408 CCValAssign &VA = RVLocs[i];
3409 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3414 // If the calling conventions do not match, then we'd better make sure the
3415 // results are returned in the same way as what the caller expects.
3417 SmallVector<CCValAssign, 16> RVLocs1;
3418 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3420 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3422 SmallVector<CCValAssign, 16> RVLocs2;
3423 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3425 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3427 if (RVLocs1.size() != RVLocs2.size())
3429 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3430 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3432 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3434 if (RVLocs1[i].isRegLoc()) {
3435 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3438 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3444 // If the callee takes no arguments then go on to check the results of the
3446 if (!Outs.empty()) {
3447 // Check if stack adjustment is needed. For now, do not do this if any
3448 // argument is passed on the stack.
3449 SmallVector<CCValAssign, 16> ArgLocs;
3450 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3453 // Allocate shadow area for Win64
3455 CCInfo.AllocateStack(32, 8);
3457 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3458 if (CCInfo.getNextStackOffset()) {
3459 MachineFunction &MF = DAG.getMachineFunction();
3460 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3463 // Check if the arguments are already laid out in the right way as
3464 // the caller's fixed stack objects.
3465 MachineFrameInfo *MFI = MF.getFrameInfo();
3466 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3467 const X86InstrInfo *TII =
3468 static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3469 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3470 CCValAssign &VA = ArgLocs[i];
3471 SDValue Arg = OutVals[i];
3472 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3473 if (VA.getLocInfo() == CCValAssign::Indirect)
3475 if (!VA.isRegLoc()) {
3476 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3483 // If the tailcall address may be in a register, then make sure it's
3484 // possible to register allocate for it. In 32-bit, the call address can
3485 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3486 // callee-saved registers are restored. These happen to be the same
3487 // registers used to pass 'inreg' arguments so watch out for those.
3488 if (!Subtarget->is64Bit() &&
3489 ((!isa<GlobalAddressSDNode>(Callee) &&
3490 !isa<ExternalSymbolSDNode>(Callee)) ||
3491 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3492 unsigned NumInRegs = 0;
3493 // In PIC we need an extra register to formulate the address computation
3495 unsigned MaxInRegs =
3496 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3498 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3499 CCValAssign &VA = ArgLocs[i];
3502 unsigned Reg = VA.getLocReg();
3505 case X86::EAX: case X86::EDX: case X86::ECX:
3506 if (++NumInRegs == MaxInRegs)
3518 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3519 const TargetLibraryInfo *libInfo) const {
3520 return X86::createFastISel(funcInfo, libInfo);
3523 //===----------------------------------------------------------------------===//
3524 // Other Lowering Hooks
3525 //===----------------------------------------------------------------------===//
3527 static bool MayFoldLoad(SDValue Op) {
3528 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3531 static bool MayFoldIntoStore(SDValue Op) {
3532 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3535 static bool isTargetShuffle(unsigned Opcode) {
3537 default: return false;
3538 case X86ISD::PSHUFB:
3539 case X86ISD::PSHUFD:
3540 case X86ISD::PSHUFHW:
3541 case X86ISD::PSHUFLW:
3543 case X86ISD::PALIGNR:
3544 case X86ISD::MOVLHPS:
3545 case X86ISD::MOVLHPD:
3546 case X86ISD::MOVHLPS:
3547 case X86ISD::MOVLPS:
3548 case X86ISD::MOVLPD:
3549 case X86ISD::MOVSHDUP:
3550 case X86ISD::MOVSLDUP:
3551 case X86ISD::MOVDDUP:
3554 case X86ISD::UNPCKL:
3555 case X86ISD::UNPCKH:
3556 case X86ISD::VPERMILP:
3557 case X86ISD::VPERM2X128:
3558 case X86ISD::VPERMI:
3563 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3564 SDValue V1, SelectionDAG &DAG) {
3566 default: llvm_unreachable("Unknown x86 shuffle node");
3567 case X86ISD::MOVSHDUP:
3568 case X86ISD::MOVSLDUP:
3569 case X86ISD::MOVDDUP:
3570 return DAG.getNode(Opc, dl, VT, V1);
3574 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3575 SDValue V1, unsigned TargetMask,
3576 SelectionDAG &DAG) {
3578 default: llvm_unreachable("Unknown x86 shuffle node");
3579 case X86ISD::PSHUFD:
3580 case X86ISD::PSHUFHW:
3581 case X86ISD::PSHUFLW:
3582 case X86ISD::VPERMILP:
3583 case X86ISD::VPERMI:
3584 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3588 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3589 SDValue V1, SDValue V2, unsigned TargetMask,
3590 SelectionDAG &DAG) {
3592 default: llvm_unreachable("Unknown x86 shuffle node");
3593 case X86ISD::PALIGNR:
3594 case X86ISD::VALIGN:
3596 case X86ISD::VPERM2X128:
3597 return DAG.getNode(Opc, dl, VT, V1, V2,
3598 DAG.getConstant(TargetMask, MVT::i8));
3602 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3603 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3605 default: llvm_unreachable("Unknown x86 shuffle node");
3606 case X86ISD::MOVLHPS:
3607 case X86ISD::MOVLHPD:
3608 case X86ISD::MOVHLPS:
3609 case X86ISD::MOVLPS:
3610 case X86ISD::MOVLPD:
3613 case X86ISD::UNPCKL:
3614 case X86ISD::UNPCKH:
3615 return DAG.getNode(Opc, dl, VT, V1, V2);
3619 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3620 MachineFunction &MF = DAG.getMachineFunction();
3621 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3622 DAG.getSubtarget().getRegisterInfo());
3623 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3624 int ReturnAddrIndex = FuncInfo->getRAIndex();
3626 if (ReturnAddrIndex == 0) {
3627 // Set up a frame object for the return address.
3628 unsigned SlotSize = RegInfo->getSlotSize();
3629 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3632 FuncInfo->setRAIndex(ReturnAddrIndex);
3635 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3638 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3639 bool hasSymbolicDisplacement) {
3640 // Offset should fit into 32 bit immediate field.
3641 if (!isInt<32>(Offset))
3644 // If we don't have a symbolic displacement - we don't have any extra
3646 if (!hasSymbolicDisplacement)
3649 // FIXME: Some tweaks might be needed for medium code model.
3650 if (M != CodeModel::Small && M != CodeModel::Kernel)
3653 // For small code model we assume that latest object is 16MB before end of 31
3654 // bits boundary. We may also accept pretty large negative constants knowing
3655 // that all objects are in the positive half of address space.
3656 if (M == CodeModel::Small && Offset < 16*1024*1024)
3659 // For kernel code model we know that all object resist in the negative half
3660 // of 32bits address space. We may not accept negative offsets, since they may
3661 // be just off and we may accept pretty large positive ones.
3662 if (M == CodeModel::Kernel && Offset > 0)
3668 /// isCalleePop - Determines whether the callee is required to pop its
3669 /// own arguments. Callee pop is necessary to support tail calls.
3670 bool X86::isCalleePop(CallingConv::ID CallingConv,
3671 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3672 switch (CallingConv) {
3675 case CallingConv::X86_StdCall:
3676 case CallingConv::X86_FastCall:
3677 case CallingConv::X86_ThisCall:
3679 case CallingConv::Fast:
3680 case CallingConv::GHC:
3681 case CallingConv::HiPE:
3688 /// \brief Return true if the condition is an unsigned comparison operation.
3689 static bool isX86CCUnsigned(unsigned X86CC) {
3691 default: llvm_unreachable("Invalid integer condition!");
3692 case X86::COND_E: return true;
3693 case X86::COND_G: return false;
3694 case X86::COND_GE: return false;
3695 case X86::COND_L: return false;
3696 case X86::COND_LE: return false;
3697 case X86::COND_NE: return true;
3698 case X86::COND_B: return true;
3699 case X86::COND_A: return true;
3700 case X86::COND_BE: return true;
3701 case X86::COND_AE: return true;
3703 llvm_unreachable("covered switch fell through?!");
3706 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3707 /// specific condition code, returning the condition code and the LHS/RHS of the
3708 /// comparison to make.
3709 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3710 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3712 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3713 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3714 // X > -1 -> X == 0, jump !sign.
3715 RHS = DAG.getConstant(0, RHS.getValueType());
3716 return X86::COND_NS;
3718 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3719 // X < 0 -> X == 0, jump on sign.
3722 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3724 RHS = DAG.getConstant(0, RHS.getValueType());
3725 return X86::COND_LE;
3729 switch (SetCCOpcode) {
3730 default: llvm_unreachable("Invalid integer condition!");
3731 case ISD::SETEQ: return X86::COND_E;
3732 case ISD::SETGT: return X86::COND_G;
3733 case ISD::SETGE: return X86::COND_GE;
3734 case ISD::SETLT: return X86::COND_L;
3735 case ISD::SETLE: return X86::COND_LE;
3736 case ISD::SETNE: return X86::COND_NE;
3737 case ISD::SETULT: return X86::COND_B;
3738 case ISD::SETUGT: return X86::COND_A;
3739 case ISD::SETULE: return X86::COND_BE;
3740 case ISD::SETUGE: return X86::COND_AE;
3744 // First determine if it is required or is profitable to flip the operands.
3746 // If LHS is a foldable load, but RHS is not, flip the condition.
3747 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3748 !ISD::isNON_EXTLoad(RHS.getNode())) {
3749 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3750 std::swap(LHS, RHS);
3753 switch (SetCCOpcode) {
3759 std::swap(LHS, RHS);
3763 // On a floating point condition, the flags are set as follows:
3765 // 0 | 0 | 0 | X > Y
3766 // 0 | 0 | 1 | X < Y
3767 // 1 | 0 | 0 | X == Y
3768 // 1 | 1 | 1 | unordered
3769 switch (SetCCOpcode) {
3770 default: llvm_unreachable("Condcode should be pre-legalized away");
3772 case ISD::SETEQ: return X86::COND_E;
3773 case ISD::SETOLT: // flipped
3775 case ISD::SETGT: return X86::COND_A;
3776 case ISD::SETOLE: // flipped
3778 case ISD::SETGE: return X86::COND_AE;
3779 case ISD::SETUGT: // flipped
3781 case ISD::SETLT: return X86::COND_B;
3782 case ISD::SETUGE: // flipped
3784 case ISD::SETLE: return X86::COND_BE;
3786 case ISD::SETNE: return X86::COND_NE;
3787 case ISD::SETUO: return X86::COND_P;
3788 case ISD::SETO: return X86::COND_NP;
3790 case ISD::SETUNE: return X86::COND_INVALID;
3794 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3795 /// code. Current x86 isa includes the following FP cmov instructions:
3796 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3797 static bool hasFPCMov(unsigned X86CC) {
3813 /// isFPImmLegal - Returns true if the target can instruction select the
3814 /// specified FP immediate natively. If false, the legalizer will
3815 /// materialize the FP immediate as a load from a constant pool.
3816 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3817 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3818 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3824 /// \brief Returns true if it is beneficial to convert a load of a constant
3825 /// to just the constant itself.
3826 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3828 assert(Ty->isIntegerTy());
3830 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3831 if (BitSize == 0 || BitSize > 64)
3836 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3837 /// the specified range (L, H].
3838 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3839 return (Val < 0) || (Val >= Low && Val < Hi);
3842 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3843 /// specified value.
3844 static bool isUndefOrEqual(int Val, int CmpVal) {
3845 return (Val < 0 || Val == CmpVal);
3848 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3849 /// from position Pos and ending in Pos+Size, falls within the specified
3850 /// sequential range (L, L+Pos]. or is undef.
3851 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3852 unsigned Pos, unsigned Size, int Low) {
3853 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3854 if (!isUndefOrEqual(Mask[i], Low))
3859 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3860 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3861 /// the second operand.
3862 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3863 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3864 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3865 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3866 return (Mask[0] < 2 && Mask[1] < 2);
3870 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3871 /// is suitable for input to PSHUFHW.
3872 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3873 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3876 // Lower quadword copied in order or undef.
3877 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3880 // Upper quadword shuffled.
3881 for (unsigned i = 4; i != 8; ++i)
3882 if (!isUndefOrInRange(Mask[i], 4, 8))
3885 if (VT == MVT::v16i16) {
3886 // Lower quadword copied in order or undef.
3887 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3890 // Upper quadword shuffled.
3891 for (unsigned i = 12; i != 16; ++i)
3892 if (!isUndefOrInRange(Mask[i], 12, 16))
3899 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3900 /// is suitable for input to PSHUFLW.
3901 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3902 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3905 // Upper quadword copied in order.
3906 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3909 // Lower quadword shuffled.
3910 for (unsigned i = 0; i != 4; ++i)
3911 if (!isUndefOrInRange(Mask[i], 0, 4))
3914 if (VT == MVT::v16i16) {
3915 // Upper quadword copied in order.
3916 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3919 // Lower quadword shuffled.
3920 for (unsigned i = 8; i != 12; ++i)
3921 if (!isUndefOrInRange(Mask[i], 8, 12))
3928 /// \brief Return true if the mask specifies a shuffle of elements that is
3929 /// suitable for input to intralane (palignr) or interlane (valign) vector
3931 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3932 unsigned NumElts = VT.getVectorNumElements();
3933 unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3934 unsigned NumLaneElts = NumElts/NumLanes;
3936 // Do not handle 64-bit element shuffles with palignr.
3937 if (NumLaneElts == 2)
3940 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3942 for (i = 0; i != NumLaneElts; ++i) {
3947 // Lane is all undef, go to next lane
3948 if (i == NumLaneElts)
3951 int Start = Mask[i+l];
3953 // Make sure its in this lane in one of the sources
3954 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3955 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3958 // If not lane 0, then we must match lane 0
3959 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3962 // Correct second source to be contiguous with first source
3963 if (Start >= (int)NumElts)
3964 Start -= NumElts - NumLaneElts;
3966 // Make sure we're shifting in the right direction.
3967 if (Start <= (int)(i+l))
3972 // Check the rest of the elements to see if they are consecutive.
3973 for (++i; i != NumLaneElts; ++i) {
3974 int Idx = Mask[i+l];
3976 // Make sure its in this lane
3977 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3978 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3981 // If not lane 0, then we must match lane 0
3982 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3985 if (Idx >= (int)NumElts)
3986 Idx -= NumElts - NumLaneElts;
3988 if (!isUndefOrEqual(Idx, Start+i))
3997 /// \brief Return true if the node specifies a shuffle of elements that is
3998 /// suitable for input to PALIGNR.
3999 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
4000 const X86Subtarget *Subtarget) {
4001 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
4002 (VT.is256BitVector() && !Subtarget->hasInt256()) ||
4003 VT.is512BitVector())
4004 // FIXME: Add AVX512BW.
4007 return isAlignrMask(Mask, VT, false);
4010 /// \brief Return true if the node specifies a shuffle of elements that is
4011 /// suitable for input to VALIGN.
4012 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
4013 const X86Subtarget *Subtarget) {
4014 // FIXME: Add AVX512VL.
4015 if (!VT.is512BitVector() || !Subtarget->hasAVX512())
4017 return isAlignrMask(Mask, VT, true);
4020 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4021 /// the two vector operands have swapped position.
4022 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
4023 unsigned NumElems) {
4024 for (unsigned i = 0; i != NumElems; ++i) {
4028 else if (idx < (int)NumElems)
4029 Mask[i] = idx + NumElems;
4031 Mask[i] = idx - NumElems;
4035 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
4036 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
4037 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
4038 /// reverse of what x86 shuffles want.
4039 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
4041 unsigned NumElems = VT.getVectorNumElements();
4042 unsigned NumLanes = VT.getSizeInBits()/128;
4043 unsigned NumLaneElems = NumElems/NumLanes;
4045 if (NumLaneElems != 2 && NumLaneElems != 4)
4048 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4049 bool symetricMaskRequired =
4050 (VT.getSizeInBits() >= 256) && (EltSize == 32);
4052 // VSHUFPSY divides the resulting vector into 4 chunks.
4053 // The sources are also splitted into 4 chunks, and each destination
4054 // chunk must come from a different source chunk.
4056 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
4057 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
4059 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
4060 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
4062 // VSHUFPDY divides the resulting vector into 4 chunks.
4063 // The sources are also splitted into 4 chunks, and each destination
4064 // chunk must come from a different source chunk.
4066 // SRC1 => X3 X2 X1 X0
4067 // SRC2 => Y3 Y2 Y1 Y0
4069 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
4071 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4072 unsigned HalfLaneElems = NumLaneElems/2;
4073 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4074 for (unsigned i = 0; i != NumLaneElems; ++i) {
4075 int Idx = Mask[i+l];
4076 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4077 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4079 // For VSHUFPSY, the mask of the second half must be the same as the
4080 // first but with the appropriate offsets. This works in the same way as
4081 // VPERMILPS works with masks.
4082 if (!symetricMaskRequired || Idx < 0)
4084 if (MaskVal[i] < 0) {
4085 MaskVal[i] = Idx - l;
4088 if ((signed)(Idx - l) != MaskVal[i])
4096 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4097 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4098 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4099 if (!VT.is128BitVector())
4102 unsigned NumElems = VT.getVectorNumElements();
4107 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4108 return isUndefOrEqual(Mask[0], 6) &&
4109 isUndefOrEqual(Mask[1], 7) &&
4110 isUndefOrEqual(Mask[2], 2) &&
4111 isUndefOrEqual(Mask[3], 3);
4114 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4115 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4117 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4118 if (!VT.is128BitVector())
4121 unsigned NumElems = VT.getVectorNumElements();
4126 return isUndefOrEqual(Mask[0], 2) &&
4127 isUndefOrEqual(Mask[1], 3) &&
4128 isUndefOrEqual(Mask[2], 2) &&
4129 isUndefOrEqual(Mask[3], 3);
4132 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4133 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4134 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4135 if (!VT.is128BitVector())
4138 unsigned NumElems = VT.getVectorNumElements();
4140 if (NumElems != 2 && NumElems != 4)
4143 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4144 if (!isUndefOrEqual(Mask[i], i + NumElems))
4147 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4148 if (!isUndefOrEqual(Mask[i], i))
4154 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4155 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4156 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4157 if (!VT.is128BitVector())
4160 unsigned NumElems = VT.getVectorNumElements();
4162 if (NumElems != 2 && NumElems != 4)
4165 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4166 if (!isUndefOrEqual(Mask[i], i))
4169 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4170 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4176 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4177 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4178 /// i. e: If all but one element come from the same vector.
4179 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4180 // TODO: Deal with AVX's VINSERTPS
4181 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4184 unsigned CorrectPosV1 = 0;
4185 unsigned CorrectPosV2 = 0;
4186 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4187 if (Mask[i] == -1) {
4195 else if (Mask[i] == i + 4)
4199 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4200 // We have 3 elements (undefs count as elements from any vector) from one
4201 // vector, and one from another.
4208 // Some special combinations that can be optimized.
4211 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4212 SelectionDAG &DAG) {
4213 MVT VT = SVOp->getSimpleValueType(0);
4216 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4219 ArrayRef<int> Mask = SVOp->getMask();
4221 // These are the special masks that may be optimized.
4222 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4223 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4224 bool MatchEvenMask = true;
4225 bool MatchOddMask = true;
4226 for (int i=0; i<8; ++i) {
4227 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4228 MatchEvenMask = false;
4229 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4230 MatchOddMask = false;
4233 if (!MatchEvenMask && !MatchOddMask)
4236 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4238 SDValue Op0 = SVOp->getOperand(0);
4239 SDValue Op1 = SVOp->getOperand(1);
4241 if (MatchEvenMask) {
4242 // Shift the second operand right to 32 bits.
4243 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4244 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4246 // Shift the first operand left to 32 bits.
4247 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4248 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4250 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4251 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4254 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4255 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4256 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4257 bool HasInt256, bool V2IsSplat = false) {
4259 assert(VT.getSizeInBits() >= 128 &&
4260 "Unsupported vector type for unpckl");
4262 unsigned NumElts = VT.getVectorNumElements();
4263 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4264 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4267 assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4268 "Unsupported vector type for unpckh");
4270 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4271 unsigned NumLanes = VT.getSizeInBits()/128;
4272 unsigned NumLaneElts = NumElts/NumLanes;
4274 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4275 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4276 int BitI = Mask[l+i];
4277 int BitI1 = Mask[l+i+1];
4278 if (!isUndefOrEqual(BitI, j))
4281 if (!isUndefOrEqual(BitI1, NumElts))
4284 if (!isUndefOrEqual(BitI1, j + NumElts))
4293 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4294 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4295 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4296 bool HasInt256, bool V2IsSplat = false) {
4297 assert(VT.getSizeInBits() >= 128 &&
4298 "Unsupported vector type for unpckh");
4300 unsigned NumElts = VT.getVectorNumElements();
4301 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4302 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4305 assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4306 "Unsupported vector type for unpckh");
4308 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4309 unsigned NumLanes = VT.getSizeInBits()/128;
4310 unsigned NumLaneElts = NumElts/NumLanes;
4312 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4313 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4314 int BitI = Mask[l+i];
4315 int BitI1 = Mask[l+i+1];
4316 if (!isUndefOrEqual(BitI, j))
4319 if (isUndefOrEqual(BitI1, NumElts))
4322 if (!isUndefOrEqual(BitI1, j+NumElts))
4330 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4331 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4333 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4334 unsigned NumElts = VT.getVectorNumElements();
4335 bool Is256BitVec = VT.is256BitVector();
4337 if (VT.is512BitVector())
4339 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4340 "Unsupported vector type for unpckh");
4342 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4343 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4346 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4347 // FIXME: Need a better way to get rid of this, there's no latency difference
4348 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4349 // the former later. We should also remove the "_undef" special mask.
4350 if (NumElts == 4 && Is256BitVec)
4353 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4354 // independently on 128-bit lanes.
4355 unsigned NumLanes = VT.getSizeInBits()/128;
4356 unsigned NumLaneElts = NumElts/NumLanes;
4358 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4359 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4360 int BitI = Mask[l+i];
4361 int BitI1 = Mask[l+i+1];
4363 if (!isUndefOrEqual(BitI, j))
4365 if (!isUndefOrEqual(BitI1, j))
4373 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4374 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4376 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4377 unsigned NumElts = VT.getVectorNumElements();
4379 if (VT.is512BitVector())
4382 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4383 "Unsupported vector type for unpckh");
4385 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4386 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4389 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4390 // independently on 128-bit lanes.
4391 unsigned NumLanes = VT.getSizeInBits()/128;
4392 unsigned NumLaneElts = NumElts/NumLanes;
4394 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4395 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4396 int BitI = Mask[l+i];
4397 int BitI1 = Mask[l+i+1];
4398 if (!isUndefOrEqual(BitI, j))
4400 if (!isUndefOrEqual(BitI1, j))
4407 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4408 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4409 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4410 if (!VT.is512BitVector())
4413 unsigned NumElts = VT.getVectorNumElements();
4414 unsigned HalfSize = NumElts/2;
4415 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4416 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4421 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4422 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4430 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4431 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4432 /// MOVSD, and MOVD, i.e. setting the lowest element.
4433 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4434 if (VT.getVectorElementType().getSizeInBits() < 32)
4436 if (!VT.is128BitVector())
4439 unsigned NumElts = VT.getVectorNumElements();
4441 if (!isUndefOrEqual(Mask[0], NumElts))
4444 for (unsigned i = 1; i != NumElts; ++i)
4445 if (!isUndefOrEqual(Mask[i], i))
4451 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4452 /// as permutations between 128-bit chunks or halves. As an example: this
4454 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4455 /// The first half comes from the second half of V1 and the second half from the
4456 /// the second half of V2.
4457 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4458 if (!HasFp256 || !VT.is256BitVector())
4461 // The shuffle result is divided into half A and half B. In total the two
4462 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4463 // B must come from C, D, E or F.
4464 unsigned HalfSize = VT.getVectorNumElements()/2;
4465 bool MatchA = false, MatchB = false;
4467 // Check if A comes from one of C, D, E, F.
4468 for (unsigned Half = 0; Half != 4; ++Half) {
4469 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4475 // Check if B comes from one of C, D, E, F.
4476 for (unsigned Half = 0; Half != 4; ++Half) {
4477 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4483 return MatchA && MatchB;
4486 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4487 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4488 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4489 MVT VT = SVOp->getSimpleValueType(0);
4491 unsigned HalfSize = VT.getVectorNumElements()/2;
4493 unsigned FstHalf = 0, SndHalf = 0;
4494 for (unsigned i = 0; i < HalfSize; ++i) {
4495 if (SVOp->getMaskElt(i) > 0) {
4496 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4500 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4501 if (SVOp->getMaskElt(i) > 0) {
4502 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4507 return (FstHalf | (SndHalf << 4));
4510 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4511 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4512 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4516 unsigned NumElts = VT.getVectorNumElements();
4518 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4519 for (unsigned i = 0; i != NumElts; ++i) {
4522 Imm8 |= Mask[i] << (i*2);
4527 unsigned LaneSize = 4;
4528 SmallVector<int, 4> MaskVal(LaneSize, -1);
4530 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4531 for (unsigned i = 0; i != LaneSize; ++i) {
4532 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4536 if (MaskVal[i] < 0) {
4537 MaskVal[i] = Mask[i+l] - l;
4538 Imm8 |= MaskVal[i] << (i*2);
4541 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4548 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4549 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4550 /// Note that VPERMIL mask matching is different depending whether theunderlying
4551 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4552 /// to the same elements of the low, but to the higher half of the source.
4553 /// In VPERMILPD the two lanes could be shuffled independently of each other
4554 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4555 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4556 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4557 if (VT.getSizeInBits() < 256 || EltSize < 32)
4559 bool symetricMaskRequired = (EltSize == 32);
4560 unsigned NumElts = VT.getVectorNumElements();
4562 unsigned NumLanes = VT.getSizeInBits()/128;
4563 unsigned LaneSize = NumElts/NumLanes;
4564 // 2 or 4 elements in one lane
4566 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4567 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4568 for (unsigned i = 0; i != LaneSize; ++i) {
4569 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4571 if (symetricMaskRequired) {
4572 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4573 ExpectedMaskVal[i] = Mask[i+l] - l;
4576 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4584 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4585 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4586 /// element of vector 2 and the other elements to come from vector 1 in order.
4587 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4588 bool V2IsSplat = false, bool V2IsUndef = false) {
4589 if (!VT.is128BitVector())
4592 unsigned NumOps = VT.getVectorNumElements();
4593 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4596 if (!isUndefOrEqual(Mask[0], 0))
4599 for (unsigned i = 1; i != NumOps; ++i)
4600 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4601 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4602 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4608 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4609 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4610 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4611 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4612 const X86Subtarget *Subtarget) {
4613 if (!Subtarget->hasSSE3())
4616 unsigned NumElems = VT.getVectorNumElements();
4618 if ((VT.is128BitVector() && NumElems != 4) ||
4619 (VT.is256BitVector() && NumElems != 8) ||
4620 (VT.is512BitVector() && NumElems != 16))
4623 // "i+1" is the value the indexed mask element must have
4624 for (unsigned i = 0; i != NumElems; i += 2)
4625 if (!isUndefOrEqual(Mask[i], i+1) ||
4626 !isUndefOrEqual(Mask[i+1], i+1))
4632 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4633 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4634 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4635 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4636 const X86Subtarget *Subtarget) {
4637 if (!Subtarget->hasSSE3())
4640 unsigned NumElems = VT.getVectorNumElements();
4642 if ((VT.is128BitVector() && NumElems != 4) ||
4643 (VT.is256BitVector() && NumElems != 8) ||
4644 (VT.is512BitVector() && NumElems != 16))
4647 // "i" is the value the indexed mask element must have
4648 for (unsigned i = 0; i != NumElems; i += 2)
4649 if (!isUndefOrEqual(Mask[i], i) ||
4650 !isUndefOrEqual(Mask[i+1], i))
4656 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4657 /// specifies a shuffle of elements that is suitable for input to 256-bit
4658 /// version of MOVDDUP.
4659 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4660 if (!HasFp256 || !VT.is256BitVector())
4663 unsigned NumElts = VT.getVectorNumElements();
4667 for (unsigned i = 0; i != NumElts/2; ++i)
4668 if (!isUndefOrEqual(Mask[i], 0))
4670 for (unsigned i = NumElts/2; i != NumElts; ++i)
4671 if (!isUndefOrEqual(Mask[i], NumElts/2))
4676 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4677 /// specifies a shuffle of elements that is suitable for input to 128-bit
4678 /// version of MOVDDUP.
4679 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4680 if (!VT.is128BitVector())
4683 unsigned e = VT.getVectorNumElements() / 2;
4684 for (unsigned i = 0; i != e; ++i)
4685 if (!isUndefOrEqual(Mask[i], i))
4687 for (unsigned i = 0; i != e; ++i)
4688 if (!isUndefOrEqual(Mask[e+i], i))
4693 /// isVEXTRACTIndex - Return true if the specified
4694 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4695 /// suitable for instruction that extract 128 or 256 bit vectors
4696 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4697 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4698 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4701 // The index should be aligned on a vecWidth-bit boundary.
4703 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4705 MVT VT = N->getSimpleValueType(0);
4706 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4707 bool Result = (Index * ElSize) % vecWidth == 0;
4712 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4713 /// operand specifies a subvector insert that is suitable for input to
4714 /// insertion of 128 or 256-bit subvectors
4715 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4716 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4717 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4719 // The index should be aligned on a vecWidth-bit boundary.
4721 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4723 MVT VT = N->getSimpleValueType(0);
4724 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4725 bool Result = (Index * ElSize) % vecWidth == 0;
4730 bool X86::isVINSERT128Index(SDNode *N) {
4731 return isVINSERTIndex(N, 128);
4734 bool X86::isVINSERT256Index(SDNode *N) {
4735 return isVINSERTIndex(N, 256);
4738 bool X86::isVEXTRACT128Index(SDNode *N) {
4739 return isVEXTRACTIndex(N, 128);
4742 bool X86::isVEXTRACT256Index(SDNode *N) {
4743 return isVEXTRACTIndex(N, 256);
4746 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4747 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4748 /// Handles 128-bit and 256-bit.
4749 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4750 MVT VT = N->getSimpleValueType(0);
4752 assert((VT.getSizeInBits() >= 128) &&
4753 "Unsupported vector type for PSHUF/SHUFP");
4755 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4756 // independently on 128-bit lanes.
4757 unsigned NumElts = VT.getVectorNumElements();
4758 unsigned NumLanes = VT.getSizeInBits()/128;
4759 unsigned NumLaneElts = NumElts/NumLanes;
4761 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4762 "Only supports 2, 4 or 8 elements per lane");
4764 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4766 for (unsigned i = 0; i != NumElts; ++i) {
4767 int Elt = N->getMaskElt(i);
4768 if (Elt < 0) continue;
4769 Elt &= NumLaneElts - 1;
4770 unsigned ShAmt = (i << Shift) % 8;
4771 Mask |= Elt << ShAmt;
4777 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4778 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4779 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4780 MVT VT = N->getSimpleValueType(0);
4782 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4783 "Unsupported vector type for PSHUFHW");
4785 unsigned NumElts = VT.getVectorNumElements();
4788 for (unsigned l = 0; l != NumElts; l += 8) {
4789 // 8 nodes per lane, but we only care about the last 4.
4790 for (unsigned i = 0; i < 4; ++i) {
4791 int Elt = N->getMaskElt(l+i+4);
4792 if (Elt < 0) continue;
4793 Elt &= 0x3; // only 2-bits.
4794 Mask |= Elt << (i * 2);
4801 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4802 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4803 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4804 MVT VT = N->getSimpleValueType(0);
4806 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4807 "Unsupported vector type for PSHUFHW");
4809 unsigned NumElts = VT.getVectorNumElements();
4812 for (unsigned l = 0; l != NumElts; l += 8) {
4813 // 8 nodes per lane, but we only care about the first 4.
4814 for (unsigned i = 0; i < 4; ++i) {
4815 int Elt = N->getMaskElt(l+i);
4816 if (Elt < 0) continue;
4817 Elt &= 0x3; // only 2-bits
4818 Mask |= Elt << (i * 2);
4825 /// \brief Return the appropriate immediate to shuffle the specified
4826 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4827 /// VALIGN (if Interlane is true) instructions.
4828 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4830 MVT VT = SVOp->getSimpleValueType(0);
4831 unsigned EltSize = InterLane ? 1 :
4832 VT.getVectorElementType().getSizeInBits() >> 3;
4834 unsigned NumElts = VT.getVectorNumElements();
4835 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4836 unsigned NumLaneElts = NumElts/NumLanes;
4840 for (i = 0; i != NumElts; ++i) {
4841 Val = SVOp->getMaskElt(i);
4845 if (Val >= (int)NumElts)
4846 Val -= NumElts - NumLaneElts;
4848 assert(Val - i > 0 && "PALIGNR imm should be positive");
4849 return (Val - i) * EltSize;
4852 /// \brief Return the appropriate immediate to shuffle the specified
4853 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4854 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4855 return getShuffleAlignrImmediate(SVOp, false);
4858 /// \brief Return the appropriate immediate to shuffle the specified
4859 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4860 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4861 return getShuffleAlignrImmediate(SVOp, true);
4865 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4866 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4867 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4868 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4871 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4873 MVT VecVT = N->getOperand(0).getSimpleValueType();
4874 MVT ElVT = VecVT.getVectorElementType();
4876 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4877 return Index / NumElemsPerChunk;
4880 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4881 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4882 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4883 llvm_unreachable("Illegal insert subvector for VINSERT");
4886 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4888 MVT VecVT = N->getSimpleValueType(0);
4889 MVT ElVT = VecVT.getVectorElementType();
4891 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4892 return Index / NumElemsPerChunk;
4895 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4896 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4897 /// and VINSERTI128 instructions.
4898 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4899 return getExtractVEXTRACTImmediate(N, 128);
4902 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4903 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4904 /// and VINSERTI64x4 instructions.
4905 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4906 return getExtractVEXTRACTImmediate(N, 256);
4909 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4910 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4911 /// and VINSERTI128 instructions.
4912 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4913 return getInsertVINSERTImmediate(N, 128);
4916 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4917 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4918 /// and VINSERTI64x4 instructions.
4919 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4920 return getInsertVINSERTImmediate(N, 256);
4923 /// isZero - Returns true if Elt is a constant integer zero
4924 static bool isZero(SDValue V) {
4925 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4926 return C && C->isNullValue();
4929 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4931 bool X86::isZeroNode(SDValue Elt) {
4934 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4935 return CFP->getValueAPF().isPosZero();
4939 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4940 /// match movhlps. The lower half elements should come from upper half of
4941 /// V1 (and in order), and the upper half elements should come from the upper
4942 /// half of V2 (and in order).
4943 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4944 if (!VT.is128BitVector())
4946 if (VT.getVectorNumElements() != 4)
4948 for (unsigned i = 0, e = 2; i != e; ++i)
4949 if (!isUndefOrEqual(Mask[i], i+2))
4951 for (unsigned i = 2; i != 4; ++i)
4952 if (!isUndefOrEqual(Mask[i], i+4))
4957 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4958 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4960 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4961 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4963 N = N->getOperand(0).getNode();
4964 if (!ISD::isNON_EXTLoad(N))
4967 *LD = cast<LoadSDNode>(N);
4971 // Test whether the given value is a vector value which will be legalized
4973 static bool WillBeConstantPoolLoad(SDNode *N) {
4974 if (N->getOpcode() != ISD::BUILD_VECTOR)
4977 // Check for any non-constant elements.
4978 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4979 switch (N->getOperand(i).getNode()->getOpcode()) {
4981 case ISD::ConstantFP:
4988 // Vectors of all-zeros and all-ones are materialized with special
4989 // instructions rather than being loaded.
4990 return !ISD::isBuildVectorAllZeros(N) &&
4991 !ISD::isBuildVectorAllOnes(N);
4994 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4995 /// match movlp{s|d}. The lower half elements should come from lower half of
4996 /// V1 (and in order), and the upper half elements should come from the upper
4997 /// half of V2 (and in order). And since V1 will become the source of the
4998 /// MOVLP, it must be either a vector load or a scalar load to vector.
4999 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
5000 ArrayRef<int> Mask, MVT VT) {
5001 if (!VT.is128BitVector())
5004 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
5006 // Is V2 is a vector load, don't do this transformation. We will try to use
5007 // load folding shufps op.
5008 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
5011 unsigned NumElems = VT.getVectorNumElements();
5013 if (NumElems != 2 && NumElems != 4)
5015 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
5016 if (!isUndefOrEqual(Mask[i], i))
5018 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
5019 if (!isUndefOrEqual(Mask[i], i+NumElems))
5024 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
5025 /// to an zero vector.
5026 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
5027 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
5028 SDValue V1 = N->getOperand(0);
5029 SDValue V2 = N->getOperand(1);
5030 unsigned NumElems = N->getValueType(0).getVectorNumElements();
5031 for (unsigned i = 0; i != NumElems; ++i) {
5032 int Idx = N->getMaskElt(i);
5033 if (Idx >= (int)NumElems) {
5034 unsigned Opc = V2.getOpcode();
5035 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
5037 if (Opc != ISD::BUILD_VECTOR ||
5038 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5040 } else if (Idx >= 0) {
5041 unsigned Opc = V1.getOpcode();
5042 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5044 if (Opc != ISD::BUILD_VECTOR ||
5045 !X86::isZeroNode(V1.getOperand(Idx)))
5052 /// getZeroVector - Returns a vector of specified type with all zero elements.
5054 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5055 SelectionDAG &DAG, SDLoc dl) {
5056 assert(VT.isVector() && "Expected a vector type");
5058 // Always build SSE zero vectors as <4 x i32> bitcasted
5059 // to their dest type. This ensures they get CSE'd.
5061 if (VT.is128BitVector()) { // SSE
5062 if (Subtarget->hasSSE2()) { // SSE2
5063 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5064 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5066 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5067 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5069 } else if (VT.is256BitVector()) { // AVX
5070 if (Subtarget->hasInt256()) { // AVX2
5071 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5072 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5073 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5075 // 256-bit logic and arithmetic instructions in AVX are all
5076 // floating-point, no support for integer ops. Emit fp zeroed vectors.
5077 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5078 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5079 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5081 } else if (VT.is512BitVector()) { // AVX-512
5082 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5083 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5084 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5085 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5086 } else if (VT.getScalarType() == MVT::i1) {
5087 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5088 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5089 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5090 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5092 llvm_unreachable("Unexpected vector type");
5094 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5097 /// getOnesVector - Returns a vector of specified type with all bits set.
5098 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5099 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5100 /// Then bitcast to their original type, ensuring they get CSE'd.
5101 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5103 assert(VT.isVector() && "Expected a vector type");
5105 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5107 if (VT.is256BitVector()) {
5108 if (HasInt256) { // AVX2
5109 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5110 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5112 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5113 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5115 } else if (VT.is128BitVector()) {
5116 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5118 llvm_unreachable("Unexpected vector type");
5120 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5123 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5124 /// that point to V2 points to its first element.
5125 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5126 for (unsigned i = 0; i != NumElems; ++i) {
5127 if (Mask[i] > (int)NumElems) {
5133 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5134 /// operation of specified width.
5135 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5137 unsigned NumElems = VT.getVectorNumElements();
5138 SmallVector<int, 8> Mask;
5139 Mask.push_back(NumElems);
5140 for (unsigned i = 1; i != NumElems; ++i)
5142 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5145 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5146 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5148 unsigned NumElems = VT.getVectorNumElements();
5149 SmallVector<int, 8> Mask;
5150 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5152 Mask.push_back(i + NumElems);
5154 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5157 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5158 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5160 unsigned NumElems = VT.getVectorNumElements();
5161 SmallVector<int, 8> Mask;
5162 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5163 Mask.push_back(i + Half);
5164 Mask.push_back(i + NumElems + Half);
5166 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5169 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5170 // a generic shuffle instruction because the target has no such instructions.
5171 // Generate shuffles which repeat i16 and i8 several times until they can be
5172 // represented by v4f32 and then be manipulated by target suported shuffles.
5173 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5174 MVT VT = V.getSimpleValueType();
5175 int NumElems = VT.getVectorNumElements();
5178 while (NumElems > 4) {
5179 if (EltNo < NumElems/2) {
5180 V = getUnpackl(DAG, dl, VT, V, V);
5182 V = getUnpackh(DAG, dl, VT, V, V);
5183 EltNo -= NumElems/2;
5190 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5191 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5192 MVT VT = V.getSimpleValueType();
5195 if (VT.is128BitVector()) {
5196 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5197 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5198 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5200 } else if (VT.is256BitVector()) {
5201 // To use VPERMILPS to splat scalars, the second half of indicies must
5202 // refer to the higher part, which is a duplication of the lower one,
5203 // because VPERMILPS can only handle in-lane permutations.
5204 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5205 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5207 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5208 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5211 llvm_unreachable("Vector size not supported");
5213 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5216 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5217 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5218 MVT SrcVT = SV->getSimpleValueType(0);
5219 SDValue V1 = SV->getOperand(0);
5222 int EltNo = SV->getSplatIndex();
5223 int NumElems = SrcVT.getVectorNumElements();
5224 bool Is256BitVec = SrcVT.is256BitVector();
5226 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5227 "Unknown how to promote splat for type");
5229 // Extract the 128-bit part containing the splat element and update
5230 // the splat element index when it refers to the higher register.
5232 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5233 if (EltNo >= NumElems/2)
5234 EltNo -= NumElems/2;
5237 // All i16 and i8 vector types can't be used directly by a generic shuffle
5238 // instruction because the target has no such instruction. Generate shuffles
5239 // which repeat i16 and i8 several times until they fit in i32, and then can
5240 // be manipulated by target suported shuffles.
5241 MVT EltVT = SrcVT.getVectorElementType();
5242 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5243 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5245 // Recreate the 256-bit vector and place the same 128-bit vector
5246 // into the low and high part. This is necessary because we want
5247 // to use VPERM* to shuffle the vectors
5249 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5252 return getLegalSplat(DAG, V1, EltNo);
5255 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5256 /// vector of zero or undef vector. This produces a shuffle where the low
5257 /// element of V2 is swizzled into the zero/undef vector, landing at element
5258 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5259 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5261 const X86Subtarget *Subtarget,
5262 SelectionDAG &DAG) {
5263 MVT VT = V2.getSimpleValueType();
5265 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5266 unsigned NumElems = VT.getVectorNumElements();
5267 SmallVector<int, 16> MaskVec;
5268 for (unsigned i = 0; i != NumElems; ++i)
5269 // If this is the insertion idx, put the low elt of V2 here.
5270 MaskVec.push_back(i == Idx ? NumElems : i);
5271 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5274 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5275 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5276 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5277 /// shuffles which use a single input multiple times, and in those cases it will
5278 /// adjust the mask to only have indices within that single input.
5279 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5280 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5281 unsigned NumElems = VT.getVectorNumElements();
5285 bool IsFakeUnary = false;
5286 switch(N->getOpcode()) {
5288 ImmN = N->getOperand(N->getNumOperands()-1);
5289 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5290 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5292 case X86ISD::UNPCKH:
5293 DecodeUNPCKHMask(VT, Mask);
5294 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5296 case X86ISD::UNPCKL:
5297 DecodeUNPCKLMask(VT, Mask);
5298 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5300 case X86ISD::MOVHLPS:
5301 DecodeMOVHLPSMask(NumElems, Mask);
5302 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5304 case X86ISD::MOVLHPS:
5305 DecodeMOVLHPSMask(NumElems, Mask);
5306 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5308 case X86ISD::PALIGNR:
5309 ImmN = N->getOperand(N->getNumOperands()-1);
5310 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5312 case X86ISD::PSHUFD:
5313 case X86ISD::VPERMILP:
5314 ImmN = N->getOperand(N->getNumOperands()-1);
5315 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5318 case X86ISD::PSHUFHW:
5319 ImmN = N->getOperand(N->getNumOperands()-1);
5320 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5323 case X86ISD::PSHUFLW:
5324 ImmN = N->getOperand(N->getNumOperands()-1);
5325 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5328 case X86ISD::PSHUFB: {
5330 SDValue MaskNode = N->getOperand(1);
5331 while (MaskNode->getOpcode() == ISD::BITCAST)
5332 MaskNode = MaskNode->getOperand(0);
5334 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5335 // If we have a build-vector, then things are easy.
5336 EVT VT = MaskNode.getValueType();
5337 assert(VT.isVector() &&
5338 "Can't produce a non-vector with a build_vector!");
5339 if (!VT.isInteger())
5342 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5344 SmallVector<uint64_t, 32> RawMask;
5345 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5346 auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5349 APInt MaskElement = CN->getAPIntValue();
5351 // We now have to decode the element which could be any integer size and
5352 // extract each byte of it.
5353 for (int j = 0; j < NumBytesPerElement; ++j) {
5354 // Note that this is x86 and so always little endian: the low byte is
5355 // the first byte of the mask.
5356 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5357 MaskElement = MaskElement.lshr(8);
5360 DecodePSHUFBMask(RawMask, Mask);
5364 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5368 SDValue Ptr = MaskLoad->getBasePtr();
5369 if (Ptr->getOpcode() == X86ISD::Wrapper)
5370 Ptr = Ptr->getOperand(0);
5372 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5373 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5376 if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5377 // FIXME: Support AVX-512 here.
5378 if (!C->getType()->isVectorTy() ||
5379 (C->getNumElements() != 16 && C->getNumElements() != 32))
5382 assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5383 DecodePSHUFBMask(C, Mask);
5389 case X86ISD::VPERMI:
5390 ImmN = N->getOperand(N->getNumOperands()-1);
5391 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5395 case X86ISD::MOVSD: {
5396 // The index 0 always comes from the first element of the second source,
5397 // this is why MOVSS and MOVSD are used in the first place. The other
5398 // elements come from the other positions of the first source vector
5399 Mask.push_back(NumElems);
5400 for (unsigned i = 1; i != NumElems; ++i) {
5405 case X86ISD::VPERM2X128:
5406 ImmN = N->getOperand(N->getNumOperands()-1);
5407 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5408 if (Mask.empty()) return false;
5410 case X86ISD::MOVDDUP:
5411 case X86ISD::MOVLHPD:
5412 case X86ISD::MOVLPD:
5413 case X86ISD::MOVLPS:
5414 case X86ISD::MOVSHDUP:
5415 case X86ISD::MOVSLDUP:
5416 // Not yet implemented
5418 default: llvm_unreachable("unknown target shuffle node");
5421 // If we have a fake unary shuffle, the shuffle mask is spread across two
5422 // inputs that are actually the same node. Re-map the mask to always point
5423 // into the first input.
5426 if (M >= (int)Mask.size())
5432 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5433 /// element of the result of the vector shuffle.
5434 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5437 return SDValue(); // Limit search depth.
5439 SDValue V = SDValue(N, 0);
5440 EVT VT = V.getValueType();
5441 unsigned Opcode = V.getOpcode();
5443 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5444 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5445 int Elt = SV->getMaskElt(Index);
5448 return DAG.getUNDEF(VT.getVectorElementType());
5450 unsigned NumElems = VT.getVectorNumElements();
5451 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5452 : SV->getOperand(1);
5453 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5456 // Recurse into target specific vector shuffles to find scalars.
5457 if (isTargetShuffle(Opcode)) {
5458 MVT ShufVT = V.getSimpleValueType();
5459 unsigned NumElems = ShufVT.getVectorNumElements();
5460 SmallVector<int, 16> ShuffleMask;
5463 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5466 int Elt = ShuffleMask[Index];
5468 return DAG.getUNDEF(ShufVT.getVectorElementType());
5470 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5472 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5476 // Actual nodes that may contain scalar elements
5477 if (Opcode == ISD::BITCAST) {
5478 V = V.getOperand(0);
5479 EVT SrcVT = V.getValueType();
5480 unsigned NumElems = VT.getVectorNumElements();
5482 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5486 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5487 return (Index == 0) ? V.getOperand(0)
5488 : DAG.getUNDEF(VT.getVectorElementType());
5490 if (V.getOpcode() == ISD::BUILD_VECTOR)
5491 return V.getOperand(Index);
5496 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5497 /// shuffle operation which come from a consecutively from a zero. The
5498 /// search can start in two different directions, from left or right.
5499 /// We count undefs as zeros until PreferredNum is reached.
5500 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5501 unsigned NumElems, bool ZerosFromLeft,
5503 unsigned PreferredNum = -1U) {
5504 unsigned NumZeros = 0;
5505 for (unsigned i = 0; i != NumElems; ++i) {
5506 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5507 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5511 if (X86::isZeroNode(Elt))
5513 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5514 NumZeros = std::min(NumZeros + 1, PreferredNum);
5522 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5523 /// correspond consecutively to elements from one of the vector operands,
5524 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5526 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5527 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5528 unsigned NumElems, unsigned &OpNum) {
5529 bool SeenV1 = false;
5530 bool SeenV2 = false;
5532 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5533 int Idx = SVOp->getMaskElt(i);
5534 // Ignore undef indicies
5538 if (Idx < (int)NumElems)
5543 // Only accept consecutive elements from the same vector
5544 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5548 OpNum = SeenV1 ? 0 : 1;
5552 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5553 /// logical left shift of a vector.
5554 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5555 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5557 SVOp->getSimpleValueType(0).getVectorNumElements();
5558 unsigned NumZeros = getNumOfConsecutiveZeros(
5559 SVOp, NumElems, false /* check zeros from right */, DAG,
5560 SVOp->getMaskElt(0));
5566 // Considering the elements in the mask that are not consecutive zeros,
5567 // check if they consecutively come from only one of the source vectors.
5569 // V1 = {X, A, B, C} 0
5571 // vector_shuffle V1, V2 <1, 2, 3, X>
5573 if (!isShuffleMaskConsecutive(SVOp,
5574 0, // Mask Start Index
5575 NumElems-NumZeros, // Mask End Index(exclusive)
5576 NumZeros, // Where to start looking in the src vector
5577 NumElems, // Number of elements in vector
5578 OpSrc)) // Which source operand ?
5583 ShVal = SVOp->getOperand(OpSrc);
5587 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5588 /// logical left shift of a vector.
5589 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5590 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5592 SVOp->getSimpleValueType(0).getVectorNumElements();
5593 unsigned NumZeros = getNumOfConsecutiveZeros(
5594 SVOp, NumElems, true /* check zeros from left */, DAG,
5595 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5601 // Considering the elements in the mask that are not consecutive zeros,
5602 // check if they consecutively come from only one of the source vectors.
5604 // 0 { A, B, X, X } = V2
5606 // vector_shuffle V1, V2 <X, X, 4, 5>
5608 if (!isShuffleMaskConsecutive(SVOp,
5609 NumZeros, // Mask Start Index
5610 NumElems, // Mask End Index(exclusive)
5611 0, // Where to start looking in the src vector
5612 NumElems, // Number of elements in vector
5613 OpSrc)) // Which source operand ?
5618 ShVal = SVOp->getOperand(OpSrc);
5622 /// isVectorShift - Returns true if the shuffle can be implemented as a
5623 /// logical left or right shift of a vector.
5624 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5625 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5626 // Although the logic below support any bitwidth size, there are no
5627 // shift instructions which handle more than 128-bit vectors.
5628 if (!SVOp->getSimpleValueType(0).is128BitVector())
5631 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5632 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5638 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5640 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5641 unsigned NumNonZero, unsigned NumZero,
5643 const X86Subtarget* Subtarget,
5644 const TargetLowering &TLI) {
5651 for (unsigned i = 0; i < 16; ++i) {
5652 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5653 if (ThisIsNonZero && First) {
5655 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5657 V = DAG.getUNDEF(MVT::v8i16);
5662 SDValue ThisElt, LastElt;
5663 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5664 if (LastIsNonZero) {
5665 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5666 MVT::i16, Op.getOperand(i-1));
5668 if (ThisIsNonZero) {
5669 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5670 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5671 ThisElt, DAG.getConstant(8, MVT::i8));
5673 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5677 if (ThisElt.getNode())
5678 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5679 DAG.getIntPtrConstant(i/2));
5683 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5686 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5688 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5689 unsigned NumNonZero, unsigned NumZero,
5691 const X86Subtarget* Subtarget,
5692 const TargetLowering &TLI) {
5699 for (unsigned i = 0; i < 8; ++i) {
5700 bool isNonZero = (NonZeros & (1 << i)) != 0;
5704 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5706 V = DAG.getUNDEF(MVT::v8i16);
5709 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5710 MVT::v8i16, V, Op.getOperand(i),
5711 DAG.getIntPtrConstant(i));
5718 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5719 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5720 unsigned NonZeros, unsigned NumNonZero,
5721 unsigned NumZero, SelectionDAG &DAG,
5722 const X86Subtarget *Subtarget,
5723 const TargetLowering &TLI) {
5724 // We know there's at least one non-zero element
5725 unsigned FirstNonZeroIdx = 0;
5726 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5727 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5728 X86::isZeroNode(FirstNonZero)) {
5730 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5733 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5734 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5737 SDValue V = FirstNonZero.getOperand(0);
5738 MVT VVT = V.getSimpleValueType();
5739 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5742 unsigned FirstNonZeroDst =
5743 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5744 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5745 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5746 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5748 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5749 SDValue Elem = Op.getOperand(Idx);
5750 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5753 // TODO: What else can be here? Deal with it.
5754 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5757 // TODO: Some optimizations are still possible here
5758 // ex: Getting one element from a vector, and the rest from another.
5759 if (Elem.getOperand(0) != V)
5762 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5765 else if (IncorrectIdx == -1U) {
5769 // There was already one element with an incorrect index.
5770 // We can't optimize this case to an insertps.
5774 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5776 EVT VT = Op.getSimpleValueType();
5777 unsigned ElementMoveMask = 0;
5778 if (IncorrectIdx == -1U)
5779 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5781 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5783 SDValue InsertpsMask =
5784 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5785 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5791 /// getVShift - Return a vector logical shift node.
5793 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5794 unsigned NumBits, SelectionDAG &DAG,
5795 const TargetLowering &TLI, SDLoc dl) {
5796 assert(VT.is128BitVector() && "Unknown type for VShift");
5797 EVT ShVT = MVT::v2i64;
5798 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5799 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5800 return DAG.getNode(ISD::BITCAST, dl, VT,
5801 DAG.getNode(Opc, dl, ShVT, SrcOp,
5802 DAG.getConstant(NumBits,
5803 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5807 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5809 // Check if the scalar load can be widened into a vector load. And if
5810 // the address is "base + cst" see if the cst can be "absorbed" into
5811 // the shuffle mask.
5812 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5813 SDValue Ptr = LD->getBasePtr();
5814 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5816 EVT PVT = LD->getValueType(0);
5817 if (PVT != MVT::i32 && PVT != MVT::f32)
5822 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5823 FI = FINode->getIndex();
5825 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5826 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5827 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5828 Offset = Ptr.getConstantOperandVal(1);
5829 Ptr = Ptr.getOperand(0);
5834 // FIXME: 256-bit vector instructions don't require a strict alignment,
5835 // improve this code to support it better.
5836 unsigned RequiredAlign = VT.getSizeInBits()/8;
5837 SDValue Chain = LD->getChain();
5838 // Make sure the stack object alignment is at least 16 or 32.
5839 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5840 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5841 if (MFI->isFixedObjectIndex(FI)) {
5842 // Can't change the alignment. FIXME: It's possible to compute
5843 // the exact stack offset and reference FI + adjust offset instead.
5844 // If someone *really* cares about this. That's the way to implement it.
5847 MFI->setObjectAlignment(FI, RequiredAlign);
5851 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5852 // Ptr + (Offset & ~15).
5855 if ((Offset % RequiredAlign) & 3)
5857 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5859 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5860 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5862 int EltNo = (Offset - StartOffset) >> 2;
5863 unsigned NumElems = VT.getVectorNumElements();
5865 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5866 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5867 LD->getPointerInfo().getWithOffset(StartOffset),
5868 false, false, false, 0);
5870 SmallVector<int, 8> Mask;
5871 for (unsigned i = 0; i != NumElems; ++i)
5872 Mask.push_back(EltNo);
5874 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5880 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5881 /// vector of type 'VT', see if the elements can be replaced by a single large
5882 /// load which has the same value as a build_vector whose operands are 'elts'.
5884 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5886 /// FIXME: we'd also like to handle the case where the last elements are zero
5887 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5888 /// There's even a handy isZeroNode for that purpose.
5889 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5890 SDLoc &DL, SelectionDAG &DAG,
5891 bool isAfterLegalize) {
5892 EVT EltVT = VT.getVectorElementType();
5893 unsigned NumElems = Elts.size();
5895 LoadSDNode *LDBase = nullptr;
5896 unsigned LastLoadedElt = -1U;
5898 // For each element in the initializer, see if we've found a load or an undef.
5899 // If we don't find an initial load element, or later load elements are
5900 // non-consecutive, bail out.
5901 for (unsigned i = 0; i < NumElems; ++i) {
5902 SDValue Elt = Elts[i];
5904 if (!Elt.getNode() ||
5905 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5908 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5910 LDBase = cast<LoadSDNode>(Elt.getNode());
5914 if (Elt.getOpcode() == ISD::UNDEF)
5917 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5918 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5923 // If we have found an entire vector of loads and undefs, then return a large
5924 // load of the entire vector width starting at the base pointer. If we found
5925 // consecutive loads for the low half, generate a vzext_load node.
5926 if (LastLoadedElt == NumElems - 1) {
5928 if (isAfterLegalize &&
5929 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5932 SDValue NewLd = SDValue();
5934 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5935 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5936 LDBase->getPointerInfo(),
5937 LDBase->isVolatile(), LDBase->isNonTemporal(),
5938 LDBase->isInvariant(), 0);
5939 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5940 LDBase->getPointerInfo(),
5941 LDBase->isVolatile(), LDBase->isNonTemporal(),
5942 LDBase->isInvariant(), LDBase->getAlignment());
5944 if (LDBase->hasAnyUseOfValue(1)) {
5945 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5947 SDValue(NewLd.getNode(), 1));
5948 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5949 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5950 SDValue(NewLd.getNode(), 1));
5955 if (NumElems == 4 && LastLoadedElt == 1 &&
5956 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5957 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5958 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5960 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5961 LDBase->getPointerInfo(),
5962 LDBase->getAlignment(),
5963 false/*isVolatile*/, true/*ReadMem*/,
5966 // Make sure the newly-created LOAD is in the same position as LDBase in
5967 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5968 // update uses of LDBase's output chain to use the TokenFactor.
5969 if (LDBase->hasAnyUseOfValue(1)) {
5970 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5971 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5972 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5973 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5974 SDValue(ResNode.getNode(), 1));
5977 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5982 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5983 /// to generate a splat value for the following cases:
5984 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5985 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5986 /// a scalar load, or a constant.
5987 /// The VBROADCAST node is returned when a pattern is found,
5988 /// or SDValue() otherwise.
5989 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5990 SelectionDAG &DAG) {
5991 if (!Subtarget->hasFp256())
5994 MVT VT = Op.getSimpleValueType();
5997 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5998 "Unsupported vector type for broadcast.");
6003 switch (Op.getOpcode()) {
6005 // Unknown pattern found.
6008 case ISD::BUILD_VECTOR: {
6009 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
6010 BitVector UndefElements;
6011 SDValue Splat = BVOp->getSplatValue(&UndefElements);
6013 // We need a splat of a single value to use broadcast, and it doesn't
6014 // make any sense if the value is only in one element of the vector.
6015 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
6019 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6020 Ld.getOpcode() == ISD::ConstantFP);
6022 // Make sure that all of the users of a non-constant load are from the
6023 // BUILD_VECTOR node.
6024 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6029 case ISD::VECTOR_SHUFFLE: {
6030 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6032 // Shuffles must have a splat mask where the first element is
6034 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
6037 SDValue Sc = Op.getOperand(0);
6038 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
6039 Sc.getOpcode() != ISD::BUILD_VECTOR) {
6041 if (!Subtarget->hasInt256())
6044 // Use the register form of the broadcast instruction available on AVX2.
6045 if (VT.getSizeInBits() >= 256)
6046 Sc = Extract128BitVector(Sc, 0, DAG, dl);
6047 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6050 Ld = Sc.getOperand(0);
6051 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6052 Ld.getOpcode() == ISD::ConstantFP);
6054 // The scalar_to_vector node and the suspected
6055 // load node must have exactly one user.
6056 // Constants may have multiple users.
6058 // AVX-512 has register version of the broadcast
6059 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6060 Ld.getValueType().getSizeInBits() >= 32;
6061 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6068 bool IsGE256 = (VT.getSizeInBits() >= 256);
6070 // Handle the broadcasting a single constant scalar from the constant pool
6071 // into a vector. On Sandybridge it is still better to load a constant vector
6072 // from the constant pool and not to broadcast it from a scalar.
6073 if (ConstSplatVal && Subtarget->hasInt256()) {
6074 EVT CVT = Ld.getValueType();
6075 assert(!CVT.isVector() && "Must not broadcast a vector type");
6076 unsigned ScalarSize = CVT.getSizeInBits();
6078 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
6079 const Constant *C = nullptr;
6080 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6081 C = CI->getConstantIntValue();
6082 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6083 C = CF->getConstantFPValue();
6085 assert(C && "Invalid constant type");
6087 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6088 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6089 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6090 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6091 MachinePointerInfo::getConstantPool(),
6092 false, false, false, Alignment);
6094 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6098 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6099 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6101 // Handle AVX2 in-register broadcasts.
6102 if (!IsLoad && Subtarget->hasInt256() &&
6103 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6104 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6106 // The scalar source must be a normal load.
6110 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6111 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6113 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6114 // double since there is no vbroadcastsd xmm
6115 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6116 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6117 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6120 // Unsupported broadcast.
6124 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6125 /// underlying vector and index.
6127 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6129 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6131 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6132 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6135 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6137 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6139 // (extract_vector_elt (vector_shuffle<2,u,u,u>
6140 // (extract_subvector (v8f32 %vreg0), Constant<4>),
6143 // In this case the vector is the extract_subvector expression and the index
6144 // is 2, as specified by the shuffle.
6145 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6146 SDValue ShuffleVec = SVOp->getOperand(0);
6147 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6148 assert(ShuffleVecVT.getVectorElementType() ==
6149 ExtractedFromVec.getSimpleValueType().getVectorElementType());
6151 int ShuffleIdx = SVOp->getMaskElt(Idx);
6152 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6153 ExtractedFromVec = ShuffleVec;
6159 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6160 MVT VT = Op.getSimpleValueType();
6162 // Skip if insert_vec_elt is not supported.
6163 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6164 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6168 unsigned NumElems = Op.getNumOperands();
6172 SmallVector<unsigned, 4> InsertIndices;
6173 SmallVector<int, 8> Mask(NumElems, -1);
6175 for (unsigned i = 0; i != NumElems; ++i) {
6176 unsigned Opc = Op.getOperand(i).getOpcode();
6178 if (Opc == ISD::UNDEF)
6181 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6182 // Quit if more than 1 elements need inserting.
6183 if (InsertIndices.size() > 1)
6186 InsertIndices.push_back(i);
6190 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6191 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6192 // Quit if non-constant index.
6193 if (!isa<ConstantSDNode>(ExtIdx))
6195 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6197 // Quit if extracted from vector of different type.
6198 if (ExtractedFromVec.getValueType() != VT)
6201 if (!VecIn1.getNode())
6202 VecIn1 = ExtractedFromVec;
6203 else if (VecIn1 != ExtractedFromVec) {
6204 if (!VecIn2.getNode())
6205 VecIn2 = ExtractedFromVec;
6206 else if (VecIn2 != ExtractedFromVec)
6207 // Quit if more than 2 vectors to shuffle
6211 if (ExtractedFromVec == VecIn1)
6213 else if (ExtractedFromVec == VecIn2)
6214 Mask[i] = Idx + NumElems;
6217 if (!VecIn1.getNode())
6220 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6221 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6222 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6223 unsigned Idx = InsertIndices[i];
6224 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6225 DAG.getIntPtrConstant(Idx));
6231 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6233 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6235 MVT VT = Op.getSimpleValueType();
6236 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6237 "Unexpected type in LowerBUILD_VECTORvXi1!");
6240 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6241 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6242 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6243 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6246 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6247 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6248 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6249 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6252 bool AllContants = true;
6253 uint64_t Immediate = 0;
6254 int NonConstIdx = -1;
6255 bool IsSplat = true;
6256 unsigned NumNonConsts = 0;
6257 unsigned NumConsts = 0;
6258 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6259 SDValue In = Op.getOperand(idx);
6260 if (In.getOpcode() == ISD::UNDEF)
6262 if (!isa<ConstantSDNode>(In)) {
6263 AllContants = false;
6269 if (cast<ConstantSDNode>(In)->getZExtValue())
6270 Immediate |= (1ULL << idx);
6272 if (In != Op.getOperand(0))
6277 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6278 DAG.getConstant(Immediate, MVT::i16));
6279 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6280 DAG.getIntPtrConstant(0));
6283 if (NumNonConsts == 1 && NonConstIdx != 0) {
6286 SDValue VecAsImm = DAG.getConstant(Immediate,
6287 MVT::getIntegerVT(VT.getSizeInBits()));
6288 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6291 DstVec = DAG.getUNDEF(VT);
6292 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6293 Op.getOperand(NonConstIdx),
6294 DAG.getIntPtrConstant(NonConstIdx));
6296 if (!IsSplat && (NonConstIdx != 0))
6297 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6298 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6301 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6302 DAG.getConstant(-1, SelectVT),
6303 DAG.getConstant(0, SelectVT));
6305 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6306 DAG.getConstant((Immediate | 1), SelectVT),
6307 DAG.getConstant(Immediate, SelectVT));
6308 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6311 /// \brief Return true if \p N implements a horizontal binop and return the
6312 /// operands for the horizontal binop into V0 and V1.
6314 /// This is a helper function of PerformBUILD_VECTORCombine.
6315 /// This function checks that the build_vector \p N in input implements a
6316 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6317 /// operation to match.
6318 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6319 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6320 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6323 /// This function only analyzes elements of \p N whose indices are
6324 /// in range [BaseIdx, LastIdx).
6325 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6327 unsigned BaseIdx, unsigned LastIdx,
6328 SDValue &V0, SDValue &V1) {
6329 EVT VT = N->getValueType(0);
6331 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6332 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6333 "Invalid Vector in input!");
6335 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6336 bool CanFold = true;
6337 unsigned ExpectedVExtractIdx = BaseIdx;
6338 unsigned NumElts = LastIdx - BaseIdx;
6339 V0 = DAG.getUNDEF(VT);
6340 V1 = DAG.getUNDEF(VT);
6342 // Check if N implements a horizontal binop.
6343 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6344 SDValue Op = N->getOperand(i + BaseIdx);
6347 if (Op->getOpcode() == ISD::UNDEF) {
6348 // Update the expected vector extract index.
6349 if (i * 2 == NumElts)
6350 ExpectedVExtractIdx = BaseIdx;
6351 ExpectedVExtractIdx += 2;
6355 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6360 SDValue Op0 = Op.getOperand(0);
6361 SDValue Op1 = Op.getOperand(1);
6363 // Try to match the following pattern:
6364 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6365 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6366 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6367 Op0.getOperand(0) == Op1.getOperand(0) &&
6368 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6369 isa<ConstantSDNode>(Op1.getOperand(1)));
6373 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6374 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6376 if (i * 2 < NumElts) {
6377 if (V0.getOpcode() == ISD::UNDEF)
6378 V0 = Op0.getOperand(0);
6380 if (V1.getOpcode() == ISD::UNDEF)
6381 V1 = Op0.getOperand(0);
6382 if (i * 2 == NumElts)
6383 ExpectedVExtractIdx = BaseIdx;
6386 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6387 if (I0 == ExpectedVExtractIdx)
6388 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6389 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6390 // Try to match the following dag sequence:
6391 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6392 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6396 ExpectedVExtractIdx += 2;
6402 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6403 /// a concat_vector.
6405 /// This is a helper function of PerformBUILD_VECTORCombine.
6406 /// This function expects two 256-bit vectors called V0 and V1.
6407 /// At first, each vector is split into two separate 128-bit vectors.
6408 /// Then, the resulting 128-bit vectors are used to implement two
6409 /// horizontal binary operations.
6411 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6413 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6414 /// the two new horizontal binop.
6415 /// When Mode is set, the first horizontal binop dag node would take as input
6416 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6417 /// horizontal binop dag node would take as input the lower 128-bit of V1
6418 /// and the upper 128-bit of V1.
6420 /// HADD V0_LO, V0_HI
6421 /// HADD V1_LO, V1_HI
6423 /// Otherwise, the first horizontal binop dag node takes as input the lower
6424 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6425 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6427 /// HADD V0_LO, V1_LO
6428 /// HADD V0_HI, V1_HI
6430 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6431 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6432 /// the upper 128-bits of the result.
6433 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6434 SDLoc DL, SelectionDAG &DAG,
6435 unsigned X86Opcode, bool Mode,
6436 bool isUndefLO, bool isUndefHI) {
6437 EVT VT = V0.getValueType();
6438 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6439 "Invalid nodes in input!");
6441 unsigned NumElts = VT.getVectorNumElements();
6442 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6443 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6444 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6445 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6446 EVT NewVT = V0_LO.getValueType();
6448 SDValue LO = DAG.getUNDEF(NewVT);
6449 SDValue HI = DAG.getUNDEF(NewVT);
6452 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6453 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6454 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6455 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6456 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6458 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6459 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6460 V1_LO->getOpcode() != ISD::UNDEF))
6461 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6463 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6464 V1_HI->getOpcode() != ISD::UNDEF))
6465 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6468 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6471 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6472 /// sequence of 'vadd + vsub + blendi'.
6473 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6474 const X86Subtarget *Subtarget) {
6476 EVT VT = BV->getValueType(0);
6477 unsigned NumElts = VT.getVectorNumElements();
6478 SDValue InVec0 = DAG.getUNDEF(VT);
6479 SDValue InVec1 = DAG.getUNDEF(VT);
6481 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6482 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6484 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6485 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6486 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6489 // Odd-numbered elements in the input build vector are obtained from
6490 // adding two integer/float elements.
6491 // Even-numbered elements in the input build vector are obtained from
6492 // subtracting two integer/float elements.
6493 unsigned ExpectedOpcode = ISD::FSUB;
6494 unsigned NextExpectedOpcode = ISD::FADD;
6495 bool AddFound = false;
6496 bool SubFound = false;
6498 for (unsigned i = 0, e = NumElts; i != e; i++) {
6499 SDValue Op = BV->getOperand(i);
6501 // Skip 'undef' values.
6502 unsigned Opcode = Op.getOpcode();
6503 if (Opcode == ISD::UNDEF) {
6504 std::swap(ExpectedOpcode, NextExpectedOpcode);
6508 // Early exit if we found an unexpected opcode.
6509 if (Opcode != ExpectedOpcode)
6512 SDValue Op0 = Op.getOperand(0);
6513 SDValue Op1 = Op.getOperand(1);
6515 // Try to match the following pattern:
6516 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6517 // Early exit if we cannot match that sequence.
6518 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6519 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6520 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6521 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6522 Op0.getOperand(1) != Op1.getOperand(1))
6525 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6529 // We found a valid add/sub node. Update the information accordingly.
6535 // Update InVec0 and InVec1.
6536 if (InVec0.getOpcode() == ISD::UNDEF)
6537 InVec0 = Op0.getOperand(0);
6538 if (InVec1.getOpcode() == ISD::UNDEF)
6539 InVec1 = Op1.getOperand(0);
6541 // Make sure that operands in input to each add/sub node always
6542 // come from a same pair of vectors.
6543 if (InVec0 != Op0.getOperand(0)) {
6544 if (ExpectedOpcode == ISD::FSUB)
6547 // FADD is commutable. Try to commute the operands
6548 // and then test again.
6549 std::swap(Op0, Op1);
6550 if (InVec0 != Op0.getOperand(0))
6554 if (InVec1 != Op1.getOperand(0))
6557 // Update the pair of expected opcodes.
6558 std::swap(ExpectedOpcode, NextExpectedOpcode);
6561 // Don't try to fold this build_vector into a VSELECT if it has
6562 // too many UNDEF operands.
6563 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6564 InVec1.getOpcode() != ISD::UNDEF) {
6565 // Emit a sequence of vector add and sub followed by a VSELECT.
6566 // The new VSELECT will be lowered into a BLENDI.
6567 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6568 // and emit a single ADDSUB instruction.
6569 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6570 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6572 // Construct the VSELECT mask.
6573 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6574 EVT SVT = MaskVT.getVectorElementType();
6575 unsigned SVTBits = SVT.getSizeInBits();
6576 SmallVector<SDValue, 8> Ops;
6578 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6579 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6580 APInt::getAllOnesValue(SVTBits);
6581 SDValue Constant = DAG.getConstant(Value, SVT);
6582 Ops.push_back(Constant);
6585 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6586 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6592 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6593 const X86Subtarget *Subtarget) {
6595 EVT VT = N->getValueType(0);
6596 unsigned NumElts = VT.getVectorNumElements();
6597 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6598 SDValue InVec0, InVec1;
6600 // Try to match an ADDSUB.
6601 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6602 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6603 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6604 if (Value.getNode())
6608 // Try to match horizontal ADD/SUB.
6609 unsigned NumUndefsLO = 0;
6610 unsigned NumUndefsHI = 0;
6611 unsigned Half = NumElts/2;
6613 // Count the number of UNDEF operands in the build_vector in input.
6614 for (unsigned i = 0, e = Half; i != e; ++i)
6615 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6618 for (unsigned i = Half, e = NumElts; i != e; ++i)
6619 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6622 // Early exit if this is either a build_vector of all UNDEFs or all the
6623 // operands but one are UNDEF.
6624 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6627 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6628 // Try to match an SSE3 float HADD/HSUB.
6629 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6630 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6632 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6633 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6634 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6635 // Try to match an SSSE3 integer HADD/HSUB.
6636 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6637 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6639 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6640 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6643 if (!Subtarget->hasAVX())
6646 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6647 // Try to match an AVX horizontal add/sub of packed single/double
6648 // precision floating point values from 256-bit vectors.
6649 SDValue InVec2, InVec3;
6650 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6651 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6652 ((InVec0.getOpcode() == ISD::UNDEF ||
6653 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6654 ((InVec1.getOpcode() == ISD::UNDEF ||
6655 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6656 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6658 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6659 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6660 ((InVec0.getOpcode() == ISD::UNDEF ||
6661 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6662 ((InVec1.getOpcode() == ISD::UNDEF ||
6663 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6664 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6665 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6666 // Try to match an AVX2 horizontal add/sub of signed integers.
6667 SDValue InVec2, InVec3;
6669 bool CanFold = true;
6671 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6672 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6673 ((InVec0.getOpcode() == ISD::UNDEF ||
6674 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6675 ((InVec1.getOpcode() == ISD::UNDEF ||
6676 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6677 X86Opcode = X86ISD::HADD;
6678 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6679 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6680 ((InVec0.getOpcode() == ISD::UNDEF ||
6681 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6682 ((InVec1.getOpcode() == ISD::UNDEF ||
6683 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6684 X86Opcode = X86ISD::HSUB;
6689 // Fold this build_vector into a single horizontal add/sub.
6690 // Do this only if the target has AVX2.
6691 if (Subtarget->hasAVX2())
6692 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6694 // Do not try to expand this build_vector into a pair of horizontal
6695 // add/sub if we can emit a pair of scalar add/sub.
6696 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6699 // Convert this build_vector into a pair of horizontal binop followed by
6701 bool isUndefLO = NumUndefsLO == Half;
6702 bool isUndefHI = NumUndefsHI == Half;
6703 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6704 isUndefLO, isUndefHI);
6708 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6709 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6711 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6712 X86Opcode = X86ISD::HADD;
6713 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6714 X86Opcode = X86ISD::HSUB;
6715 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6716 X86Opcode = X86ISD::FHADD;
6717 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6718 X86Opcode = X86ISD::FHSUB;
6722 // Don't try to expand this build_vector into a pair of horizontal add/sub
6723 // if we can simply emit a pair of scalar add/sub.
6724 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6727 // Convert this build_vector into two horizontal add/sub followed by
6729 bool isUndefLO = NumUndefsLO == Half;
6730 bool isUndefHI = NumUndefsHI == Half;
6731 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6732 isUndefLO, isUndefHI);
6739 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6742 MVT VT = Op.getSimpleValueType();
6743 MVT ExtVT = VT.getVectorElementType();
6744 unsigned NumElems = Op.getNumOperands();
6746 // Generate vectors for predicate vectors.
6747 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6748 return LowerBUILD_VECTORvXi1(Op, DAG);
6750 // Vectors containing all zeros can be matched by pxor and xorps later
6751 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6752 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6753 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6754 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6757 return getZeroVector(VT, Subtarget, DAG, dl);
6760 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6761 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6762 // vpcmpeqd on 256-bit vectors.
6763 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6764 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6767 if (!VT.is512BitVector())
6768 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6771 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6772 if (Broadcast.getNode())
6775 unsigned EVTBits = ExtVT.getSizeInBits();
6777 unsigned NumZero = 0;
6778 unsigned NumNonZero = 0;
6779 unsigned NonZeros = 0;
6780 bool IsAllConstants = true;
6781 SmallSet<SDValue, 8> Values;
6782 for (unsigned i = 0; i < NumElems; ++i) {
6783 SDValue Elt = Op.getOperand(i);
6784 if (Elt.getOpcode() == ISD::UNDEF)
6787 if (Elt.getOpcode() != ISD::Constant &&
6788 Elt.getOpcode() != ISD::ConstantFP)
6789 IsAllConstants = false;
6790 if (X86::isZeroNode(Elt))
6793 NonZeros |= (1 << i);
6798 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6799 if (NumNonZero == 0)
6800 return DAG.getUNDEF(VT);
6802 // Special case for single non-zero, non-undef, element.
6803 if (NumNonZero == 1) {
6804 unsigned Idx = countTrailingZeros(NonZeros);
6805 SDValue Item = Op.getOperand(Idx);
6807 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6808 // the value are obviously zero, truncate the value to i32 and do the
6809 // insertion that way. Only do this if the value is non-constant or if the
6810 // value is a constant being inserted into element 0. It is cheaper to do
6811 // a constant pool load than it is to do a movd + shuffle.
6812 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6813 (!IsAllConstants || Idx == 0)) {
6814 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6816 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6817 EVT VecVT = MVT::v4i32;
6818 unsigned VecElts = 4;
6820 // Truncate the value (which may itself be a constant) to i32, and
6821 // convert it to a vector with movd (S2V+shuffle to zero extend).
6822 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6823 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6825 // If using the new shuffle lowering, just directly insert this.
6826 if (ExperimentalVectorShuffleLowering)
6828 ISD::BITCAST, dl, VT,
6829 getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
6831 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6833 // Now we have our 32-bit value zero extended in the low element of
6834 // a vector. If Idx != 0, swizzle it into place.
6836 SmallVector<int, 4> Mask;
6837 Mask.push_back(Idx);
6838 for (unsigned i = 1; i != VecElts; ++i)
6840 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6843 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6847 // If we have a constant or non-constant insertion into the low element of
6848 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6849 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6850 // depending on what the source datatype is.
6853 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6855 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6856 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6857 if (VT.is256BitVector() || VT.is512BitVector()) {
6858 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6859 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6860 Item, DAG.getIntPtrConstant(0));
6862 assert(VT.is128BitVector() && "Expected an SSE value type!");
6863 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6864 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6865 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6868 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6869 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6870 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6871 if (VT.is256BitVector()) {
6872 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6873 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6875 assert(VT.is128BitVector() && "Expected an SSE value type!");
6876 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6878 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6882 // Is it a vector logical left shift?
6883 if (NumElems == 2 && Idx == 1 &&
6884 X86::isZeroNode(Op.getOperand(0)) &&
6885 !X86::isZeroNode(Op.getOperand(1))) {
6886 unsigned NumBits = VT.getSizeInBits();
6887 return getVShift(true, VT,
6888 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6889 VT, Op.getOperand(1)),
6890 NumBits/2, DAG, *this, dl);
6893 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6896 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6897 // is a non-constant being inserted into an element other than the low one,
6898 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6899 // movd/movss) to move this into the low element, then shuffle it into
6901 if (EVTBits == 32) {
6902 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6904 // If using the new shuffle lowering, just directly insert this.
6905 if (ExperimentalVectorShuffleLowering)
6906 return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6908 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6909 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6910 SmallVector<int, 8> MaskVec;
6911 for (unsigned i = 0; i != NumElems; ++i)
6912 MaskVec.push_back(i == Idx ? 0 : 1);
6913 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6917 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6918 if (Values.size() == 1) {
6919 if (EVTBits == 32) {
6920 // Instead of a shuffle like this:
6921 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6922 // Check if it's possible to issue this instead.
6923 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6924 unsigned Idx = countTrailingZeros(NonZeros);
6925 SDValue Item = Op.getOperand(Idx);
6926 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6927 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6932 // A vector full of immediates; various special cases are already
6933 // handled, so this is best done with a single constant-pool load.
6937 // For AVX-length vectors, build the individual 128-bit pieces and use
6938 // shuffles to put them in place.
6939 if (VT.is256BitVector() || VT.is512BitVector()) {
6940 SmallVector<SDValue, 64> V;
6941 for (unsigned i = 0; i != NumElems; ++i)
6942 V.push_back(Op.getOperand(i));
6944 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6946 // Build both the lower and upper subvector.
6947 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6948 makeArrayRef(&V[0], NumElems/2));
6949 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6950 makeArrayRef(&V[NumElems / 2], NumElems/2));
6952 // Recreate the wider vector with the lower and upper part.
6953 if (VT.is256BitVector())
6954 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6955 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6958 // Let legalizer expand 2-wide build_vectors.
6959 if (EVTBits == 64) {
6960 if (NumNonZero == 1) {
6961 // One half is zero or undef.
6962 unsigned Idx = countTrailingZeros(NonZeros);
6963 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6964 Op.getOperand(Idx));
6965 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6970 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6971 if (EVTBits == 8 && NumElems == 16) {
6972 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6974 if (V.getNode()) return V;
6977 if (EVTBits == 16 && NumElems == 8) {
6978 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6980 if (V.getNode()) return V;
6983 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6984 if (EVTBits == 32 && NumElems == 4) {
6985 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6986 NumZero, DAG, Subtarget, *this);
6991 // If element VT is == 32 bits, turn it into a number of shuffles.
6992 SmallVector<SDValue, 8> V(NumElems);
6993 if (NumElems == 4 && NumZero > 0) {
6994 for (unsigned i = 0; i < 4; ++i) {
6995 bool isZero = !(NonZeros & (1 << i));
6997 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6999 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7002 for (unsigned i = 0; i < 2; ++i) {
7003 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
7006 V[i] = V[i*2]; // Must be a zero vector.
7009 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
7012 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
7015 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
7020 bool Reverse1 = (NonZeros & 0x3) == 2;
7021 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
7025 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
7026 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
7028 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
7031 if (Values.size() > 1 && VT.is128BitVector()) {
7032 // Check for a build vector of consecutive loads.
7033 for (unsigned i = 0; i < NumElems; ++i)
7034 V[i] = Op.getOperand(i);
7036 // Check for elements which are consecutive loads.
7037 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
7041 // Check for a build vector from mostly shuffle plus few inserting.
7042 SDValue Sh = buildFromShuffleMostly(Op, DAG);
7046 // For SSE 4.1, use insertps to put the high elements into the low element.
7047 if (getSubtarget()->hasSSE41()) {
7049 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
7050 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7052 Result = DAG.getUNDEF(VT);
7054 for (unsigned i = 1; i < NumElems; ++i) {
7055 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7056 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7057 Op.getOperand(i), DAG.getIntPtrConstant(i));
7062 // Otherwise, expand into a number of unpckl*, start by extending each of
7063 // our (non-undef) elements to the full vector width with the element in the
7064 // bottom slot of the vector (which generates no code for SSE).
7065 for (unsigned i = 0; i < NumElems; ++i) {
7066 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7067 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7069 V[i] = DAG.getUNDEF(VT);
7072 // Next, we iteratively mix elements, e.g. for v4f32:
7073 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7074 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7075 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
7076 unsigned EltStride = NumElems >> 1;
7077 while (EltStride != 0) {
7078 for (unsigned i = 0; i < EltStride; ++i) {
7079 // If V[i+EltStride] is undef and this is the first round of mixing,
7080 // then it is safe to just drop this shuffle: V[i] is already in the
7081 // right place, the one element (since it's the first round) being
7082 // inserted as undef can be dropped. This isn't safe for successive
7083 // rounds because they will permute elements within both vectors.
7084 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7085 EltStride == NumElems/2)
7088 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7097 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7098 // to create 256-bit vectors from two other 128-bit ones.
7099 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7101 MVT ResVT = Op.getSimpleValueType();
7103 assert((ResVT.is256BitVector() ||
7104 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7106 SDValue V1 = Op.getOperand(0);
7107 SDValue V2 = Op.getOperand(1);
7108 unsigned NumElems = ResVT.getVectorNumElements();
7109 if(ResVT.is256BitVector())
7110 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7112 if (Op.getNumOperands() == 4) {
7113 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7114 ResVT.getVectorNumElements()/2);
7115 SDValue V3 = Op.getOperand(2);
7116 SDValue V4 = Op.getOperand(3);
7117 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7118 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7120 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7123 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7124 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7125 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7126 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7127 Op.getNumOperands() == 4)));
7129 // AVX can use the vinsertf128 instruction to create 256-bit vectors
7130 // from two other 128-bit ones.
7132 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7133 return LowerAVXCONCAT_VECTORS(Op, DAG);
7137 //===----------------------------------------------------------------------===//
7138 // Vector shuffle lowering
7140 // This is an experimental code path for lowering vector shuffles on x86. It is
7141 // designed to handle arbitrary vector shuffles and blends, gracefully
7142 // degrading performance as necessary. It works hard to recognize idiomatic
7143 // shuffles and lower them to optimal instruction patterns without leaving
7144 // a framework that allows reasonably efficient handling of all vector shuffle
7146 //===----------------------------------------------------------------------===//
7148 /// \brief Tiny helper function to identify a no-op mask.
7150 /// This is a somewhat boring predicate function. It checks whether the mask
7151 /// array input, which is assumed to be a single-input shuffle mask of the kind
7152 /// used by the X86 shuffle instructions (not a fully general
7153 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7154 /// in-place shuffle are 'no-op's.
7155 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7156 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7157 if (Mask[i] != -1 && Mask[i] != i)
7162 /// \brief Helper function to classify a mask as a single-input mask.
7164 /// This isn't a generic single-input test because in the vector shuffle
7165 /// lowering we canonicalize single inputs to be the first input operand. This
7166 /// means we can more quickly test for a single input by only checking whether
7167 /// an input from the second operand exists. We also assume that the size of
7168 /// mask corresponds to the size of the input vectors which isn't true in the
7169 /// fully general case.
7170 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7172 if (M >= (int)Mask.size())
7177 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7178 // 2013 will allow us to use it as a non-type template parameter.
7181 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7183 /// See its documentation for details.
7184 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7185 if (Mask.size() != Args.size())
7187 for (int i = 0, e = Mask.size(); i < e; ++i) {
7188 assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7189 assert(*Args[i] < (int)Args.size() * 2 &&
7190 "Argument outside the range of possible shuffle inputs!");
7191 if (Mask[i] != -1 && Mask[i] != *Args[i])
7199 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7202 /// This is a fast way to test a shuffle mask against a fixed pattern:
7204 /// if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7206 /// It returns true if the mask is exactly as wide as the argument list, and
7207 /// each element of the mask is either -1 (signifying undef) or the value given
7208 /// in the argument.
7209 static const VariadicFunction1<
7210 bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7212 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7214 /// This helper function produces an 8-bit shuffle immediate corresponding to
7215 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7216 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7219 /// NB: We rely heavily on "undef" masks preserving the input lane.
7220 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7221 SelectionDAG &DAG) {
7222 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7223 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7224 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7225 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7226 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7229 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7230 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7231 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7232 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7233 return DAG.getConstant(Imm, MVT::i8);
7236 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7238 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7239 /// support for floating point shuffles but not integer shuffles. These
7240 /// instructions will incur a domain crossing penalty on some chips though so
7241 /// it is better to avoid lowering through this for integer vectors where
7243 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7244 const X86Subtarget *Subtarget,
7245 SelectionDAG &DAG) {
7247 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7248 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7249 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7250 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7251 ArrayRef<int> Mask = SVOp->getMask();
7252 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7254 if (isSingleInputShuffleMask(Mask)) {
7255 // Straight shuffle of a single input vector. Simulate this by using the
7256 // single input as both of the "inputs" to this instruction..
7257 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7258 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7259 DAG.getConstant(SHUFPDMask, MVT::i8));
7261 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7262 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7264 // Use dedicated unpack instructions for masks that match their pattern.
7265 if (isShuffleEquivalent(Mask, 0, 2))
7266 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7267 if (isShuffleEquivalent(Mask, 1, 3))
7268 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7270 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7271 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7272 DAG.getConstant(SHUFPDMask, MVT::i8));
7275 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7277 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7278 /// the integer unit to minimize domain crossing penalties. However, for blends
7279 /// it falls back to the floating point shuffle operation with appropriate bit
7281 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7282 const X86Subtarget *Subtarget,
7283 SelectionDAG &DAG) {
7285 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7286 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7287 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7288 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7289 ArrayRef<int> Mask = SVOp->getMask();
7290 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7292 if (isSingleInputShuffleMask(Mask)) {
7293 // Straight shuffle of a single input vector. For everything from SSE2
7294 // onward this has a single fast instruction with no scary immediates.
7295 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7296 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7297 int WidenedMask[4] = {
7298 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7299 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7301 ISD::BITCAST, DL, MVT::v2i64,
7302 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7303 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7306 // Use dedicated unpack instructions for masks that match their pattern.
7307 if (isShuffleEquivalent(Mask, 0, 2))
7308 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7309 if (isShuffleEquivalent(Mask, 1, 3))
7310 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7312 // We implement this with SHUFPD which is pretty lame because it will likely
7313 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7314 // However, all the alternatives are still more cycles and newer chips don't
7315 // have this problem. It would be really nice if x86 had better shuffles here.
7316 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7317 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7318 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7319 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7322 /// \brief Lower 4-lane 32-bit floating point shuffles.
7324 /// Uses instructions exclusively from the floating point unit to minimize
7325 /// domain crossing penalties, as these are sufficient to implement all v4f32
7327 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7328 const X86Subtarget *Subtarget,
7329 SelectionDAG &DAG) {
7331 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7332 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7333 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7334 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7335 ArrayRef<int> Mask = SVOp->getMask();
7336 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7338 SDValue LowV = V1, HighV = V2;
7339 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7342 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7344 if (NumV2Elements == 0)
7345 // Straight shuffle of a single input vector. We pass the input vector to
7346 // both operands to simulate this with a SHUFPS.
7347 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7348 getV4X86ShuffleImm8ForMask(Mask, DAG));
7350 // Use dedicated unpack instructions for masks that match their pattern.
7351 if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7352 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7353 if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7354 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7356 if (NumV2Elements == 1) {
7358 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7361 // Check for whether we can use INSERTPS to perform the blend. We only use
7362 // INSERTPS when the V1 elements are already in the correct locations
7363 // because otherwise we can just always use two SHUFPS instructions which
7364 // are much smaller to encode than a SHUFPS and an INSERTPS.
7365 if (Subtarget->hasSSE41()) {
7366 // When using INSERTPS we can zero any lane of the destination. Collect
7367 // the zero inputs into a mask and drop them from the lanes of V1 which
7368 // actually need to be present as inputs to the INSERTPS.
7370 if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7371 ZMask = 0xF ^ (1 << V2Index);
7372 } else if (V1.getOpcode() == ISD::BUILD_VECTOR) {
7373 for (int i = 0; i < 4; ++i) {
7378 SDValue Input = V1.getOperand(M);
7379 if (Input.getOpcode() != ISD::UNDEF &&
7380 !X86::isZeroNode(Input)) {
7381 // A non-zero input!
7390 // Synthesize a shuffle mask for the non-zero and non-v2 inputs.
7391 int InsertShuffleMask[4] = {-1, -1, -1, -1};
7392 for (int i = 0; i < 4; ++i)
7393 if (i != V2Index && (ZMask & (1 << i)) == 0)
7394 InsertShuffleMask[i] = Mask[i];
7396 if (isNoopShuffleMask(InsertShuffleMask)) {
7397 // Replace V1 with undef if nothing from V1 survives the INSERTPS.
7398 if ((ZMask | 1 << V2Index) == 0xF)
7399 V1 = DAG.getUNDEF(MVT::v4f32);
7401 unsigned InsertPSMask = (Mask[V2Index] - 4) << 6 | V2Index << 4 | ZMask;
7402 assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7404 // Insert the V2 element into the desired position.
7405 return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7406 DAG.getConstant(InsertPSMask, MVT::i8));
7410 // Compute the index adjacent to V2Index and in the same half by toggling
7412 int V2AdjIndex = V2Index ^ 1;
7414 if (Mask[V2AdjIndex] == -1) {
7415 // Handles all the cases where we have a single V2 element and an undef.
7416 // This will only ever happen in the high lanes because we commute the
7417 // vector otherwise.
7419 std::swap(LowV, HighV);
7420 NewMask[V2Index] -= 4;
7422 // Handle the case where the V2 element ends up adjacent to a V1 element.
7423 // To make this work, blend them together as the first step.
7424 int V1Index = V2AdjIndex;
7425 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7426 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7427 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7429 // Now proceed to reconstruct the final blend as we have the necessary
7430 // high or low half formed.
7437 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7438 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7440 } else if (NumV2Elements == 2) {
7441 if (Mask[0] < 4 && Mask[1] < 4) {
7442 // Handle the easy case where we have V1 in the low lanes and V2 in the
7443 // high lanes. We never see this reversed because we sort the shuffle.
7447 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7448 // trying to place elements directly, just blend them and set up the final
7449 // shuffle to place them.
7451 // The first two blend mask elements are for V1, the second two are for
7453 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7454 Mask[2] < 4 ? Mask[2] : Mask[3],
7455 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7456 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7457 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7458 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7460 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7463 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7464 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7465 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7466 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7469 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7470 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7473 static SDValue lowerIntegerElementInsertionVectorShuffle(
7474 MVT VT, SDLoc DL, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7475 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7476 int V2Index = std::find_if(Mask.begin(), Mask.end(),
7477 [&Mask](int M) { return M >= (int)Mask.size(); }) -
7480 // Check for a single input from a SCALAR_TO_VECTOR node.
7481 // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7482 // all the smarts here sunk into that routine. However, the current
7483 // lowering of BUILD_VECTOR makes that nearly impossible until the old
7484 // vector shuffle lowering is dead.
7485 if ((Mask[V2Index] == (int)Mask.size() &&
7486 V2.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
7487 V2.getOpcode() == ISD::BUILD_VECTOR) {
7488 SDValue V2S = V2.getOperand(Mask[V2Index] - Mask.size());
7490 bool V1IsAllZero = false;
7491 if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7493 } else if (V1.getOpcode() == ISD::BUILD_VECTOR) {
7495 for (int M : Mask) {
7496 if (M < 0 || M >= (int)Mask.size())
7498 SDValue Input = V1.getOperand(M);
7499 if (Input.getOpcode() != ISD::UNDEF && !X86::isZeroNode(Input)) {
7500 // A non-zero input!
7501 V1IsAllZero = false;
7507 // First, we need to zext the scalar if it is smaller than an i32.
7508 MVT EltVT = VT.getVectorElementType();
7509 assert(EltVT == V2S.getSimpleValueType() &&
7510 "Different scalar and element types!");
7512 if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7513 // Zero-extend directly to i32.
7515 V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7518 V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT,
7519 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S));
7521 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7524 // If we have 4 or fewer lanes we can cheaply shuffle the element into
7525 // the desired position. Otherwise it is more efficient to do a vector
7526 // shift left. We know that we can do a vector shift left because all
7527 // the inputs are zero.
7528 if (VT.getVectorNumElements() <= 4) {
7529 SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7530 V2Shuffle[V2Index] = 0;
7531 V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7533 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7535 X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7537 V2Index * EltVT.getSizeInBits(),
7538 DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7539 V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7548 /// \brief Lower 4-lane i32 vector shuffles.
7550 /// We try to handle these with integer-domain shuffles where we can, but for
7551 /// blends we use the floating point domain blend instructions.
7552 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7553 const X86Subtarget *Subtarget,
7554 SelectionDAG &DAG) {
7556 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7557 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7558 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7559 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7560 ArrayRef<int> Mask = SVOp->getMask();
7561 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7564 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7566 if (NumV2Elements == 0)
7567 // Straight shuffle of a single input vector. For everything from SSE2
7568 // onward this has a single fast instruction with no scary immediates.
7569 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7570 getV4X86ShuffleImm8ForMask(Mask, DAG));
7572 // Use dedicated unpack instructions for masks that match their pattern.
7573 if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7574 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7575 if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7576 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7578 // There are special ways we can lower some single-element blends.
7579 if (NumV2Elements == 1)
7580 if (SDValue V = lowerIntegerElementInsertionVectorShuffle(
7581 MVT::v4i32, DL, V1, V2, Mask, Subtarget, DAG))
7584 // We implement this with SHUFPS because it can blend from two vectors.
7585 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7586 // up the inputs, bypassing domain shift penalties that we would encur if we
7587 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7589 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7590 DAG.getVectorShuffle(
7592 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7593 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7596 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7597 /// shuffle lowering, and the most complex part.
7599 /// The lowering strategy is to try to form pairs of input lanes which are
7600 /// targeted at the same half of the final vector, and then use a dword shuffle
7601 /// to place them onto the right half, and finally unpack the paired lanes into
7602 /// their final position.
7604 /// The exact breakdown of how to form these dword pairs and align them on the
7605 /// correct sides is really tricky. See the comments within the function for
7606 /// more of the details.
7607 static SDValue lowerV8I16SingleInputVectorShuffle(
7608 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7609 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7610 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7611 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7612 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7614 SmallVector<int, 4> LoInputs;
7615 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7616 [](int M) { return M >= 0; });
7617 std::sort(LoInputs.begin(), LoInputs.end());
7618 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7619 SmallVector<int, 4> HiInputs;
7620 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7621 [](int M) { return M >= 0; });
7622 std::sort(HiInputs.begin(), HiInputs.end());
7623 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7625 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7626 int NumHToL = LoInputs.size() - NumLToL;
7628 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7629 int NumHToH = HiInputs.size() - NumLToH;
7630 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7631 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7632 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7633 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7635 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7636 // such inputs we can swap two of the dwords across the half mark and end up
7637 // with <=2 inputs to each half in each half. Once there, we can fall through
7638 // to the generic code below. For example:
7640 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7641 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7643 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7644 // and an existing 2-into-2 on the other half. In this case we may have to
7645 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7646 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7647 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7648 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7649 // half than the one we target for fixing) will be fixed when we re-enter this
7650 // path. We will also combine away any sequence of PSHUFD instructions that
7651 // result into a single instruction. Here is an example of the tricky case:
7653 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7654 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7656 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7658 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7659 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7661 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7662 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7664 // The result is fine to be handled by the generic logic.
7665 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7666 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7667 int AOffset, int BOffset) {
7668 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7669 "Must call this with A having 3 or 1 inputs from the A half.");
7670 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7671 "Must call this with B having 1 or 3 inputs from the B half.");
7672 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7673 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7675 // Compute the index of dword with only one word among the three inputs in
7676 // a half by taking the sum of the half with three inputs and subtracting
7677 // the sum of the actual three inputs. The difference is the remaining
7680 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7681 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7682 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7683 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7684 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7685 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7686 int TripleNonInputIdx =
7687 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7688 TripleDWord = TripleNonInputIdx / 2;
7690 // We use xor with one to compute the adjacent DWord to whichever one the
7692 OneInputDWord = (OneInput / 2) ^ 1;
7694 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7695 // and BToA inputs. If there is also such a problem with the BToB and AToB
7696 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7697 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7698 // is essential that we don't *create* a 3<-1 as then we might oscillate.
7699 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7700 // Compute how many inputs will be flipped by swapping these DWords. We
7702 // to balance this to ensure we don't form a 3-1 shuffle in the other
7704 int NumFlippedAToBInputs =
7705 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7706 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7707 int NumFlippedBToBInputs =
7708 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7709 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7710 if ((NumFlippedAToBInputs == 1 &&
7711 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7712 (NumFlippedBToBInputs == 1 &&
7713 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7714 // We choose whether to fix the A half or B half based on whether that
7715 // half has zero flipped inputs. At zero, we may not be able to fix it
7716 // with that half. We also bias towards fixing the B half because that
7717 // will more commonly be the high half, and we have to bias one way.
7718 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7719 ArrayRef<int> Inputs) {
7720 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7721 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7722 PinnedIdx ^ 1) != Inputs.end();
7723 // Determine whether the free index is in the flipped dword or the
7724 // unflipped dword based on where the pinned index is. We use this bit
7725 // in an xor to conditionally select the adjacent dword.
7726 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7727 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7728 FixFreeIdx) != Inputs.end();
7729 if (IsFixIdxInput == IsFixFreeIdxInput)
7731 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7732 FixFreeIdx) != Inputs.end();
7733 assert(IsFixIdxInput != IsFixFreeIdxInput &&
7734 "We need to be changing the number of flipped inputs!");
7735 int PSHUFHalfMask[] = {0, 1, 2, 3};
7736 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7737 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7739 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7742 if (M != -1 && M == FixIdx)
7744 else if (M != -1 && M == FixFreeIdx)
7747 if (NumFlippedBToBInputs != 0) {
7749 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7750 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7752 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7754 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7755 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7760 int PSHUFDMask[] = {0, 1, 2, 3};
7761 PSHUFDMask[ADWord] = BDWord;
7762 PSHUFDMask[BDWord] = ADWord;
7763 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7764 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7765 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7766 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7768 // Adjust the mask to match the new locations of A and B.
7770 if (M != -1 && M/2 == ADWord)
7771 M = 2 * BDWord + M % 2;
7772 else if (M != -1 && M/2 == BDWord)
7773 M = 2 * ADWord + M % 2;
7775 // Recurse back into this routine to re-compute state now that this isn't
7776 // a 3 and 1 problem.
7777 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7780 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7781 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7782 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7783 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7785 // At this point there are at most two inputs to the low and high halves from
7786 // each half. That means the inputs can always be grouped into dwords and
7787 // those dwords can then be moved to the correct half with a dword shuffle.
7788 // We use at most one low and one high word shuffle to collect these paired
7789 // inputs into dwords, and finally a dword shuffle to place them.
7790 int PSHUFLMask[4] = {-1, -1, -1, -1};
7791 int PSHUFHMask[4] = {-1, -1, -1, -1};
7792 int PSHUFDMask[4] = {-1, -1, -1, -1};
7794 // First fix the masks for all the inputs that are staying in their
7795 // original halves. This will then dictate the targets of the cross-half
7797 auto fixInPlaceInputs =
7798 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7799 MutableArrayRef<int> SourceHalfMask,
7800 MutableArrayRef<int> HalfMask, int HalfOffset) {
7801 if (InPlaceInputs.empty())
7803 if (InPlaceInputs.size() == 1) {
7804 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7805 InPlaceInputs[0] - HalfOffset;
7806 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7809 if (IncomingInputs.empty()) {
7810 // Just fix all of the in place inputs.
7811 for (int Input : InPlaceInputs) {
7812 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7813 PSHUFDMask[Input / 2] = Input / 2;
7818 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7819 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7820 InPlaceInputs[0] - HalfOffset;
7821 // Put the second input next to the first so that they are packed into
7822 // a dword. We find the adjacent index by toggling the low bit.
7823 int AdjIndex = InPlaceInputs[0] ^ 1;
7824 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7825 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7826 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7828 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7829 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7831 // Now gather the cross-half inputs and place them into a free dword of
7832 // their target half.
7833 // FIXME: This operation could almost certainly be simplified dramatically to
7834 // look more like the 3-1 fixing operation.
7835 auto moveInputsToRightHalf = [&PSHUFDMask](
7836 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7837 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7838 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7840 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7841 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7843 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7845 int LowWord = Word & ~1;
7846 int HighWord = Word | 1;
7847 return isWordClobbered(SourceHalfMask, LowWord) ||
7848 isWordClobbered(SourceHalfMask, HighWord);
7851 if (IncomingInputs.empty())
7854 if (ExistingInputs.empty()) {
7855 // Map any dwords with inputs from them into the right half.
7856 for (int Input : IncomingInputs) {
7857 // If the source half mask maps over the inputs, turn those into
7858 // swaps and use the swapped lane.
7859 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7860 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7861 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7862 Input - SourceOffset;
7863 // We have to swap the uses in our half mask in one sweep.
7864 for (int &M : HalfMask)
7865 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7867 else if (M == Input)
7868 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7870 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7871 Input - SourceOffset &&
7872 "Previous placement doesn't match!");
7874 // Note that this correctly re-maps both when we do a swap and when
7875 // we observe the other side of the swap above. We rely on that to
7876 // avoid swapping the members of the input list directly.
7877 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7880 // Map the input's dword into the correct half.
7881 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7882 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7884 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7886 "Previous placement doesn't match!");
7889 // And just directly shift any other-half mask elements to be same-half
7890 // as we will have mirrored the dword containing the element into the
7891 // same position within that half.
7892 for (int &M : HalfMask)
7893 if (M >= SourceOffset && M < SourceOffset + 4) {
7894 M = M - SourceOffset + DestOffset;
7895 assert(M >= 0 && "This should never wrap below zero!");
7900 // Ensure we have the input in a viable dword of its current half. This
7901 // is particularly tricky because the original position may be clobbered
7902 // by inputs being moved and *staying* in that half.
7903 if (IncomingInputs.size() == 1) {
7904 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7905 int InputFixed = std::find(std::begin(SourceHalfMask),
7906 std::end(SourceHalfMask), -1) -
7907 std::begin(SourceHalfMask) + SourceOffset;
7908 SourceHalfMask[InputFixed - SourceOffset] =
7909 IncomingInputs[0] - SourceOffset;
7910 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7912 IncomingInputs[0] = InputFixed;
7914 } else if (IncomingInputs.size() == 2) {
7915 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7916 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7917 // We have two non-adjacent or clobbered inputs we need to extract from
7918 // the source half. To do this, we need to map them into some adjacent
7919 // dword slot in the source mask.
7920 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7921 IncomingInputs[1] - SourceOffset};
7923 // If there is a free slot in the source half mask adjacent to one of
7924 // the inputs, place the other input in it. We use (Index XOR 1) to
7925 // compute an adjacent index.
7926 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7927 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7928 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7929 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7930 InputsFixed[1] = InputsFixed[0] ^ 1;
7931 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7932 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7933 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7934 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7935 InputsFixed[0] = InputsFixed[1] ^ 1;
7936 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7937 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7938 // The two inputs are in the same DWord but it is clobbered and the
7939 // adjacent DWord isn't used at all. Move both inputs to the free
7941 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7942 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
7943 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
7944 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
7946 // The only way we hit this point is if there is no clobbering
7947 // (because there are no off-half inputs to this half) and there is no
7948 // free slot adjacent to one of the inputs. In this case, we have to
7949 // swap an input with a non-input.
7950 for (int i = 0; i < 4; ++i)
7951 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
7952 "We can't handle any clobbers here!");
7953 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
7954 "Cannot have adjacent inputs here!");
7956 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7957 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
7959 // We also have to update the final source mask in this case because
7960 // it may need to undo the above swap.
7961 for (int &M : FinalSourceHalfMask)
7962 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
7963 M = InputsFixed[1] + SourceOffset;
7964 else if (M == InputsFixed[1] + SourceOffset)
7965 M = (InputsFixed[0] ^ 1) + SourceOffset;
7967 InputsFixed[1] = InputsFixed[0] ^ 1;
7970 // Point everything at the fixed inputs.
7971 for (int &M : HalfMask)
7972 if (M == IncomingInputs[0])
7973 M = InputsFixed[0] + SourceOffset;
7974 else if (M == IncomingInputs[1])
7975 M = InputsFixed[1] + SourceOffset;
7977 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
7978 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
7981 llvm_unreachable("Unhandled input size!");
7984 // Now hoist the DWord down to the right half.
7985 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7986 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7987 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7988 for (int &M : HalfMask)
7989 for (int Input : IncomingInputs)
7991 M = FreeDWord * 2 + Input % 2;
7993 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
7994 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7995 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
7996 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7998 // Now enact all the shuffles we've computed to move the inputs into their
8000 if (!isNoopShuffleMask(PSHUFLMask))
8001 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8002 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8003 if (!isNoopShuffleMask(PSHUFHMask))
8004 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8005 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8006 if (!isNoopShuffleMask(PSHUFDMask))
8007 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8008 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8009 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8010 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8012 // At this point, each half should contain all its inputs, and we can then
8013 // just shuffle them into their final position.
8014 assert(std::count_if(LoMask.begin(), LoMask.end(),
8015 [](int M) { return M >= 4; }) == 0 &&
8016 "Failed to lift all the high half inputs to the low mask!");
8017 assert(std::count_if(HiMask.begin(), HiMask.end(),
8018 [](int M) { return M >= 0 && M < 4; }) == 0 &&
8019 "Failed to lift all the low half inputs to the high mask!");
8021 // Do a half shuffle for the low mask.
8022 if (!isNoopShuffleMask(LoMask))
8023 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8024 getV4X86ShuffleImm8ForMask(LoMask, DAG));
8026 // Do a half shuffle with the high mask after shifting its values down.
8027 for (int &M : HiMask)
8030 if (!isNoopShuffleMask(HiMask))
8031 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8032 getV4X86ShuffleImm8ForMask(HiMask, DAG));
8037 /// \brief Detect whether the mask pattern should be lowered through
8040 /// This essentially tests whether viewing the mask as an interleaving of two
8041 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
8042 /// lowering it through interleaving is a significantly better strategy.
8043 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
8044 int NumEvenInputs[2] = {0, 0};
8045 int NumOddInputs[2] = {0, 0};
8046 int NumLoInputs[2] = {0, 0};
8047 int NumHiInputs[2] = {0, 0};
8048 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
8052 int InputIdx = Mask[i] >= Size;
8055 ++NumLoInputs[InputIdx];
8057 ++NumHiInputs[InputIdx];
8060 ++NumEvenInputs[InputIdx];
8062 ++NumOddInputs[InputIdx];
8065 // The minimum number of cross-input results for both the interleaved and
8066 // split cases. If interleaving results in fewer cross-input results, return
8068 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
8069 NumEvenInputs[0] + NumOddInputs[1]);
8070 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
8071 NumLoInputs[0] + NumHiInputs[1]);
8072 return InterleavedCrosses < SplitCrosses;
8075 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
8077 /// This strategy only works when the inputs from each vector fit into a single
8078 /// half of that vector, and generally there are not so many inputs as to leave
8079 /// the in-place shuffles required highly constrained (and thus expensive). It
8080 /// shifts all the inputs into a single side of both input vectors and then
8081 /// uses an unpack to interleave these inputs in a single vector. At that
8082 /// point, we will fall back on the generic single input shuffle lowering.
8083 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
8085 MutableArrayRef<int> Mask,
8086 const X86Subtarget *Subtarget,
8087 SelectionDAG &DAG) {
8088 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8089 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8090 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
8091 for (int i = 0; i < 8; ++i)
8092 if (Mask[i] >= 0 && Mask[i] < 4)
8093 LoV1Inputs.push_back(i);
8094 else if (Mask[i] >= 4 && Mask[i] < 8)
8095 HiV1Inputs.push_back(i);
8096 else if (Mask[i] >= 8 && Mask[i] < 12)
8097 LoV2Inputs.push_back(i);
8098 else if (Mask[i] >= 12)
8099 HiV2Inputs.push_back(i);
8101 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
8102 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
8105 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
8106 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
8107 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
8109 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
8110 HiV1Inputs.size() + HiV2Inputs.size();
8112 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
8113 ArrayRef<int> HiInputs, bool MoveToLo,
8115 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
8116 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
8117 if (BadInputs.empty())
8120 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8121 int MoveOffset = MoveToLo ? 0 : 4;
8123 if (GoodInputs.empty()) {
8124 for (int BadInput : BadInputs) {
8125 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
8126 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
8129 if (GoodInputs.size() == 2) {
8130 // If the low inputs are spread across two dwords, pack them into
8132 MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
8133 MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
8134 Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
8135 Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
8137 // Otherwise pin the good inputs.
8138 for (int GoodInput : GoodInputs)
8139 MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
8142 if (BadInputs.size() == 2) {
8143 // If we have two bad inputs then there may be either one or two good
8144 // inputs fixed in place. Find a fixed input, and then find the *other*
8145 // two adjacent indices by using modular arithmetic.
8147 std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
8148 [](int M) { return M >= 0; }) -
8149 std::begin(MoveMask);
8151 ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
8152 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
8153 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
8154 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8155 MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
8156 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8157 Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
8159 assert(BadInputs.size() == 1 && "All sizes handled");
8160 int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
8161 std::end(MoveMask), -1) -
8162 std::begin(MoveMask);
8163 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8164 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8168 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8171 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
8173 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
8176 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
8177 // cross-half traffic in the final shuffle.
8179 // Munge the mask to be a single-input mask after the unpack merges the
8183 M = 2 * (M % 4) + (M / 8);
8185 return DAG.getVectorShuffle(
8186 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
8187 DL, MVT::v8i16, V1, V2),
8188 DAG.getUNDEF(MVT::v8i16), Mask);
8191 /// \brief Generic lowering of 8-lane i16 shuffles.
8193 /// This handles both single-input shuffles and combined shuffle/blends with
8194 /// two inputs. The single input shuffles are immediately delegated to
8195 /// a dedicated lowering routine.
8197 /// The blends are lowered in one of three fundamental ways. If there are few
8198 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8199 /// of the input is significantly cheaper when lowered as an interleaving of
8200 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8201 /// halves of the inputs separately (making them have relatively few inputs)
8202 /// and then concatenate them.
8203 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8204 const X86Subtarget *Subtarget,
8205 SelectionDAG &DAG) {
8207 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8208 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8209 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8210 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8211 ArrayRef<int> OrigMask = SVOp->getMask();
8212 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8213 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8214 MutableArrayRef<int> Mask(MaskStorage);
8216 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8218 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8219 auto isV2 = [](int M) { return M >= 8; };
8221 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
8222 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8224 if (NumV2Inputs == 0)
8225 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
8227 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
8228 "to be V1-input shuffles.");
8230 // There are special ways we can lower some single-element blends.
8231 if (NumV2Inputs == 1)
8232 if (SDValue V = lowerIntegerElementInsertionVectorShuffle(
8233 MVT::v8i16, DL, V1, V2, Mask, Subtarget, DAG))
8236 if (NumV1Inputs + NumV2Inputs <= 4)
8237 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
8239 // Check whether an interleaving lowering is likely to be more efficient.
8240 // This isn't perfect but it is a strong heuristic that tends to work well on
8241 // the kinds of shuffles that show up in practice.
8243 // FIXME: Handle 1x, 2x, and 4x interleaving.
8244 if (shouldLowerAsInterleaving(Mask)) {
8245 // FIXME: Figure out whether we should pack these into the low or high
8248 int EMask[8], OMask[8];
8249 for (int i = 0; i < 4; ++i) {
8250 EMask[i] = Mask[2*i];
8251 OMask[i] = Mask[2*i + 1];
8256 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
8257 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
8259 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
8262 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8263 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8265 for (int i = 0; i < 4; ++i) {
8266 LoBlendMask[i] = Mask[i];
8267 HiBlendMask[i] = Mask[i + 4];
8270 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8271 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8272 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
8273 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
8275 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8276 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
8279 /// \brief Check whether a compaction lowering can be done by dropping even
8280 /// elements and compute how many times even elements must be dropped.
8282 /// This handles shuffles which take every Nth element where N is a power of
8283 /// two. Example shuffle masks:
8285 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8286 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8287 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8288 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8289 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8290 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8292 /// Any of these lanes can of course be undef.
8294 /// This routine only supports N <= 3.
8295 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8298 /// \returns N above, or the number of times even elements must be dropped if
8299 /// there is such a number. Otherwise returns zero.
8300 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8301 // Figure out whether we're looping over two inputs or just one.
8302 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8304 // The modulus for the shuffle vector entries is based on whether this is
8305 // a single input or not.
8306 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8307 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8308 "We should only be called with masks with a power-of-2 size!");
8310 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8312 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8313 // and 2^3 simultaneously. This is because we may have ambiguity with
8314 // partially undef inputs.
8315 bool ViableForN[3] = {true, true, true};
8317 for (int i = 0, e = Mask.size(); i < e; ++i) {
8318 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8323 bool IsAnyViable = false;
8324 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8325 if (ViableForN[j]) {
8328 // The shuffle mask must be equal to (i * 2^N) % M.
8329 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8332 ViableForN[j] = false;
8334 // Early exit if we exhaust the possible powers of two.
8339 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8343 // Return 0 as there is no viable power of two.
8347 /// \brief Generic lowering of v16i8 shuffles.
8349 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8350 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8351 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8352 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8354 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8355 const X86Subtarget *Subtarget,
8356 SelectionDAG &DAG) {
8358 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8359 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8360 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8361 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8362 ArrayRef<int> OrigMask = SVOp->getMask();
8363 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8364 int MaskStorage[16] = {
8365 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8366 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
8367 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
8368 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
8369 MutableArrayRef<int> Mask(MaskStorage);
8370 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
8371 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
8374 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8376 // For single-input shuffles, there are some nicer lowering tricks we can use.
8377 if (NumV2Elements == 0) {
8378 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8379 // Notably, this handles splat and partial-splat shuffles more efficiently.
8380 // However, it only makes sense if the pre-duplication shuffle simplifies
8381 // things significantly. Currently, this means we need to be able to
8382 // express the pre-duplication shuffle as an i16 shuffle.
8384 // FIXME: We should check for other patterns which can be widened into an
8385 // i16 shuffle as well.
8386 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8387 for (int i = 0; i < 16; i += 2) {
8388 if (Mask[i] != Mask[i + 1])
8393 auto tryToWidenViaDuplication = [&]() -> SDValue {
8394 if (!canWidenViaDuplication(Mask))
8396 SmallVector<int, 4> LoInputs;
8397 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8398 [](int M) { return M >= 0 && M < 8; });
8399 std::sort(LoInputs.begin(), LoInputs.end());
8400 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8402 SmallVector<int, 4> HiInputs;
8403 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8404 [](int M) { return M >= 8; });
8405 std::sort(HiInputs.begin(), HiInputs.end());
8406 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8409 bool TargetLo = LoInputs.size() >= HiInputs.size();
8410 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8411 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8413 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8414 SmallDenseMap<int, int, 8> LaneMap;
8415 for (int I : InPlaceInputs) {
8416 PreDupI16Shuffle[I/2] = I/2;
8419 int j = TargetLo ? 0 : 4, je = j + 4;
8420 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8421 // Check if j is already a shuffle of this input. This happens when
8422 // there are two adjacent bytes after we move the low one.
8423 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8424 // If we haven't yet mapped the input, search for a slot into which
8426 while (j < je && PreDupI16Shuffle[j] != -1)
8430 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8433 // Map this input with the i16 shuffle.
8434 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8437 // Update the lane map based on the mapping we ended up with.
8438 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8441 ISD::BITCAST, DL, MVT::v16i8,
8442 DAG.getVectorShuffle(MVT::v8i16, DL,
8443 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8444 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8446 // Unpack the bytes to form the i16s that will be shuffled into place.
8447 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8448 MVT::v16i8, V1, V1);
8450 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8451 for (int i = 0; i < 16; i += 2) {
8453 PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8454 assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8457 ISD::BITCAST, DL, MVT::v16i8,
8458 DAG.getVectorShuffle(MVT::v8i16, DL,
8459 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8460 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8462 if (SDValue V = tryToWidenViaDuplication())
8466 // Check whether an interleaving lowering is likely to be more efficient.
8467 // This isn't perfect but it is a strong heuristic that tends to work well on
8468 // the kinds of shuffles that show up in practice.
8470 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8471 if (shouldLowerAsInterleaving(Mask)) {
8472 // FIXME: Figure out whether we should pack these into the low or high
8475 int EMask[16], OMask[16];
8476 for (int i = 0; i < 8; ++i) {
8477 EMask[i] = Mask[2*i];
8478 OMask[i] = Mask[2*i + 1];
8483 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8484 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8486 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8489 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8490 // with PSHUFB. It is important to do this before we attempt to generate any
8491 // blends but after all of the single-input lowerings. If the single input
8492 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8493 // want to preserve that and we can DAG combine any longer sequences into
8494 // a PSHUFB in the end. But once we start blending from multiple inputs,
8495 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8496 // and there are *very* few patterns that would actually be faster than the
8497 // PSHUFB approach because of its ability to zero lanes.
8499 // FIXME: The only exceptions to the above are blends which are exact
8500 // interleavings with direct instructions supporting them. We currently don't
8501 // handle those well here.
8502 if (Subtarget->hasSSSE3()) {
8505 for (int i = 0; i < 16; ++i)
8506 if (Mask[i] == -1) {
8507 V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8509 V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8511 DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8513 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8514 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8515 if (isSingleInputShuffleMask(Mask))
8516 return V1; // Single inputs are easy.
8518 // Otherwise, blend the two.
8519 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8520 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8521 return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8524 // There are special ways we can lower some single-element blends.
8525 if (NumV2Elements == 1)
8526 if (SDValue V = lowerIntegerElementInsertionVectorShuffle(
8527 MVT::v16i8, DL, V1, V2, Mask, Subtarget, DAG))
8530 // Check whether a compaction lowering can be done. This handles shuffles
8531 // which take every Nth element for some even N. See the helper function for
8534 // We special case these as they can be particularly efficiently handled with
8535 // the PACKUSB instruction on x86 and they show up in common patterns of
8536 // rearranging bytes to truncate wide elements.
8537 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8538 // NumEvenDrops is the power of two stride of the elements. Another way of
8539 // thinking about it is that we need to drop the even elements this many
8540 // times to get the original input.
8541 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8543 // First we need to zero all the dropped bytes.
8544 assert(NumEvenDrops <= 3 &&
8545 "No support for dropping even elements more than 3 times.");
8546 // We use the mask type to pick which bytes are preserved based on how many
8547 // elements are dropped.
8548 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8549 SDValue ByteClearMask =
8550 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8551 DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8552 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8554 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8556 // Now pack things back together.
8557 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8558 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8559 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8560 for (int i = 1; i < NumEvenDrops; ++i) {
8561 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8562 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8568 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8569 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8570 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8571 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8573 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8574 MutableArrayRef<int> V1HalfBlendMask,
8575 MutableArrayRef<int> V2HalfBlendMask) {
8576 for (int i = 0; i < 8; ++i)
8577 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8578 V1HalfBlendMask[i] = HalfMask[i];
8580 } else if (HalfMask[i] >= 16) {
8581 V2HalfBlendMask[i] = HalfMask[i] - 16;
8582 HalfMask[i] = i + 8;
8585 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8586 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8588 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8590 auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8591 MutableArrayRef<int> HiBlendMask) {
8593 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8594 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8596 if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8597 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8598 std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8599 [](int M) { return M >= 0 && M % 2 == 1; })) {
8600 // Use a mask to drop the high bytes.
8601 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8602 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8603 DAG.getConstant(0x00FF, MVT::v8i16));
8605 // This will be a single vector shuffle instead of a blend so nuke V2.
8606 V2 = DAG.getUNDEF(MVT::v8i16);
8608 // Squash the masks to point directly into V1.
8609 for (int &M : LoBlendMask)
8612 for (int &M : HiBlendMask)
8616 // Otherwise just unpack the low half of V into V1 and the high half into
8617 // V2 so that we can blend them as i16s.
8618 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8619 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8620 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8621 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8624 SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8625 SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8626 return std::make_pair(BlendedLo, BlendedHi);
8628 SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8629 std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8630 std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8632 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8633 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8635 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8638 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8640 /// This routine breaks down the specific type of 128-bit shuffle and
8641 /// dispatches to the lowering routines accordingly.
8642 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8643 MVT VT, const X86Subtarget *Subtarget,
8644 SelectionDAG &DAG) {
8645 switch (VT.SimpleTy) {
8647 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8649 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8651 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8653 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8655 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8657 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8660 llvm_unreachable("Unimplemented!");
8664 static bool isHalfCrossingShuffleMask(ArrayRef<int> Mask) {
8665 int Size = Mask.size();
8666 for (int M : Mask.slice(0, Size / 2))
8667 if (M >= 0 && (M % Size) >= Size / 2)
8669 for (int M : Mask.slice(Size / 2, Size / 2))
8670 if (M >= 0 && (M % Size) < Size / 2)
8675 /// \brief Generic routine to split a 256-bit vector shuffle into 128-bit
8678 /// There is a severely limited set of shuffles available in AVX1 for 256-bit
8679 /// vectors resulting in routinely needing to split the shuffle into two 128-bit
8680 /// shuffles. This can be done generically for any 256-bit vector shuffle and so
8681 /// we encode the logic here for specific shuffle lowering routines to bail to
8682 /// when they exhaust the features avaible to more directly handle the shuffle.
8683 static SDValue splitAndLower256BitVectorShuffle(SDValue Op, SDValue V1,
8685 const X86Subtarget *Subtarget,
8686 SelectionDAG &DAG) {
8688 MVT VT = Op.getSimpleValueType();
8689 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8690 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8691 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8692 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8693 ArrayRef<int> Mask = SVOp->getMask();
8695 ArrayRef<int> LoMask = Mask.slice(0, Mask.size()/2);
8696 ArrayRef<int> HiMask = Mask.slice(Mask.size()/2);
8698 int NumElements = VT.getVectorNumElements();
8699 int SplitNumElements = NumElements / 2;
8700 MVT ScalarVT = VT.getScalarType();
8701 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8703 SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8704 DAG.getIntPtrConstant(0));
8705 SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8706 DAG.getIntPtrConstant(SplitNumElements));
8707 SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8708 DAG.getIntPtrConstant(0));
8709 SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8710 DAG.getIntPtrConstant(SplitNumElements));
8712 // Now create two 4-way blends of these half-width vectors.
8713 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8714 SmallVector<int, 16> V1BlendMask, V2BlendMask, BlendMask;
8715 for (int i = 0; i < SplitNumElements; ++i) {
8716 int M = HalfMask[i];
8717 if (M >= NumElements) {
8718 V2BlendMask.push_back(M - NumElements);
8719 V1BlendMask.push_back(-1);
8720 BlendMask.push_back(SplitNumElements + i);
8721 } else if (M >= 0) {
8722 V2BlendMask.push_back(-1);
8723 V1BlendMask.push_back(M);
8724 BlendMask.push_back(i);
8726 V2BlendMask.push_back(-1);
8727 V1BlendMask.push_back(-1);
8728 BlendMask.push_back(-1);
8731 SDValue V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8732 SDValue V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8733 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8735 SDValue Lo = HalfBlend(LoMask);
8736 SDValue Hi = HalfBlend(HiMask);
8737 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8740 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
8742 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
8743 /// isn't available.
8744 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8745 const X86Subtarget *Subtarget,
8746 SelectionDAG &DAG) {
8748 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8749 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8750 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8751 ArrayRef<int> Mask = SVOp->getMask();
8752 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8754 // FIXME: If we have AVX2, we should delegate to generic code as crossing
8755 // shuffles aren't a problem and FP and int have the same patterns.
8757 // FIXME: We can handle these more cleverly than splitting for v4f64.
8758 if (isHalfCrossingShuffleMask(Mask))
8759 return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8761 if (isSingleInputShuffleMask(Mask)) {
8762 // Non-half-crossing single input shuffles can be lowerid with an
8763 // interleaved permutation.
8764 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
8765 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
8766 return DAG.getNode(X86ISD::VPERMILP, DL, MVT::v4f64, V1,
8767 DAG.getConstant(VPERMILPMask, MVT::i8));
8770 // X86 has dedicated unpack instructions that can handle specific blend
8771 // operations: UNPCKH and UNPCKL.
8772 if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
8773 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
8774 if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
8775 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
8776 // FIXME: It would be nice to find a way to get canonicalization to commute
8778 if (isShuffleEquivalent(Mask, 4, 0, 6, 2))
8779 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
8780 if (isShuffleEquivalent(Mask, 5, 1, 7, 3))
8781 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
8783 // Check if the blend happens to exactly fit that of SHUFPD.
8784 if (Mask[0] < 4 && (Mask[1] == -1 || Mask[1] >= 4) &&
8785 Mask[2] < 4 && (Mask[3] == -1 || Mask[3] >= 4)) {
8786 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
8787 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
8788 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
8789 DAG.getConstant(SHUFPDMask, MVT::i8));
8791 if ((Mask[0] == -1 || Mask[0] >= 4) && Mask[1] < 4 &&
8792 (Mask[2] == -1 || Mask[2] >= 4) && Mask[3] < 4) {
8793 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
8794 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
8795 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
8796 DAG.getConstant(SHUFPDMask, MVT::i8));
8799 // Shuffle the input elements into the desired positions in V1 and V2 and
8800 // blend them together.
8801 int V1Mask[] = {-1, -1, -1, -1};
8802 int V2Mask[] = {-1, -1, -1, -1};
8803 for (int i = 0; i < 4; ++i)
8804 if (Mask[i] >= 0 && Mask[i] < 4)
8805 V1Mask[i] = Mask[i];
8806 else if (Mask[i] >= 4)
8807 V2Mask[i] = Mask[i] - 4;
8809 V1 = DAG.getVectorShuffle(MVT::v4f64, DL, V1, DAG.getUNDEF(MVT::v4f64), V1Mask);
8810 V2 = DAG.getVectorShuffle(MVT::v4f64, DL, V2, DAG.getUNDEF(MVT::v4f64), V2Mask);
8812 unsigned BlendMask = 0;
8813 for (int i = 0; i < 4; ++i)
8815 BlendMask |= 1 << i;
8817 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v4f64, V1, V2,
8818 DAG.getConstant(BlendMask, MVT::i8));
8821 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
8823 /// Largely delegates to common code when we have AVX2 and to the floating-point
8824 /// code when we only have AVX.
8825 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8826 const X86Subtarget *Subtarget,
8827 SelectionDAG &DAG) {
8829 assert(Op.getSimpleValueType() == MVT::v4i64 && "Bad shuffle type!");
8830 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8831 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8832 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8833 ArrayRef<int> Mask = SVOp->getMask();
8834 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8836 // FIXME: If we have AVX2, we should delegate to generic code as crossing
8837 // shuffles aren't a problem and FP and int have the same patterns.
8839 if (isHalfCrossingShuffleMask(Mask))
8840 return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8842 // AVX1 doesn't provide any facilities for v4i64 shuffles, bitcast and
8843 // delegate to floating point code.
8844 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V1);
8845 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V2);
8846 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i64,
8847 lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG));
8850 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
8852 /// This routine either breaks down the specific type of a 256-bit x86 vector
8853 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
8854 /// together based on the available instructions.
8855 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8856 MVT VT, const X86Subtarget *Subtarget,
8857 SelectionDAG &DAG) {
8858 switch (VT.SimpleTy) {
8860 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8862 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8867 // Fall back to the basic pattern of extracting the high half and forming
8869 // FIXME: Add targeted lowering for each type that can document rationale
8870 // for delegating to this when necessary.
8871 return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8874 llvm_unreachable("Not a valid 256-bit x86 vector type!");
8878 /// \brief Tiny helper function to test whether a shuffle mask could be
8879 /// simplified by widening the elements being shuffled.
8880 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
8881 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8882 if (Mask[i] % 2 != 0 || Mask[i] + 1 != Mask[i+1])
8888 /// \brief Top-level lowering for x86 vector shuffles.
8890 /// This handles decomposition, canonicalization, and lowering of all x86
8891 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8892 /// above in helper routines. The canonicalization attempts to widen shuffles
8893 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8894 /// s.t. only one of the two inputs needs to be tested, etc.
8895 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8896 SelectionDAG &DAG) {
8897 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8898 ArrayRef<int> Mask = SVOp->getMask();
8899 SDValue V1 = Op.getOperand(0);
8900 SDValue V2 = Op.getOperand(1);
8901 MVT VT = Op.getSimpleValueType();
8902 int NumElements = VT.getVectorNumElements();
8905 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8907 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8908 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8909 if (V1IsUndef && V2IsUndef)
8910 return DAG.getUNDEF(VT);
8912 // When we create a shuffle node we put the UNDEF node to second operand,
8913 // but in some cases the first operand may be transformed to UNDEF.
8914 // In this case we should just commute the node.
8916 return DAG.getCommutedVectorShuffle(*SVOp);
8918 // Check for non-undef masks pointing at an undef vector and make the masks
8919 // undef as well. This makes it easier to match the shuffle based solely on
8923 if (M >= NumElements) {
8924 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8925 for (int &M : NewMask)
8926 if (M >= NumElements)
8928 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8931 // For integer vector shuffles, try to collapse them into a shuffle of fewer
8932 // lanes but wider integers. We cap this to not form integers larger than i64
8933 // but it might be interesting to form i128 integers to handle flipping the
8934 // low and high halves of AVX 256-bit vectors.
8935 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8936 canWidenShuffleElements(Mask)) {
8937 SmallVector<int, 8> NewMask;
8938 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8939 NewMask.push_back(Mask[i] / 2);
8941 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8942 VT.getVectorNumElements() / 2);
8943 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8944 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8945 return DAG.getNode(ISD::BITCAST, dl, VT,
8946 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8949 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8950 for (int M : SVOp->getMask())
8953 else if (M < NumElements)
8958 // Commute the shuffle as needed such that more elements come from V1 than
8959 // V2. This allows us to match the shuffle pattern strictly on how many
8960 // elements come from V1 without handling the symmetric cases.
8961 if (NumV2Elements > NumV1Elements)
8962 return DAG.getCommutedVectorShuffle(*SVOp);
8964 // When the number of V1 and V2 elements are the same, try to minimize the
8965 // number of uses of V2 in the low half of the vector.
8966 if (NumV1Elements == NumV2Elements) {
8967 int LowV1Elements = 0, LowV2Elements = 0;
8968 for (int M : SVOp->getMask().slice(0, NumElements / 2))
8969 if (M >= NumElements)
8973 if (LowV2Elements > LowV1Elements)
8974 return DAG.getCommutedVectorShuffle(*SVOp);
8977 // For each vector width, delegate to a specialized lowering routine.
8978 if (VT.getSizeInBits() == 128)
8979 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8981 if (VT.getSizeInBits() == 256)
8982 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8984 llvm_unreachable("Unimplemented!");
8988 //===----------------------------------------------------------------------===//
8989 // Legacy vector shuffle lowering
8991 // This code is the legacy code handling vector shuffles until the above
8992 // replaces its functionality and performance.
8993 //===----------------------------------------------------------------------===//
8995 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8996 bool hasInt256, unsigned *MaskOut = nullptr) {
8997 MVT EltVT = VT.getVectorElementType();
8999 // There is no blend with immediate in AVX-512.
9000 if (VT.is512BitVector())
9003 if (!hasSSE41 || EltVT == MVT::i8)
9005 if (!hasInt256 && VT == MVT::v16i16)
9008 unsigned MaskValue = 0;
9009 unsigned NumElems = VT.getVectorNumElements();
9010 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9011 unsigned NumLanes = (NumElems - 1) / 8 + 1;
9012 unsigned NumElemsInLane = NumElems / NumLanes;
9014 // Blend for v16i16 should be symetric for the both lanes.
9015 for (unsigned i = 0; i < NumElemsInLane; ++i) {
9017 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
9018 int EltIdx = MaskVals[i];
9020 if ((EltIdx < 0 || EltIdx == (int)i) &&
9021 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
9024 if (((unsigned)EltIdx == (i + NumElems)) &&
9025 (SndLaneEltIdx < 0 ||
9026 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
9027 MaskValue |= (1 << i);
9033 *MaskOut = MaskValue;
9037 // Try to lower a shuffle node into a simple blend instruction.
9038 // This function assumes isBlendMask returns true for this
9039 // SuffleVectorSDNode
9040 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
9042 const X86Subtarget *Subtarget,
9043 SelectionDAG &DAG) {
9044 MVT VT = SVOp->getSimpleValueType(0);
9045 MVT EltVT = VT.getVectorElementType();
9046 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
9047 Subtarget->hasInt256() && "Trying to lower a "
9048 "VECTOR_SHUFFLE to a Blend but "
9049 "with the wrong mask"));
9050 SDValue V1 = SVOp->getOperand(0);
9051 SDValue V2 = SVOp->getOperand(1);
9053 unsigned NumElems = VT.getVectorNumElements();
9055 // Convert i32 vectors to floating point if it is not AVX2.
9056 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9058 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9059 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9061 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
9062 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
9065 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
9066 DAG.getConstant(MaskValue, MVT::i32));
9067 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9070 /// In vector type \p VT, return true if the element at index \p InputIdx
9071 /// falls on a different 128-bit lane than \p OutputIdx.
9072 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
9073 unsigned OutputIdx) {
9074 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
9075 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
9078 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
9079 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
9080 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
9081 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
9083 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
9084 SelectionDAG &DAG) {
9085 MVT VT = V1.getSimpleValueType();
9086 assert(VT.is128BitVector() || VT.is256BitVector());
9088 MVT EltVT = VT.getVectorElementType();
9089 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
9090 unsigned NumElts = VT.getVectorNumElements();
9092 SmallVector<SDValue, 32> PshufbMask;
9093 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
9094 int InputIdx = MaskVals[OutputIdx];
9095 unsigned InputByteIdx;
9097 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
9098 InputByteIdx = 0x80;
9100 // Cross lane is not allowed.
9101 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
9103 InputByteIdx = InputIdx * EltSizeInBytes;
9104 // Index is an byte offset within the 128-bit lane.
9105 InputByteIdx &= 0xf;
9108 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
9109 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
9110 if (InputByteIdx != 0x80)
9115 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
9117 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
9118 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
9119 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
9122 // v8i16 shuffles - Prefer shuffles in the following order:
9123 // 1. [all] pshuflw, pshufhw, optional move
9124 // 2. [ssse3] 1 x pshufb
9125 // 3. [ssse3] 2 x pshufb + 1 x por
9126 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
9128 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
9129 SelectionDAG &DAG) {
9130 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9131 SDValue V1 = SVOp->getOperand(0);
9132 SDValue V2 = SVOp->getOperand(1);
9134 SmallVector<int, 8> MaskVals;
9136 // Determine if more than 1 of the words in each of the low and high quadwords
9137 // of the result come from the same quadword of one of the two inputs. Undef
9138 // mask values count as coming from any quadword, for better codegen.
9140 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
9141 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
9142 unsigned LoQuad[] = { 0, 0, 0, 0 };
9143 unsigned HiQuad[] = { 0, 0, 0, 0 };
9144 // Indices of quads used.
9145 std::bitset<4> InputQuads;
9146 for (unsigned i = 0; i < 8; ++i) {
9147 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
9148 int EltIdx = SVOp->getMaskElt(i);
9149 MaskVals.push_back(EltIdx);
9158 InputQuads.set(EltIdx / 4);
9161 int BestLoQuad = -1;
9162 unsigned MaxQuad = 1;
9163 for (unsigned i = 0; i < 4; ++i) {
9164 if (LoQuad[i] > MaxQuad) {
9166 MaxQuad = LoQuad[i];
9170 int BestHiQuad = -1;
9172 for (unsigned i = 0; i < 4; ++i) {
9173 if (HiQuad[i] > MaxQuad) {
9175 MaxQuad = HiQuad[i];
9179 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
9180 // of the two input vectors, shuffle them into one input vector so only a
9181 // single pshufb instruction is necessary. If there are more than 2 input
9182 // quads, disable the next transformation since it does not help SSSE3.
9183 bool V1Used = InputQuads[0] || InputQuads[1];
9184 bool V2Used = InputQuads[2] || InputQuads[3];
9185 if (Subtarget->hasSSSE3()) {
9186 if (InputQuads.count() == 2 && V1Used && V2Used) {
9187 BestLoQuad = InputQuads[0] ? 0 : 1;
9188 BestHiQuad = InputQuads[2] ? 2 : 3;
9190 if (InputQuads.count() > 2) {
9196 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
9197 // the shuffle mask. If a quad is scored as -1, that means that it contains
9198 // words from all 4 input quadwords.
9200 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
9202 BestLoQuad < 0 ? 0 : BestLoQuad,
9203 BestHiQuad < 0 ? 1 : BestHiQuad
9205 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
9206 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
9207 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
9208 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
9210 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
9211 // source words for the shuffle, to aid later transformations.
9212 bool AllWordsInNewV = true;
9213 bool InOrder[2] = { true, true };
9214 for (unsigned i = 0; i != 8; ++i) {
9215 int idx = MaskVals[i];
9217 InOrder[i/4] = false;
9218 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
9220 AllWordsInNewV = false;
9224 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
9225 if (AllWordsInNewV) {
9226 for (int i = 0; i != 8; ++i) {
9227 int idx = MaskVals[i];
9230 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
9231 if ((idx != i) && idx < 4)
9233 if ((idx != i) && idx > 3)
9242 // If we've eliminated the use of V2, and the new mask is a pshuflw or
9243 // pshufhw, that's as cheap as it gets. Return the new shuffle.
9244 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
9245 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
9246 unsigned TargetMask = 0;
9247 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
9248 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
9249 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9250 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
9251 getShufflePSHUFLWImmediate(SVOp);
9252 V1 = NewV.getOperand(0);
9253 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
9257 // Promote splats to a larger type which usually leads to more efficient code.
9258 // FIXME: Is this true if pshufb is available?
9259 if (SVOp->isSplat())
9260 return PromoteSplat(SVOp, DAG);
9262 // If we have SSSE3, and all words of the result are from 1 input vector,
9263 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
9264 // is present, fall back to case 4.
9265 if (Subtarget->hasSSSE3()) {
9266 SmallVector<SDValue,16> pshufbMask;
9268 // If we have elements from both input vectors, set the high bit of the
9269 // shuffle mask element to zero out elements that come from V2 in the V1
9270 // mask, and elements that come from V1 in the V2 mask, so that the two
9271 // results can be OR'd together.
9272 bool TwoInputs = V1Used && V2Used;
9273 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
9275 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9277 // Calculate the shuffle mask for the second input, shuffle it, and
9278 // OR it with the first shuffled input.
9279 CommuteVectorShuffleMask(MaskVals, 8);
9280 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
9281 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9282 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9285 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
9286 // and update MaskVals with new element order.
9287 std::bitset<8> InOrder;
9288 if (BestLoQuad >= 0) {
9289 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
9290 for (int i = 0; i != 4; ++i) {
9291 int idx = MaskVals[i];
9294 } else if ((idx / 4) == BestLoQuad) {
9299 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9302 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9303 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9304 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
9306 getShufflePSHUFLWImmediate(SVOp), DAG);
9310 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
9311 // and update MaskVals with the new element order.
9312 if (BestHiQuad >= 0) {
9313 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
9314 for (unsigned i = 4; i != 8; ++i) {
9315 int idx = MaskVals[i];
9318 } else if ((idx / 4) == BestHiQuad) {
9319 MaskV[i] = (idx & 3) + 4;
9323 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9326 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9327 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9328 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
9330 getShufflePSHUFHWImmediate(SVOp), DAG);
9334 // In case BestHi & BestLo were both -1, which means each quadword has a word
9335 // from each of the four input quadwords, calculate the InOrder bitvector now
9336 // before falling through to the insert/extract cleanup.
9337 if (BestLoQuad == -1 && BestHiQuad == -1) {
9339 for (int i = 0; i != 8; ++i)
9340 if (MaskVals[i] < 0 || MaskVals[i] == i)
9344 // The other elements are put in the right place using pextrw and pinsrw.
9345 for (unsigned i = 0; i != 8; ++i) {
9348 int EltIdx = MaskVals[i];
9351 SDValue ExtOp = (EltIdx < 8) ?
9352 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
9353 DAG.getIntPtrConstant(EltIdx)) :
9354 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
9355 DAG.getIntPtrConstant(EltIdx - 8));
9356 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
9357 DAG.getIntPtrConstant(i));
9362 /// \brief v16i16 shuffles
9364 /// FIXME: We only support generation of a single pshufb currently. We can
9365 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
9366 /// well (e.g 2 x pshufb + 1 x por).
9368 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
9369 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9370 SDValue V1 = SVOp->getOperand(0);
9371 SDValue V2 = SVOp->getOperand(1);
9374 if (V2.getOpcode() != ISD::UNDEF)
9377 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9378 return getPSHUFB(MaskVals, V1, dl, DAG);
9381 // v16i8 shuffles - Prefer shuffles in the following order:
9382 // 1. [ssse3] 1 x pshufb
9383 // 2. [ssse3] 2 x pshufb + 1 x por
9384 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
9385 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
9386 const X86Subtarget* Subtarget,
9387 SelectionDAG &DAG) {
9388 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9389 SDValue V1 = SVOp->getOperand(0);
9390 SDValue V2 = SVOp->getOperand(1);
9392 ArrayRef<int> MaskVals = SVOp->getMask();
9394 // Promote splats to a larger type which usually leads to more efficient code.
9395 // FIXME: Is this true if pshufb is available?
9396 if (SVOp->isSplat())
9397 return PromoteSplat(SVOp, DAG);
9399 // If we have SSSE3, case 1 is generated when all result bytes come from
9400 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
9401 // present, fall back to case 3.
9403 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
9404 if (Subtarget->hasSSSE3()) {
9405 SmallVector<SDValue,16> pshufbMask;
9407 // If all result elements are from one input vector, then only translate
9408 // undef mask values to 0x80 (zero out result) in the pshufb mask.
9410 // Otherwise, we have elements from both input vectors, and must zero out
9411 // elements that come from V2 in the first mask, and V1 in the second mask
9412 // so that we can OR them together.
9413 for (unsigned i = 0; i != 16; ++i) {
9414 int EltIdx = MaskVals[i];
9415 if (EltIdx < 0 || EltIdx >= 16)
9417 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9419 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
9420 DAG.getNode(ISD::BUILD_VECTOR, dl,
9421 MVT::v16i8, pshufbMask));
9423 // As PSHUFB will zero elements with negative indices, it's safe to ignore
9424 // the 2nd operand if it's undefined or zero.
9425 if (V2.getOpcode() == ISD::UNDEF ||
9426 ISD::isBuildVectorAllZeros(V2.getNode()))
9429 // Calculate the shuffle mask for the second input, shuffle it, and
9430 // OR it with the first shuffled input.
9432 for (unsigned i = 0; i != 16; ++i) {
9433 int EltIdx = MaskVals[i];
9434 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
9435 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9437 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
9438 DAG.getNode(ISD::BUILD_VECTOR, dl,
9439 MVT::v16i8, pshufbMask));
9440 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9443 // No SSSE3 - Calculate in place words and then fix all out of place words
9444 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
9445 // the 16 different words that comprise the two doublequadword input vectors.
9446 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9447 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9449 for (int i = 0; i != 8; ++i) {
9450 int Elt0 = MaskVals[i*2];
9451 int Elt1 = MaskVals[i*2+1];
9453 // This word of the result is all undef, skip it.
9454 if (Elt0 < 0 && Elt1 < 0)
9457 // This word of the result is already in the correct place, skip it.
9458 if ((Elt0 == i*2) && (Elt1 == i*2+1))
9461 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
9462 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
9465 // If Elt0 and Elt1 are defined, are consecutive, and can be load
9466 // using a single extract together, load it and store it.
9467 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
9468 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9469 DAG.getIntPtrConstant(Elt1 / 2));
9470 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9471 DAG.getIntPtrConstant(i));
9475 // If Elt1 is defined, extract it from the appropriate source. If the
9476 // source byte is not also odd, shift the extracted word left 8 bits
9477 // otherwise clear the bottom 8 bits if we need to do an or.
9479 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9480 DAG.getIntPtrConstant(Elt1 / 2));
9481 if ((Elt1 & 1) == 0)
9482 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
9484 TLI.getShiftAmountTy(InsElt.getValueType())));
9486 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
9487 DAG.getConstant(0xFF00, MVT::i16));
9489 // If Elt0 is defined, extract it from the appropriate source. If the
9490 // source byte is not also even, shift the extracted word right 8 bits. If
9491 // Elt1 was also defined, OR the extracted values together before
9492 // inserting them in the result.
9494 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
9495 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
9496 if ((Elt0 & 1) != 0)
9497 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
9499 TLI.getShiftAmountTy(InsElt0.getValueType())));
9501 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
9502 DAG.getConstant(0x00FF, MVT::i16));
9503 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
9506 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9507 DAG.getIntPtrConstant(i));
9509 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
9512 // v32i8 shuffles - Translate to VPSHUFB if possible.
9514 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
9515 const X86Subtarget *Subtarget,
9516 SelectionDAG &DAG) {
9517 MVT VT = SVOp->getSimpleValueType(0);
9518 SDValue V1 = SVOp->getOperand(0);
9519 SDValue V2 = SVOp->getOperand(1);
9521 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9523 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9524 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
9525 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
9527 // VPSHUFB may be generated if
9528 // (1) one of input vector is undefined or zeroinitializer.
9529 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
9530 // And (2) the mask indexes don't cross the 128-bit lane.
9531 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
9532 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
9535 if (V1IsAllZero && !V2IsAllZero) {
9536 CommuteVectorShuffleMask(MaskVals, 32);
9539 return getPSHUFB(MaskVals, V1, dl, DAG);
9542 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
9543 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
9544 /// done when every pair / quad of shuffle mask elements point to elements in
9545 /// the right sequence. e.g.
9546 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
9548 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
9549 SelectionDAG &DAG) {
9550 MVT VT = SVOp->getSimpleValueType(0);
9552 unsigned NumElems = VT.getVectorNumElements();
9555 switch (VT.SimpleTy) {
9556 default: llvm_unreachable("Unexpected!");
9559 return SDValue(SVOp, 0);
9560 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
9561 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
9562 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
9563 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
9564 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
9565 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
9568 SmallVector<int, 8> MaskVec;
9569 for (unsigned i = 0; i != NumElems; i += Scale) {
9571 for (unsigned j = 0; j != Scale; ++j) {
9572 int EltIdx = SVOp->getMaskElt(i+j);
9576 StartIdx = (EltIdx / Scale);
9577 if (EltIdx != (int)(StartIdx*Scale + j))
9580 MaskVec.push_back(StartIdx);
9583 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
9584 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
9585 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
9588 /// getVZextMovL - Return a zero-extending vector move low node.
9590 static SDValue getVZextMovL(MVT VT, MVT OpVT,
9591 SDValue SrcOp, SelectionDAG &DAG,
9592 const X86Subtarget *Subtarget, SDLoc dl) {
9593 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
9594 LoadSDNode *LD = nullptr;
9595 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
9596 LD = dyn_cast<LoadSDNode>(SrcOp);
9598 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
9600 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
9601 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
9602 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9603 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
9604 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
9606 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
9607 return DAG.getNode(ISD::BITCAST, dl, VT,
9608 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9609 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9617 return DAG.getNode(ISD::BITCAST, dl, VT,
9618 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9619 DAG.getNode(ISD::BITCAST, dl,
9623 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
9624 /// which could not be matched by any known target speficic shuffle
9626 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9628 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
9629 if (NewOp.getNode())
9632 MVT VT = SVOp->getSimpleValueType(0);
9634 unsigned NumElems = VT.getVectorNumElements();
9635 unsigned NumLaneElems = NumElems / 2;
9638 MVT EltVT = VT.getVectorElementType();
9639 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
9642 SmallVector<int, 16> Mask;
9643 for (unsigned l = 0; l < 2; ++l) {
9644 // Build a shuffle mask for the output, discovering on the fly which
9645 // input vectors to use as shuffle operands (recorded in InputUsed).
9646 // If building a suitable shuffle vector proves too hard, then bail
9647 // out with UseBuildVector set.
9648 bool UseBuildVector = false;
9649 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9650 unsigned LaneStart = l * NumLaneElems;
9651 for (unsigned i = 0; i != NumLaneElems; ++i) {
9652 // The mask element. This indexes into the input.
9653 int Idx = SVOp->getMaskElt(i+LaneStart);
9655 // the mask element does not index into any input vector.
9660 // The input vector this mask element indexes into.
9661 int Input = Idx / NumLaneElems;
9663 // Turn the index into an offset from the start of the input vector.
9664 Idx -= Input * NumLaneElems;
9666 // Find or create a shuffle vector operand to hold this input.
9668 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9669 if (InputUsed[OpNo] == Input)
9670 // This input vector is already an operand.
9672 if (InputUsed[OpNo] < 0) {
9673 // Create a new operand for this input vector.
9674 InputUsed[OpNo] = Input;
9679 if (OpNo >= array_lengthof(InputUsed)) {
9680 // More than two input vectors used! Give up on trying to create a
9681 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
9682 UseBuildVector = true;
9686 // Add the mask index for the new shuffle vector.
9687 Mask.push_back(Idx + OpNo * NumLaneElems);
9690 if (UseBuildVector) {
9691 SmallVector<SDValue, 16> SVOps;
9692 for (unsigned i = 0; i != NumLaneElems; ++i) {
9693 // The mask element. This indexes into the input.
9694 int Idx = SVOp->getMaskElt(i+LaneStart);
9696 SVOps.push_back(DAG.getUNDEF(EltVT));
9700 // The input vector this mask element indexes into.
9701 int Input = Idx / NumElems;
9703 // Turn the index into an offset from the start of the input vector.
9704 Idx -= Input * NumElems;
9706 // Extract the vector element by hand.
9707 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9708 SVOp->getOperand(Input),
9709 DAG.getIntPtrConstant(Idx)));
9712 // Construct the output using a BUILD_VECTOR.
9713 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9714 } else if (InputUsed[0] < 0) {
9715 // No input vectors were used! The result is undefined.
9716 Output[l] = DAG.getUNDEF(NVT);
9718 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9719 (InputUsed[0] % 2) * NumLaneElems,
9721 // If only one input was used, use an undefined vector for the other.
9722 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9723 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9724 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9725 // At least one input vector was used. Create a new shuffle vector.
9726 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9732 // Concatenate the result back
9733 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9736 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9737 /// 4 elements, and match them with several different shuffle types.
9739 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9740 SDValue V1 = SVOp->getOperand(0);
9741 SDValue V2 = SVOp->getOperand(1);
9743 MVT VT = SVOp->getSimpleValueType(0);
9745 assert(VT.is128BitVector() && "Unsupported vector size");
9747 std::pair<int, int> Locs[4];
9748 int Mask1[] = { -1, -1, -1, -1 };
9749 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9753 for (unsigned i = 0; i != 4; ++i) {
9754 int Idx = PermMask[i];
9756 Locs[i] = std::make_pair(-1, -1);
9758 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9760 Locs[i] = std::make_pair(0, NumLo);
9764 Locs[i] = std::make_pair(1, NumHi);
9766 Mask1[2+NumHi] = Idx;
9772 if (NumLo <= 2 && NumHi <= 2) {
9773 // If no more than two elements come from either vector. This can be
9774 // implemented with two shuffles. First shuffle gather the elements.
9775 // The second shuffle, which takes the first shuffle as both of its
9776 // vector operands, put the elements into the right order.
9777 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9779 int Mask2[] = { -1, -1, -1, -1 };
9781 for (unsigned i = 0; i != 4; ++i)
9782 if (Locs[i].first != -1) {
9783 unsigned Idx = (i < 2) ? 0 : 4;
9784 Idx += Locs[i].first * 2 + Locs[i].second;
9788 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9791 if (NumLo == 3 || NumHi == 3) {
9792 // Otherwise, we must have three elements from one vector, call it X, and
9793 // one element from the other, call it Y. First, use a shufps to build an
9794 // intermediate vector with the one element from Y and the element from X
9795 // that will be in the same half in the final destination (the indexes don't
9796 // matter). Then, use a shufps to build the final vector, taking the half
9797 // containing the element from Y from the intermediate, and the other half
9800 // Normalize it so the 3 elements come from V1.
9801 CommuteVectorShuffleMask(PermMask, 4);
9805 // Find the element from V2.
9807 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9808 int Val = PermMask[HiIndex];
9815 Mask1[0] = PermMask[HiIndex];
9817 Mask1[2] = PermMask[HiIndex^1];
9819 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9822 Mask1[0] = PermMask[0];
9823 Mask1[1] = PermMask[1];
9824 Mask1[2] = HiIndex & 1 ? 6 : 4;
9825 Mask1[3] = HiIndex & 1 ? 4 : 6;
9826 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9829 Mask1[0] = HiIndex & 1 ? 2 : 0;
9830 Mask1[1] = HiIndex & 1 ? 0 : 2;
9831 Mask1[2] = PermMask[2];
9832 Mask1[3] = PermMask[3];
9837 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9840 // Break it into (shuffle shuffle_hi, shuffle_lo).
9841 int LoMask[] = { -1, -1, -1, -1 };
9842 int HiMask[] = { -1, -1, -1, -1 };
9844 int *MaskPtr = LoMask;
9845 unsigned MaskIdx = 0;
9848 for (unsigned i = 0; i != 4; ++i) {
9855 int Idx = PermMask[i];
9857 Locs[i] = std::make_pair(-1, -1);
9858 } else if (Idx < 4) {
9859 Locs[i] = std::make_pair(MaskIdx, LoIdx);
9860 MaskPtr[LoIdx] = Idx;
9863 Locs[i] = std::make_pair(MaskIdx, HiIdx);
9864 MaskPtr[HiIdx] = Idx;
9869 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9870 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9871 int MaskOps[] = { -1, -1, -1, -1 };
9872 for (unsigned i = 0; i != 4; ++i)
9873 if (Locs[i].first != -1)
9874 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9875 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9878 static bool MayFoldVectorLoad(SDValue V) {
9879 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9880 V = V.getOperand(0);
9882 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9883 V = V.getOperand(0);
9884 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9885 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9886 // BUILD_VECTOR (load), undef
9887 V = V.getOperand(0);
9889 return MayFoldLoad(V);
9893 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9894 MVT VT = Op.getSimpleValueType();
9896 // Canonizalize to v2f64.
9897 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9898 return DAG.getNode(ISD::BITCAST, dl, VT,
9899 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9904 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9906 SDValue V1 = Op.getOperand(0);
9907 SDValue V2 = Op.getOperand(1);
9908 MVT VT = Op.getSimpleValueType();
9910 assert(VT != MVT::v2i64 && "unsupported shuffle type");
9912 if (HasSSE2 && VT == MVT::v2f64)
9913 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9915 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9916 return DAG.getNode(ISD::BITCAST, dl, VT,
9917 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9918 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9919 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9923 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9924 SDValue V1 = Op.getOperand(0);
9925 SDValue V2 = Op.getOperand(1);
9926 MVT VT = Op.getSimpleValueType();
9928 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9929 "unsupported shuffle type");
9931 if (V2.getOpcode() == ISD::UNDEF)
9935 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9939 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9940 SDValue V1 = Op.getOperand(0);
9941 SDValue V2 = Op.getOperand(1);
9942 MVT VT = Op.getSimpleValueType();
9943 unsigned NumElems = VT.getVectorNumElements();
9945 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9946 // operand of these instructions is only memory, so check if there's a
9947 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9949 bool CanFoldLoad = false;
9951 // Trivial case, when V2 comes from a load.
9952 if (MayFoldVectorLoad(V2))
9955 // When V1 is a load, it can be folded later into a store in isel, example:
9956 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9958 // (MOVLPSmr addr:$src1, VR128:$src2)
9959 // So, recognize this potential and also use MOVLPS or MOVLPD
9960 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9963 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9965 if (HasSSE2 && NumElems == 2)
9966 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9969 // If we don't care about the second element, proceed to use movss.
9970 if (SVOp->getMaskElt(1) != -1)
9971 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9974 // movl and movlp will both match v2i64, but v2i64 is never matched by
9975 // movl earlier because we make it strict to avoid messing with the movlp load
9976 // folding logic (see the code above getMOVLP call). Match it here then,
9977 // this is horrible, but will stay like this until we move all shuffle
9978 // matching to x86 specific nodes. Note that for the 1st condition all
9979 // types are matched with movsd.
9981 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9982 // as to remove this logic from here, as much as possible
9983 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9984 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9985 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9988 assert(VT != MVT::v4i32 && "unsupported shuffle type");
9990 // Invert the operand order and use SHUFPS to match it.
9991 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9992 getShuffleSHUFImmediate(SVOp), DAG);
9995 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9996 SelectionDAG &DAG) {
9998 MVT VT = Load->getSimpleValueType(0);
9999 MVT EVT = VT.getVectorElementType();
10000 SDValue Addr = Load->getOperand(1);
10001 SDValue NewAddr = DAG.getNode(
10002 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
10003 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
10006 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
10007 DAG.getMachineFunction().getMachineMemOperand(
10008 Load->getMemOperand(), 0, EVT.getStoreSize()));
10012 // It is only safe to call this function if isINSERTPSMask is true for
10013 // this shufflevector mask.
10014 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
10015 SelectionDAG &DAG) {
10016 // Generate an insertps instruction when inserting an f32 from memory onto a
10017 // v4f32 or when copying a member from one v4f32 to another.
10018 // We also use it for transferring i32 from one register to another,
10019 // since it simply copies the same bits.
10020 // If we're transferring an i32 from memory to a specific element in a
10021 // register, we output a generic DAG that will match the PINSRD
10023 MVT VT = SVOp->getSimpleValueType(0);
10024 MVT EVT = VT.getVectorElementType();
10025 SDValue V1 = SVOp->getOperand(0);
10026 SDValue V2 = SVOp->getOperand(1);
10027 auto Mask = SVOp->getMask();
10028 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
10029 "unsupported vector type for insertps/pinsrd");
10031 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
10032 auto FromV2Predicate = [](const int &i) { return i >= 4; };
10033 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
10037 unsigned DestIndex;
10041 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
10044 // If we have 1 element from each vector, we have to check if we're
10045 // changing V1's element's place. If so, we're done. Otherwise, we
10046 // should assume we're changing V2's element's place and behave
10048 int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
10049 assert(DestIndex <= INT32_MAX && "truncated destination index");
10050 if (FromV1 == FromV2 &&
10051 static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
10055 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
10058 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
10059 "More than one element from V1 and from V2, or no elements from one "
10060 "of the vectors. This case should not have returned true from "
10065 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
10068 // Get an index into the source vector in the range [0,4) (the mask is
10069 // in the range [0,8) because it can address V1 and V2)
10070 unsigned SrcIndex = Mask[DestIndex] % 4;
10071 if (MayFoldLoad(From)) {
10072 // Trivial case, when From comes from a load and is only used by the
10073 // shuffle. Make it use insertps from the vector that we need from that
10076 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
10077 if (!NewLoad.getNode())
10080 if (EVT == MVT::f32) {
10081 // Create this as a scalar to vector to match the instruction pattern.
10082 SDValue LoadScalarToVector =
10083 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
10084 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
10085 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
10087 } else { // EVT == MVT::i32
10088 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
10089 // instruction, to match the PINSRD instruction, which loads an i32 to a
10090 // certain vector element.
10091 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
10092 DAG.getConstant(DestIndex, MVT::i32));
10096 // Vector-element-to-vector
10097 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
10098 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
10101 // Reduce a vector shuffle to zext.
10102 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
10103 SelectionDAG &DAG) {
10104 // PMOVZX is only available from SSE41.
10105 if (!Subtarget->hasSSE41())
10108 MVT VT = Op.getSimpleValueType();
10110 // Only AVX2 support 256-bit vector integer extending.
10111 if (!Subtarget->hasInt256() && VT.is256BitVector())
10114 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10116 SDValue V1 = Op.getOperand(0);
10117 SDValue V2 = Op.getOperand(1);
10118 unsigned NumElems = VT.getVectorNumElements();
10120 // Extending is an unary operation and the element type of the source vector
10121 // won't be equal to or larger than i64.
10122 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
10123 VT.getVectorElementType() == MVT::i64)
10126 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
10127 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
10128 while ((1U << Shift) < NumElems) {
10129 if (SVOp->getMaskElt(1U << Shift) == 1)
10132 // The maximal ratio is 8, i.e. from i8 to i64.
10137 // Check the shuffle mask.
10138 unsigned Mask = (1U << Shift) - 1;
10139 for (unsigned i = 0; i != NumElems; ++i) {
10140 int EltIdx = SVOp->getMaskElt(i);
10141 if ((i & Mask) != 0 && EltIdx != -1)
10143 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
10147 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
10148 MVT NeVT = MVT::getIntegerVT(NBits);
10149 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
10151 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
10154 // Simplify the operand as it's prepared to be fed into shuffle.
10155 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
10156 if (V1.getOpcode() == ISD::BITCAST &&
10157 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
10158 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
10159 V1.getOperand(0).getOperand(0)
10160 .getSimpleValueType().getSizeInBits() == SignificantBits) {
10161 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
10162 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
10163 ConstantSDNode *CIdx =
10164 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
10165 // If it's foldable, i.e. normal load with single use, we will let code
10166 // selection to fold it. Otherwise, we will short the conversion sequence.
10167 if (CIdx && CIdx->getZExtValue() == 0 &&
10168 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
10169 MVT FullVT = V.getSimpleValueType();
10170 MVT V1VT = V1.getSimpleValueType();
10171 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
10172 // The "ext_vec_elt" node is wider than the result node.
10173 // In this case we should extract subvector from V.
10174 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
10175 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
10176 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
10177 FullVT.getVectorNumElements()/Ratio);
10178 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
10179 DAG.getIntPtrConstant(0));
10181 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
10185 return DAG.getNode(ISD::BITCAST, DL, VT,
10186 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
10189 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10190 SelectionDAG &DAG) {
10191 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10192 MVT VT = Op.getSimpleValueType();
10194 SDValue V1 = Op.getOperand(0);
10195 SDValue V2 = Op.getOperand(1);
10197 if (isZeroShuffle(SVOp))
10198 return getZeroVector(VT, Subtarget, DAG, dl);
10200 // Handle splat operations
10201 if (SVOp->isSplat()) {
10202 // Use vbroadcast whenever the splat comes from a foldable load
10203 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
10204 if (Broadcast.getNode())
10208 // Check integer expanding shuffles.
10209 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
10210 if (NewOp.getNode())
10213 // If the shuffle can be profitably rewritten as a narrower shuffle, then
10215 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
10216 VT == MVT::v32i8) {
10217 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10218 if (NewOp.getNode())
10219 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
10220 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
10221 // FIXME: Figure out a cleaner way to do this.
10222 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
10223 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10224 if (NewOp.getNode()) {
10225 MVT NewVT = NewOp.getSimpleValueType();
10226 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
10227 NewVT, true, false))
10228 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
10231 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
10232 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10233 if (NewOp.getNode()) {
10234 MVT NewVT = NewOp.getSimpleValueType();
10235 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
10236 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
10245 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
10246 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10247 SDValue V1 = Op.getOperand(0);
10248 SDValue V2 = Op.getOperand(1);
10249 MVT VT = Op.getSimpleValueType();
10251 unsigned NumElems = VT.getVectorNumElements();
10252 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10253 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10254 bool V1IsSplat = false;
10255 bool V2IsSplat = false;
10256 bool HasSSE2 = Subtarget->hasSSE2();
10257 bool HasFp256 = Subtarget->hasFp256();
10258 bool HasInt256 = Subtarget->hasInt256();
10259 MachineFunction &MF = DAG.getMachineFunction();
10260 bool OptForSize = MF.getFunction()->getAttributes().
10261 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
10263 // Check if we should use the experimental vector shuffle lowering. If so,
10264 // delegate completely to that code path.
10265 if (ExperimentalVectorShuffleLowering)
10266 return lowerVectorShuffle(Op, Subtarget, DAG);
10268 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10270 if (V1IsUndef && V2IsUndef)
10271 return DAG.getUNDEF(VT);
10273 // When we create a shuffle node we put the UNDEF node to second operand,
10274 // but in some cases the first operand may be transformed to UNDEF.
10275 // In this case we should just commute the node.
10277 return DAG.getCommutedVectorShuffle(*SVOp);
10279 // Vector shuffle lowering takes 3 steps:
10281 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
10282 // narrowing and commutation of operands should be handled.
10283 // 2) Matching of shuffles with known shuffle masks to x86 target specific
10285 // 3) Rewriting of unmatched masks into new generic shuffle operations,
10286 // so the shuffle can be broken into other shuffles and the legalizer can
10287 // try the lowering again.
10289 // The general idea is that no vector_shuffle operation should be left to
10290 // be matched during isel, all of them must be converted to a target specific
10293 // Normalize the input vectors. Here splats, zeroed vectors, profitable
10294 // narrowing and commutation of operands should be handled. The actual code
10295 // doesn't include all of those, work in progress...
10296 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
10297 if (NewOp.getNode())
10300 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
10302 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
10303 // unpckh_undef). Only use pshufd if speed is more important than size.
10304 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10305 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10306 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10307 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10309 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
10310 V2IsUndef && MayFoldVectorLoad(V1))
10311 return getMOVDDup(Op, dl, V1, DAG);
10313 if (isMOVHLPS_v_undef_Mask(M, VT))
10314 return getMOVHighToLow(Op, dl, DAG);
10316 // Use to match splats
10317 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
10318 (VT == MVT::v2f64 || VT == MVT::v2i64))
10319 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10321 if (isPSHUFDMask(M, VT)) {
10322 // The actual implementation will match the mask in the if above and then
10323 // during isel it can match several different instructions, not only pshufd
10324 // as its name says, sad but true, emulate the behavior for now...
10325 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
10326 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
10328 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
10330 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
10331 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
10333 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
10334 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
10337 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
10341 if (isPALIGNRMask(M, VT, Subtarget))
10342 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
10343 getShufflePALIGNRImmediate(SVOp),
10346 if (isVALIGNMask(M, VT, Subtarget))
10347 return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
10348 getShuffleVALIGNImmediate(SVOp),
10351 // Check if this can be converted into a logical shift.
10352 bool isLeft = false;
10353 unsigned ShAmt = 0;
10355 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
10356 if (isShift && ShVal.hasOneUse()) {
10357 // If the shifted value has multiple uses, it may be cheaper to use
10358 // v_set0 + movlhps or movhlps, etc.
10359 MVT EltVT = VT.getVectorElementType();
10360 ShAmt *= EltVT.getSizeInBits();
10361 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10364 if (isMOVLMask(M, VT)) {
10365 if (ISD::isBuildVectorAllZeros(V1.getNode()))
10366 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
10367 if (!isMOVLPMask(M, VT)) {
10368 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
10369 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10371 if (VT == MVT::v4i32 || VT == MVT::v4f32)
10372 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10376 // FIXME: fold these into legal mask.
10377 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
10378 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
10380 if (isMOVHLPSMask(M, VT))
10381 return getMOVHighToLow(Op, dl, DAG);
10383 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
10384 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
10386 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
10387 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
10389 if (isMOVLPMask(M, VT))
10390 return getMOVLP(Op, dl, DAG, HasSSE2);
10392 if (ShouldXformToMOVHLPS(M, VT) ||
10393 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
10394 return DAG.getCommutedVectorShuffle(*SVOp);
10397 // No better options. Use a vshldq / vsrldq.
10398 MVT EltVT = VT.getVectorElementType();
10399 ShAmt *= EltVT.getSizeInBits();
10400 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10403 bool Commuted = false;
10404 // FIXME: This should also accept a bitcast of a splat? Be careful, not
10405 // 1,1,1,1 -> v8i16 though.
10406 BitVector UndefElements;
10407 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
10408 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10410 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
10411 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10414 // Canonicalize the splat or undef, if present, to be on the RHS.
10415 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
10416 CommuteVectorShuffleMask(M, NumElems);
10418 std::swap(V1IsSplat, V2IsSplat);
10422 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
10423 // Shuffling low element of v1 into undef, just return v1.
10426 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
10427 // the instruction selector will not match, so get a canonical MOVL with
10428 // swapped operands to undo the commute.
10429 return getMOVL(DAG, dl, VT, V2, V1);
10432 if (isUNPCKLMask(M, VT, HasInt256))
10433 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10435 if (isUNPCKHMask(M, VT, HasInt256))
10436 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10439 // Normalize mask so all entries that point to V2 points to its first
10440 // element then try to match unpck{h|l} again. If match, return a
10441 // new vector_shuffle with the corrected mask.p
10442 SmallVector<int, 8> NewMask(M.begin(), M.end());
10443 NormalizeMask(NewMask, NumElems);
10444 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
10445 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10446 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
10447 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10451 // Commute is back and try unpck* again.
10452 // FIXME: this seems wrong.
10453 CommuteVectorShuffleMask(M, NumElems);
10455 std::swap(V1IsSplat, V2IsSplat);
10457 if (isUNPCKLMask(M, VT, HasInt256))
10458 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10460 if (isUNPCKHMask(M, VT, HasInt256))
10461 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10464 // Normalize the node to match x86 shuffle ops if needed
10465 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
10466 return DAG.getCommutedVectorShuffle(*SVOp);
10468 // The checks below are all present in isShuffleMaskLegal, but they are
10469 // inlined here right now to enable us to directly emit target specific
10470 // nodes, and remove one by one until they don't return Op anymore.
10472 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
10473 SVOp->getSplatIndex() == 0 && V2IsUndef) {
10474 if (VT == MVT::v2f64 || VT == MVT::v2i64)
10475 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10478 if (isPSHUFHWMask(M, VT, HasInt256))
10479 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
10480 getShufflePSHUFHWImmediate(SVOp),
10483 if (isPSHUFLWMask(M, VT, HasInt256))
10484 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
10485 getShufflePSHUFLWImmediate(SVOp),
10488 unsigned MaskValue;
10489 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
10491 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
10493 if (isSHUFPMask(M, VT))
10494 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
10495 getShuffleSHUFImmediate(SVOp), DAG);
10497 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10498 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10499 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10500 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10502 //===--------------------------------------------------------------------===//
10503 // Generate target specific nodes for 128 or 256-bit shuffles only
10504 // supported in the AVX instruction set.
10507 // Handle VMOVDDUPY permutations
10508 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
10509 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
10511 // Handle VPERMILPS/D* permutations
10512 if (isVPERMILPMask(M, VT)) {
10513 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
10514 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
10515 getShuffleSHUFImmediate(SVOp), DAG);
10516 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
10517 getShuffleSHUFImmediate(SVOp), DAG);
10521 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
10522 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
10523 Idx*(NumElems/2), DAG, dl);
10525 // Handle VPERM2F128/VPERM2I128 permutations
10526 if (isVPERM2X128Mask(M, VT, HasFp256))
10527 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
10528 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
10530 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
10531 return getINSERTPS(SVOp, dl, DAG);
10534 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
10535 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
10537 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
10538 VT.is512BitVector()) {
10539 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
10540 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
10541 SmallVector<SDValue, 16> permclMask;
10542 for (unsigned i = 0; i != NumElems; ++i) {
10543 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
10546 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
10548 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
10549 return DAG.getNode(X86ISD::VPERMV, dl, VT,
10550 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
10551 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
10552 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
10555 //===--------------------------------------------------------------------===//
10556 // Since no target specific shuffle was selected for this generic one,
10557 // lower it into other known shuffles. FIXME: this isn't true yet, but
10558 // this is the plan.
10561 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
10562 if (VT == MVT::v8i16) {
10563 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
10564 if (NewOp.getNode())
10568 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
10569 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
10570 if (NewOp.getNode())
10574 if (VT == MVT::v16i8) {
10575 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
10576 if (NewOp.getNode())
10580 if (VT == MVT::v32i8) {
10581 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
10582 if (NewOp.getNode())
10586 // Handle all 128-bit wide vectors with 4 elements, and match them with
10587 // several different shuffle types.
10588 if (NumElems == 4 && VT.is128BitVector())
10589 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
10591 // Handle general 256-bit shuffles
10592 if (VT.is256BitVector())
10593 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
10598 // This function assumes its argument is a BUILD_VECTOR of constants or
10599 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10601 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10602 unsigned &MaskValue) {
10604 unsigned NumElems = BuildVector->getNumOperands();
10605 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10606 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10607 unsigned NumElemsInLane = NumElems / NumLanes;
10609 // Blend for v16i16 should be symetric for the both lanes.
10610 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10611 SDValue EltCond = BuildVector->getOperand(i);
10612 SDValue SndLaneEltCond =
10613 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10615 int Lane1Cond = -1, Lane2Cond = -1;
10616 if (isa<ConstantSDNode>(EltCond))
10617 Lane1Cond = !isZero(EltCond);
10618 if (isa<ConstantSDNode>(SndLaneEltCond))
10619 Lane2Cond = !isZero(SndLaneEltCond);
10621 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10622 // Lane1Cond != 0, means we want the first argument.
10623 // Lane1Cond == 0, means we want the second argument.
10624 // The encoding of this argument is 0 for the first argument, 1
10625 // for the second. Therefore, invert the condition.
10626 MaskValue |= !Lane1Cond << i;
10627 else if (Lane1Cond < 0)
10628 MaskValue |= !Lane2Cond << i;
10635 // Try to lower a vselect node into a simple blend instruction.
10636 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
10637 SelectionDAG &DAG) {
10638 SDValue Cond = Op.getOperand(0);
10639 SDValue LHS = Op.getOperand(1);
10640 SDValue RHS = Op.getOperand(2);
10642 MVT VT = Op.getSimpleValueType();
10643 MVT EltVT = VT.getVectorElementType();
10644 unsigned NumElems = VT.getVectorNumElements();
10646 // There is no blend with immediate in AVX-512.
10647 if (VT.is512BitVector())
10650 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10652 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10655 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10658 // Check the mask for BLEND and build the value.
10659 unsigned MaskValue = 0;
10660 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10663 // Convert i32 vectors to floating point if it is not AVX2.
10664 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10666 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10667 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10669 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10670 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10673 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10674 DAG.getConstant(MaskValue, MVT::i32));
10675 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10678 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10679 // A vselect where all conditions and data are constants can be optimized into
10680 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10681 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10682 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10683 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10686 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10687 if (BlendOp.getNode())
10690 // Some types for vselect were previously set to Expand, not Legal or
10691 // Custom. Return an empty SDValue so we fall-through to Expand, after
10692 // the Custom lowering phase.
10693 MVT VT = Op.getSimpleValueType();
10694 switch (VT.SimpleTy) {
10699 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10704 // We couldn't create a "Blend with immediate" node.
10705 // This node should still be legal, but we'll have to emit a blendv*
10710 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10711 MVT VT = Op.getSimpleValueType();
10714 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10717 if (VT.getSizeInBits() == 8) {
10718 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10719 Op.getOperand(0), Op.getOperand(1));
10720 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10721 DAG.getValueType(VT));
10722 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10725 if (VT.getSizeInBits() == 16) {
10726 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10727 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10729 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10730 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10731 DAG.getNode(ISD::BITCAST, dl,
10734 Op.getOperand(1)));
10735 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10736 Op.getOperand(0), Op.getOperand(1));
10737 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10738 DAG.getValueType(VT));
10739 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10742 if (VT == MVT::f32) {
10743 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10744 // the result back to FR32 register. It's only worth matching if the
10745 // result has a single use which is a store or a bitcast to i32. And in
10746 // the case of a store, it's not worth it if the index is a constant 0,
10747 // because a MOVSSmr can be used instead, which is smaller and faster.
10748 if (!Op.hasOneUse())
10750 SDNode *User = *Op.getNode()->use_begin();
10751 if ((User->getOpcode() != ISD::STORE ||
10752 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10753 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10754 (User->getOpcode() != ISD::BITCAST ||
10755 User->getValueType(0) != MVT::i32))
10757 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10758 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10761 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10764 if (VT == MVT::i32 || VT == MVT::i64) {
10765 // ExtractPS/pextrq works with constant index.
10766 if (isa<ConstantSDNode>(Op.getOperand(1)))
10772 /// Extract one bit from mask vector, like v16i1 or v8i1.
10773 /// AVX-512 feature.
10775 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10776 SDValue Vec = Op.getOperand(0);
10778 MVT VecVT = Vec.getSimpleValueType();
10779 SDValue Idx = Op.getOperand(1);
10780 MVT EltVT = Op.getSimpleValueType();
10782 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10784 // variable index can't be handled in mask registers,
10785 // extend vector to VR512
10786 if (!isa<ConstantSDNode>(Idx)) {
10787 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10788 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10789 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10790 ExtVT.getVectorElementType(), Ext, Idx);
10791 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10794 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10795 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10796 unsigned MaxSift = rc->getSize()*8 - 1;
10797 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10798 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10799 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10800 DAG.getConstant(MaxSift, MVT::i8));
10801 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10802 DAG.getIntPtrConstant(0));
10806 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10807 SelectionDAG &DAG) const {
10809 SDValue Vec = Op.getOperand(0);
10810 MVT VecVT = Vec.getSimpleValueType();
10811 SDValue Idx = Op.getOperand(1);
10813 if (Op.getSimpleValueType() == MVT::i1)
10814 return ExtractBitFromMaskVector(Op, DAG);
10816 if (!isa<ConstantSDNode>(Idx)) {
10817 if (VecVT.is512BitVector() ||
10818 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10819 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10822 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10823 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10824 MaskEltVT.getSizeInBits());
10826 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10827 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10828 getZeroVector(MaskVT, Subtarget, DAG, dl),
10829 Idx, DAG.getConstant(0, getPointerTy()));
10830 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10831 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10832 Perm, DAG.getConstant(0, getPointerTy()));
10837 // If this is a 256-bit vector result, first extract the 128-bit vector and
10838 // then extract the element from the 128-bit vector.
10839 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10841 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10842 // Get the 128-bit vector.
10843 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10844 MVT EltVT = VecVT.getVectorElementType();
10846 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10848 //if (IdxVal >= NumElems/2)
10849 // IdxVal -= NumElems/2;
10850 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10851 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10852 DAG.getConstant(IdxVal, MVT::i32));
10855 assert(VecVT.is128BitVector() && "Unexpected vector length");
10857 if (Subtarget->hasSSE41()) {
10858 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10863 MVT VT = Op.getSimpleValueType();
10864 // TODO: handle v16i8.
10865 if (VT.getSizeInBits() == 16) {
10866 SDValue Vec = Op.getOperand(0);
10867 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10869 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10870 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10871 DAG.getNode(ISD::BITCAST, dl,
10873 Op.getOperand(1)));
10874 // Transform it so it match pextrw which produces a 32-bit result.
10875 MVT EltVT = MVT::i32;
10876 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10877 Op.getOperand(0), Op.getOperand(1));
10878 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10879 DAG.getValueType(VT));
10880 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10883 if (VT.getSizeInBits() == 32) {
10884 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10888 // SHUFPS the element to the lowest double word, then movss.
10889 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10890 MVT VVT = Op.getOperand(0).getSimpleValueType();
10891 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10892 DAG.getUNDEF(VVT), Mask);
10893 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10894 DAG.getIntPtrConstant(0));
10897 if (VT.getSizeInBits() == 64) {
10898 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10899 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10900 // to match extract_elt for f64.
10901 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10905 // UNPCKHPD the element to the lowest double word, then movsd.
10906 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10907 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10908 int Mask[2] = { 1, -1 };
10909 MVT VVT = Op.getOperand(0).getSimpleValueType();
10910 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10911 DAG.getUNDEF(VVT), Mask);
10912 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10913 DAG.getIntPtrConstant(0));
10919 /// Insert one bit to mask vector, like v16i1 or v8i1.
10920 /// AVX-512 feature.
10922 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10924 SDValue Vec = Op.getOperand(0);
10925 SDValue Elt = Op.getOperand(1);
10926 SDValue Idx = Op.getOperand(2);
10927 MVT VecVT = Vec.getSimpleValueType();
10929 if (!isa<ConstantSDNode>(Idx)) {
10930 // Non constant index. Extend source and destination,
10931 // insert element and then truncate the result.
10932 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10933 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10934 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10935 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10936 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10937 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10940 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10941 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10942 if (Vec.getOpcode() == ISD::UNDEF)
10943 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10944 DAG.getConstant(IdxVal, MVT::i8));
10945 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10946 unsigned MaxSift = rc->getSize()*8 - 1;
10947 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10948 DAG.getConstant(MaxSift, MVT::i8));
10949 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10950 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10951 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10954 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10955 SelectionDAG &DAG) const {
10956 MVT VT = Op.getSimpleValueType();
10957 MVT EltVT = VT.getVectorElementType();
10959 if (EltVT == MVT::i1)
10960 return InsertBitToMaskVector(Op, DAG);
10963 SDValue N0 = Op.getOperand(0);
10964 SDValue N1 = Op.getOperand(1);
10965 SDValue N2 = Op.getOperand(2);
10966 if (!isa<ConstantSDNode>(N2))
10968 auto *N2C = cast<ConstantSDNode>(N2);
10969 unsigned IdxVal = N2C->getZExtValue();
10971 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10972 // into that, and then insert the subvector back into the result.
10973 if (VT.is256BitVector() || VT.is512BitVector()) {
10974 // Get the desired 128-bit vector half.
10975 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10977 // Insert the element into the desired half.
10978 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10979 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10981 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10982 DAG.getConstant(IdxIn128, MVT::i32));
10984 // Insert the changed part back to the 256-bit vector
10985 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10987 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10989 if (Subtarget->hasSSE41()) {
10990 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10992 if (VT == MVT::v8i16) {
10993 Opc = X86ISD::PINSRW;
10995 assert(VT == MVT::v16i8);
10996 Opc = X86ISD::PINSRB;
10999 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11001 if (N1.getValueType() != MVT::i32)
11002 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11003 if (N2.getValueType() != MVT::i32)
11004 N2 = DAG.getIntPtrConstant(IdxVal);
11005 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11008 if (EltVT == MVT::f32) {
11009 // Bits [7:6] of the constant are the source select. This will always be
11010 // zero here. The DAG Combiner may combine an extract_elt index into
11012 // bits. For example (insert (extract, 3), 2) could be matched by
11014 // the '3' into bits [7:6] of X86ISD::INSERTPS.
11015 // Bits [5:4] of the constant are the destination select. This is the
11016 // value of the incoming immediate.
11017 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11018 // combine either bitwise AND or insert of float 0.0 to set these bits.
11019 N2 = DAG.getIntPtrConstant(IdxVal << 4);
11020 // Create this as a scalar to vector..
11021 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11022 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11025 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11026 // PINSR* works with constant index.
11031 if (EltVT == MVT::i8)
11034 if (EltVT.getSizeInBits() == 16) {
11035 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11036 // as its second argument.
11037 if (N1.getValueType() != MVT::i32)
11038 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11039 if (N2.getValueType() != MVT::i32)
11040 N2 = DAG.getIntPtrConstant(IdxVal);
11041 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11046 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11048 MVT OpVT = Op.getSimpleValueType();
11050 // If this is a 256-bit vector result, first insert into a 128-bit
11051 // vector and then insert into the 256-bit vector.
11052 if (!OpVT.is128BitVector()) {
11053 // Insert into a 128-bit vector.
11054 unsigned SizeFactor = OpVT.getSizeInBits()/128;
11055 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11056 OpVT.getVectorNumElements() / SizeFactor);
11058 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11060 // Insert the 128-bit vector.
11061 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11064 if (OpVT == MVT::v1i64 &&
11065 Op.getOperand(0).getValueType() == MVT::i64)
11066 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11068 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11069 assert(OpVT.is128BitVector() && "Expected an SSE type!");
11070 return DAG.getNode(ISD::BITCAST, dl, OpVT,
11071 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
11074 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
11075 // a simple subregister reference or explicit instructions to grab
11076 // upper bits of a vector.
11077 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11078 SelectionDAG &DAG) {
11080 SDValue In = Op.getOperand(0);
11081 SDValue Idx = Op.getOperand(1);
11082 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11083 MVT ResVT = Op.getSimpleValueType();
11084 MVT InVT = In.getSimpleValueType();
11086 if (Subtarget->hasFp256()) {
11087 if (ResVT.is128BitVector() &&
11088 (InVT.is256BitVector() || InVT.is512BitVector()) &&
11089 isa<ConstantSDNode>(Idx)) {
11090 return Extract128BitVector(In, IdxVal, DAG, dl);
11092 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11093 isa<ConstantSDNode>(Idx)) {
11094 return Extract256BitVector(In, IdxVal, DAG, dl);
11100 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
11101 // simple superregister reference or explicit instructions to insert
11102 // the upper bits of a vector.
11103 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11104 SelectionDAG &DAG) {
11105 if (Subtarget->hasFp256()) {
11106 SDLoc dl(Op.getNode());
11107 SDValue Vec = Op.getNode()->getOperand(0);
11108 SDValue SubVec = Op.getNode()->getOperand(1);
11109 SDValue Idx = Op.getNode()->getOperand(2);
11111 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
11112 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
11113 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
11114 isa<ConstantSDNode>(Idx)) {
11115 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11116 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11119 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
11120 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
11121 isa<ConstantSDNode>(Idx)) {
11122 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11123 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11129 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11130 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11131 // one of the above mentioned nodes. It has to be wrapped because otherwise
11132 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11133 // be used to form addressing mode. These wrapped nodes will be selected
11136 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11137 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11139 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11140 // global base reg.
11141 unsigned char OpFlag = 0;
11142 unsigned WrapperKind = X86ISD::Wrapper;
11143 CodeModel::Model M = DAG.getTarget().getCodeModel();
11145 if (Subtarget->isPICStyleRIPRel() &&
11146 (M == CodeModel::Small || M == CodeModel::Kernel))
11147 WrapperKind = X86ISD::WrapperRIP;
11148 else if (Subtarget->isPICStyleGOT())
11149 OpFlag = X86II::MO_GOTOFF;
11150 else if (Subtarget->isPICStyleStubPIC())
11151 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11153 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
11154 CP->getAlignment(),
11155 CP->getOffset(), OpFlag);
11157 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11158 // With PIC, the address is actually $g + Offset.
11160 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11161 DAG.getNode(X86ISD::GlobalBaseReg,
11162 SDLoc(), getPointerTy()),
11169 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11170 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11172 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11173 // global base reg.
11174 unsigned char OpFlag = 0;
11175 unsigned WrapperKind = X86ISD::Wrapper;
11176 CodeModel::Model M = DAG.getTarget().getCodeModel();
11178 if (Subtarget->isPICStyleRIPRel() &&
11179 (M == CodeModel::Small || M == CodeModel::Kernel))
11180 WrapperKind = X86ISD::WrapperRIP;
11181 else if (Subtarget->isPICStyleGOT())
11182 OpFlag = X86II::MO_GOTOFF;
11183 else if (Subtarget->isPICStyleStubPIC())
11184 OpFlag = X86II::MO_PIC_BASE_OFFSET;
11186 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11189 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11191 // With PIC, the address is actually $g + Offset.
11193 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11194 DAG.getNode(X86ISD::GlobalBaseReg,
11195 SDLoc(), getPointerTy()),
11202 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11203 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11205 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11206 // global base reg.
11207 unsigned char OpFlag = 0;
11208 unsigned WrapperKind = X86ISD::Wrapper;
11209 CodeModel::Model M = DAG.getTarget().getCodeModel();
11211 if (Subtarget->isPICStyleRIPRel() &&
11212 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11213 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11214 OpFlag = X86II::MO_GOTPCREL;
11215 WrapperKind = X86ISD::WrapperRIP;
11216 } else if (Subtarget->isPICStyleGOT()) {
11217 OpFlag = X86II::MO_GOT;
11218 } else if (Subtarget->isPICStyleStubPIC()) {
11219 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11220 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11221 OpFlag = X86II::MO_DARWIN_NONLAZY;
11224 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11227 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11229 // With PIC, the address is actually $g + Offset.
11230 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11231 !Subtarget->is64Bit()) {
11232 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11233 DAG.getNode(X86ISD::GlobalBaseReg,
11234 SDLoc(), getPointerTy()),
11238 // For symbols that require a load from a stub to get the address, emit the
11240 if (isGlobalStubReference(OpFlag))
11241 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11242 MachinePointerInfo::getGOT(), false, false, false, 0);
11248 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11249 // Create the TargetBlockAddressAddress node.
11250 unsigned char OpFlags =
11251 Subtarget->ClassifyBlockAddressReference();
11252 CodeModel::Model M = DAG.getTarget().getCodeModel();
11253 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11254 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11256 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11259 if (Subtarget->isPICStyleRIPRel() &&
11260 (M == CodeModel::Small || M == CodeModel::Kernel))
11261 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11263 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11265 // With PIC, the address is actually $g + Offset.
11266 if (isGlobalRelativeToPICBase(OpFlags)) {
11267 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11268 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11276 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11277 int64_t Offset, SelectionDAG &DAG) const {
11278 // Create the TargetGlobalAddress node, folding in the constant
11279 // offset if it is legal.
11280 unsigned char OpFlags =
11281 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11282 CodeModel::Model M = DAG.getTarget().getCodeModel();
11284 if (OpFlags == X86II::MO_NO_FLAG &&
11285 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11286 // A direct static reference to a global.
11287 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11290 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11293 if (Subtarget->isPICStyleRIPRel() &&
11294 (M == CodeModel::Small || M == CodeModel::Kernel))
11295 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11297 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11299 // With PIC, the address is actually $g + Offset.
11300 if (isGlobalRelativeToPICBase(OpFlags)) {
11301 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11302 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11306 // For globals that require a load from a stub to get the address, emit the
11308 if (isGlobalStubReference(OpFlags))
11309 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11310 MachinePointerInfo::getGOT(), false, false, false, 0);
11312 // If there was a non-zero offset that we didn't fold, create an explicit
11313 // addition for it.
11315 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11316 DAG.getConstant(Offset, getPointerTy()));
11322 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11323 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11324 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11325 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11329 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11330 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11331 unsigned char OperandFlags, bool LocalDynamic = false) {
11332 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11333 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11335 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11336 GA->getValueType(0),
11340 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11344 SDValue Ops[] = { Chain, TGA, *InFlag };
11345 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11347 SDValue Ops[] = { Chain, TGA };
11348 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11351 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11352 MFI->setAdjustsStack(true);
11354 SDValue Flag = Chain.getValue(1);
11355 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11358 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11360 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11363 SDLoc dl(GA); // ? function entry point might be better
11364 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11365 DAG.getNode(X86ISD::GlobalBaseReg,
11366 SDLoc(), PtrVT), InFlag);
11367 InFlag = Chain.getValue(1);
11369 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11372 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11374 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11376 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11377 X86::RAX, X86II::MO_TLSGD);
11380 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11386 // Get the start address of the TLS block for this module.
11387 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11388 .getInfo<X86MachineFunctionInfo>();
11389 MFI->incNumLocalDynamicTLSAccesses();
11393 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11394 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11397 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11398 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11399 InFlag = Chain.getValue(1);
11400 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11401 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11404 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11408 unsigned char OperandFlags = X86II::MO_DTPOFF;
11409 unsigned WrapperKind = X86ISD::Wrapper;
11410 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11411 GA->getValueType(0),
11412 GA->getOffset(), OperandFlags);
11413 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11415 // Add x@dtpoff with the base.
11416 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11419 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11420 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11421 const EVT PtrVT, TLSModel::Model model,
11422 bool is64Bit, bool isPIC) {
11425 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11426 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11427 is64Bit ? 257 : 256));
11429 SDValue ThreadPointer =
11430 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11431 MachinePointerInfo(Ptr), false, false, false, 0);
11433 unsigned char OperandFlags = 0;
11434 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11436 unsigned WrapperKind = X86ISD::Wrapper;
11437 if (model == TLSModel::LocalExec) {
11438 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11439 } else if (model == TLSModel::InitialExec) {
11441 OperandFlags = X86II::MO_GOTTPOFF;
11442 WrapperKind = X86ISD::WrapperRIP;
11444 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11447 llvm_unreachable("Unexpected model");
11450 // emit "addl x@ntpoff,%eax" (local exec)
11451 // or "addl x@indntpoff,%eax" (initial exec)
11452 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11454 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11455 GA->getOffset(), OperandFlags);
11456 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11458 if (model == TLSModel::InitialExec) {
11459 if (isPIC && !is64Bit) {
11460 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11461 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11465 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11466 MachinePointerInfo::getGOT(), false, false, false, 0);
11469 // The address of the thread local variable is the add of the thread
11470 // pointer with the offset of the variable.
11471 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11475 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11477 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11478 const GlobalValue *GV = GA->getGlobal();
11480 if (Subtarget->isTargetELF()) {
11481 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11484 case TLSModel::GeneralDynamic:
11485 if (Subtarget->is64Bit())
11486 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11487 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11488 case TLSModel::LocalDynamic:
11489 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11490 Subtarget->is64Bit());
11491 case TLSModel::InitialExec:
11492 case TLSModel::LocalExec:
11493 return LowerToTLSExecModel(
11494 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11495 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11497 llvm_unreachable("Unknown TLS model.");
11500 if (Subtarget->isTargetDarwin()) {
11501 // Darwin only has one model of TLS. Lower to that.
11502 unsigned char OpFlag = 0;
11503 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11504 X86ISD::WrapperRIP : X86ISD::Wrapper;
11506 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11507 // global base reg.
11508 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11509 !Subtarget->is64Bit();
11511 OpFlag = X86II::MO_TLVP_PIC_BASE;
11513 OpFlag = X86II::MO_TLVP;
11515 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11516 GA->getValueType(0),
11517 GA->getOffset(), OpFlag);
11518 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11520 // With PIC32, the address is actually $g + Offset.
11522 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11523 DAG.getNode(X86ISD::GlobalBaseReg,
11524 SDLoc(), getPointerTy()),
11527 // Lowering the machine isd will make sure everything is in the right
11529 SDValue Chain = DAG.getEntryNode();
11530 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11531 SDValue Args[] = { Chain, Offset };
11532 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11534 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11535 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11536 MFI->setAdjustsStack(true);
11538 // And our return value (tls address) is in the standard call return value
11540 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11541 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11542 Chain.getValue(1));
11545 if (Subtarget->isTargetKnownWindowsMSVC() ||
11546 Subtarget->isTargetWindowsGNU()) {
11547 // Just use the implicit TLS architecture
11548 // Need to generate someting similar to:
11549 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11551 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11552 // mov rcx, qword [rdx+rcx*8]
11553 // mov eax, .tls$:tlsvar
11554 // [rax+rcx] contains the address
11555 // Windows 64bit: gs:0x58
11556 // Windows 32bit: fs:__tls_array
11559 SDValue Chain = DAG.getEntryNode();
11561 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11562 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11563 // use its literal value of 0x2C.
11564 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11565 ? Type::getInt8PtrTy(*DAG.getContext(),
11567 : Type::getInt32PtrTy(*DAG.getContext(),
11571 Subtarget->is64Bit()
11572 ? DAG.getIntPtrConstant(0x58)
11573 : (Subtarget->isTargetWindowsGNU()
11574 ? DAG.getIntPtrConstant(0x2C)
11575 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11577 SDValue ThreadPointer =
11578 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11579 MachinePointerInfo(Ptr), false, false, false, 0);
11581 // Load the _tls_index variable
11582 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11583 if (Subtarget->is64Bit())
11584 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11585 IDX, MachinePointerInfo(), MVT::i32,
11586 false, false, false, 0);
11588 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11589 false, false, false, 0);
11591 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11593 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11595 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11596 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11597 false, false, false, 0);
11599 // Get the offset of start of .tls section
11600 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11601 GA->getValueType(0),
11602 GA->getOffset(), X86II::MO_SECREL);
11603 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11605 // The address of the thread local variable is the add of the thread
11606 // pointer with the offset of the variable.
11607 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11610 llvm_unreachable("TLS not implemented for this target.");
11613 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11614 /// and take a 2 x i32 value to shift plus a shift amount.
11615 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11616 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11617 MVT VT = Op.getSimpleValueType();
11618 unsigned VTBits = VT.getSizeInBits();
11620 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11621 SDValue ShOpLo = Op.getOperand(0);
11622 SDValue ShOpHi = Op.getOperand(1);
11623 SDValue ShAmt = Op.getOperand(2);
11624 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11625 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11627 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11628 DAG.getConstant(VTBits - 1, MVT::i8));
11629 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11630 DAG.getConstant(VTBits - 1, MVT::i8))
11631 : DAG.getConstant(0, VT);
11633 SDValue Tmp2, Tmp3;
11634 if (Op.getOpcode() == ISD::SHL_PARTS) {
11635 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11636 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11638 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11639 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11642 // If the shift amount is larger or equal than the width of a part we can't
11643 // rely on the results of shld/shrd. Insert a test and select the appropriate
11644 // values for large shift amounts.
11645 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11646 DAG.getConstant(VTBits, MVT::i8));
11647 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11648 AndNode, DAG.getConstant(0, MVT::i8));
11651 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11652 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11653 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11655 if (Op.getOpcode() == ISD::SHL_PARTS) {
11656 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11657 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11659 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11660 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11663 SDValue Ops[2] = { Lo, Hi };
11664 return DAG.getMergeValues(Ops, dl);
11667 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11668 SelectionDAG &DAG) const {
11669 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11671 if (SrcVT.isVector())
11674 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11675 "Unknown SINT_TO_FP to lower!");
11677 // These are really Legal; return the operand so the caller accepts it as
11679 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11681 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11682 Subtarget->is64Bit()) {
11687 unsigned Size = SrcVT.getSizeInBits()/8;
11688 MachineFunction &MF = DAG.getMachineFunction();
11689 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11690 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11691 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11693 MachinePointerInfo::getFixedStack(SSFI),
11695 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11698 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11700 SelectionDAG &DAG) const {
11704 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11706 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11708 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11710 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11712 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11713 MachineMemOperand *MMO;
11715 int SSFI = FI->getIndex();
11717 DAG.getMachineFunction()
11718 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11719 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11721 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11722 StackSlot = StackSlot.getOperand(1);
11724 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11725 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11727 Tys, Ops, SrcVT, MMO);
11730 Chain = Result.getValue(1);
11731 SDValue InFlag = Result.getValue(2);
11733 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11734 // shouldn't be necessary except that RFP cannot be live across
11735 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11736 MachineFunction &MF = DAG.getMachineFunction();
11737 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11738 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11739 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11740 Tys = DAG.getVTList(MVT::Other);
11742 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11744 MachineMemOperand *MMO =
11745 DAG.getMachineFunction()
11746 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11747 MachineMemOperand::MOStore, SSFISize, SSFISize);
11749 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11750 Ops, Op.getValueType(), MMO);
11751 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11752 MachinePointerInfo::getFixedStack(SSFI),
11753 false, false, false, 0);
11759 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11760 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11761 SelectionDAG &DAG) const {
11762 // This algorithm is not obvious. Here it is what we're trying to output:
11765 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11766 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11768 haddpd %xmm0, %xmm0
11770 pshufd $0x4e, %xmm0, %xmm1
11776 LLVMContext *Context = DAG.getContext();
11778 // Build some magic constants.
11779 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11780 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11781 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11783 SmallVector<Constant*,2> CV1;
11785 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11786 APInt(64, 0x4330000000000000ULL))));
11788 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11789 APInt(64, 0x4530000000000000ULL))));
11790 Constant *C1 = ConstantVector::get(CV1);
11791 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11793 // Load the 64-bit value into an XMM register.
11794 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11796 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11797 MachinePointerInfo::getConstantPool(),
11798 false, false, false, 16);
11799 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11800 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11803 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11804 MachinePointerInfo::getConstantPool(),
11805 false, false, false, 16);
11806 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11807 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11810 if (Subtarget->hasSSE3()) {
11811 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11812 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11814 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11815 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11817 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11818 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11822 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11823 DAG.getIntPtrConstant(0));
11826 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11827 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11828 SelectionDAG &DAG) const {
11830 // FP constant to bias correct the final result.
11831 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11834 // Load the 32-bit value into an XMM register.
11835 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11838 // Zero out the upper parts of the register.
11839 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11841 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11842 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11843 DAG.getIntPtrConstant(0));
11845 // Or the load with the bias.
11846 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11847 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11848 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11849 MVT::v2f64, Load)),
11850 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11851 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11852 MVT::v2f64, Bias)));
11853 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11854 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11855 DAG.getIntPtrConstant(0));
11857 // Subtract the bias.
11858 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11860 // Handle final rounding.
11861 EVT DestVT = Op.getValueType();
11863 if (DestVT.bitsLT(MVT::f64))
11864 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11865 DAG.getIntPtrConstant(0));
11866 if (DestVT.bitsGT(MVT::f64))
11867 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11869 // Handle final rounding.
11873 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11874 SelectionDAG &DAG) const {
11875 SDValue N0 = Op.getOperand(0);
11876 MVT SVT = N0.getSimpleValueType();
11879 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11880 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11881 "Custom UINT_TO_FP is not supported!");
11883 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11884 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11885 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11888 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11889 SelectionDAG &DAG) const {
11890 SDValue N0 = Op.getOperand(0);
11893 if (Op.getValueType().isVector())
11894 return lowerUINT_TO_FP_vec(Op, DAG);
11896 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11897 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11898 // the optimization here.
11899 if (DAG.SignBitIsZero(N0))
11900 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11902 MVT SrcVT = N0.getSimpleValueType();
11903 MVT DstVT = Op.getSimpleValueType();
11904 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11905 return LowerUINT_TO_FP_i64(Op, DAG);
11906 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11907 return LowerUINT_TO_FP_i32(Op, DAG);
11908 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11911 // Make a 64-bit buffer, and use it to build an FILD.
11912 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11913 if (SrcVT == MVT::i32) {
11914 SDValue WordOff = DAG.getConstant(4, getPointerTy());
11915 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11916 getPointerTy(), StackSlot, WordOff);
11917 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11918 StackSlot, MachinePointerInfo(),
11920 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11921 OffsetSlot, MachinePointerInfo(),
11923 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11927 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11928 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11929 StackSlot, MachinePointerInfo(),
11931 // For i64 source, we need to add the appropriate power of 2 if the input
11932 // was negative. This is the same as the optimization in
11933 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11934 // we must be careful to do the computation in x87 extended precision, not
11935 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11936 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11937 MachineMemOperand *MMO =
11938 DAG.getMachineFunction()
11939 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11940 MachineMemOperand::MOLoad, 8, 8);
11942 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11943 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11944 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11947 APInt FF(32, 0x5F800000ULL);
11949 // Check whether the sign bit is set.
11950 SDValue SignSet = DAG.getSetCC(dl,
11951 getSetCCResultType(*DAG.getContext(), MVT::i64),
11952 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11955 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11956 SDValue FudgePtr = DAG.getConstantPool(
11957 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11960 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11961 SDValue Zero = DAG.getIntPtrConstant(0);
11962 SDValue Four = DAG.getIntPtrConstant(4);
11963 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11965 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11967 // Load the value out, extending it from f32 to f80.
11968 // FIXME: Avoid the extend by constructing the right constant pool?
11969 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11970 FudgePtr, MachinePointerInfo::getConstantPool(),
11971 MVT::f32, false, false, false, 4);
11972 // Extend everything to 80 bits to force it to be done on x87.
11973 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11974 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11977 std::pair<SDValue,SDValue>
11978 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11979 bool IsSigned, bool IsReplace) const {
11982 EVT DstTy = Op.getValueType();
11984 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11985 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11989 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11990 DstTy.getSimpleVT() >= MVT::i16 &&
11991 "Unknown FP_TO_INT to lower!");
11993 // These are really Legal.
11994 if (DstTy == MVT::i32 &&
11995 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11996 return std::make_pair(SDValue(), SDValue());
11997 if (Subtarget->is64Bit() &&
11998 DstTy == MVT::i64 &&
11999 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12000 return std::make_pair(SDValue(), SDValue());
12002 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12003 // stack slot, or into the FTOL runtime function.
12004 MachineFunction &MF = DAG.getMachineFunction();
12005 unsigned MemSize = DstTy.getSizeInBits()/8;
12006 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12007 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12010 if (!IsSigned && isIntegerTypeFTOL(DstTy))
12011 Opc = X86ISD::WIN_FTOL;
12013 switch (DstTy.getSimpleVT().SimpleTy) {
12014 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12015 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12016 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12017 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12020 SDValue Chain = DAG.getEntryNode();
12021 SDValue Value = Op.getOperand(0);
12022 EVT TheVT = Op.getOperand(0).getValueType();
12023 // FIXME This causes a redundant load/store if the SSE-class value is already
12024 // in memory, such as if it is on the callstack.
12025 if (isScalarFPTypeInSSEReg(TheVT)) {
12026 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12027 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12028 MachinePointerInfo::getFixedStack(SSFI),
12030 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12032 Chain, StackSlot, DAG.getValueType(TheVT)
12035 MachineMemOperand *MMO =
12036 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12037 MachineMemOperand::MOLoad, MemSize, MemSize);
12038 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12039 Chain = Value.getValue(1);
12040 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12041 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12044 MachineMemOperand *MMO =
12045 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12046 MachineMemOperand::MOStore, MemSize, MemSize);
12048 if (Opc != X86ISD::WIN_FTOL) {
12049 // Build the FP_TO_INT*_IN_MEM
12050 SDValue Ops[] = { Chain, Value, StackSlot };
12051 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12053 return std::make_pair(FIST, StackSlot);
12055 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12056 DAG.getVTList(MVT::Other, MVT::Glue),
12058 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12059 MVT::i32, ftol.getValue(1));
12060 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12061 MVT::i32, eax.getValue(2));
12062 SDValue Ops[] = { eax, edx };
12063 SDValue pair = IsReplace
12064 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12065 : DAG.getMergeValues(Ops, DL);
12066 return std::make_pair(pair, SDValue());
12070 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12071 const X86Subtarget *Subtarget) {
12072 MVT VT = Op->getSimpleValueType(0);
12073 SDValue In = Op->getOperand(0);
12074 MVT InVT = In.getSimpleValueType();
12077 // Optimize vectors in AVX mode:
12080 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
12081 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
12082 // Concat upper and lower parts.
12085 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
12086 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
12087 // Concat upper and lower parts.
12090 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12091 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12092 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12095 if (Subtarget->hasInt256())
12096 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12098 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12099 SDValue Undef = DAG.getUNDEF(InVT);
12100 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12101 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12102 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12104 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12105 VT.getVectorNumElements()/2);
12107 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12108 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12110 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12113 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12114 SelectionDAG &DAG) {
12115 MVT VT = Op->getSimpleValueType(0);
12116 SDValue In = Op->getOperand(0);
12117 MVT InVT = In.getSimpleValueType();
12119 unsigned int NumElts = VT.getVectorNumElements();
12120 if (NumElts != 8 && NumElts != 16)
12123 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12124 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12126 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
12127 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12128 // Now we have only mask extension
12129 assert(InVT.getVectorElementType() == MVT::i1);
12130 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
12131 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
12132 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12133 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12134 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12135 MachinePointerInfo::getConstantPool(),
12136 false, false, false, Alignment);
12138 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
12139 if (VT.is512BitVector())
12141 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
12144 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12145 SelectionDAG &DAG) {
12146 if (Subtarget->hasFp256()) {
12147 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12155 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12156 SelectionDAG &DAG) {
12158 MVT VT = Op.getSimpleValueType();
12159 SDValue In = Op.getOperand(0);
12160 MVT SVT = In.getSimpleValueType();
12162 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12163 return LowerZERO_EXTEND_AVX512(Op, DAG);
12165 if (Subtarget->hasFp256()) {
12166 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12171 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12172 VT.getVectorNumElements() != SVT.getVectorNumElements());
12176 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12178 MVT VT = Op.getSimpleValueType();
12179 SDValue In = Op.getOperand(0);
12180 MVT InVT = In.getSimpleValueType();
12182 if (VT == MVT::i1) {
12183 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12184 "Invalid scalar TRUNCATE operation");
12185 if (InVT.getSizeInBits() >= 32)
12187 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12188 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12190 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12191 "Invalid TRUNCATE operation");
12193 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12194 if (VT.getVectorElementType().getSizeInBits() >=8)
12195 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12197 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12198 unsigned NumElts = InVT.getVectorNumElements();
12199 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12200 if (InVT.getSizeInBits() < 512) {
12201 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12202 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12206 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
12207 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
12208 SDValue CP = DAG.getConstantPool(C, getPointerTy());
12209 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12210 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12211 MachinePointerInfo::getConstantPool(),
12212 false, false, false, Alignment);
12213 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
12214 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12215 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12218 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12219 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12220 if (Subtarget->hasInt256()) {
12221 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12222 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12223 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12225 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12226 DAG.getIntPtrConstant(0));
12229 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12230 DAG.getIntPtrConstant(0));
12231 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12232 DAG.getIntPtrConstant(2));
12233 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12234 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12235 static const int ShufMask[] = {0, 2, 4, 6};
12236 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12239 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12240 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12241 if (Subtarget->hasInt256()) {
12242 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12244 SmallVector<SDValue,32> pshufbMask;
12245 for (unsigned i = 0; i < 2; ++i) {
12246 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
12247 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
12248 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
12249 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
12250 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
12251 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
12252 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
12253 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
12254 for (unsigned j = 0; j < 8; ++j)
12255 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
12257 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12258 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12259 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12261 static const int ShufMask[] = {0, 2, -1, -1};
12262 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12264 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12265 DAG.getIntPtrConstant(0));
12266 return DAG.getNode(ISD::BITCAST, DL, VT, In);
12269 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12270 DAG.getIntPtrConstant(0));
12272 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12273 DAG.getIntPtrConstant(4));
12275 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12276 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12278 // The PSHUFB mask:
12279 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12280 -1, -1, -1, -1, -1, -1, -1, -1};
12282 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12283 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12284 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12286 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12287 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12289 // The MOVLHPS Mask:
12290 static const int ShufMask2[] = {0, 1, 4, 5};
12291 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12292 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12295 // Handle truncation of V256 to V128 using shuffles.
12296 if (!VT.is128BitVector() || !InVT.is256BitVector())
12299 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12301 unsigned NumElems = VT.getVectorNumElements();
12302 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12304 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12305 // Prepare truncation shuffle mask
12306 for (unsigned i = 0; i != NumElems; ++i)
12307 MaskVec[i] = i * 2;
12308 SDValue V = DAG.getVectorShuffle(NVT, DL,
12309 DAG.getNode(ISD::BITCAST, DL, NVT, In),
12310 DAG.getUNDEF(NVT), &MaskVec[0]);
12311 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12312 DAG.getIntPtrConstant(0));
12315 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12316 SelectionDAG &DAG) const {
12317 assert(!Op.getSimpleValueType().isVector());
12319 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12320 /*IsSigned=*/ true, /*IsReplace=*/ false);
12321 SDValue FIST = Vals.first, StackSlot = Vals.second;
12322 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12323 if (!FIST.getNode()) return Op;
12325 if (StackSlot.getNode())
12326 // Load the result.
12327 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12328 FIST, StackSlot, MachinePointerInfo(),
12329 false, false, false, 0);
12331 // The node is the result.
12335 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12336 SelectionDAG &DAG) const {
12337 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12338 /*IsSigned=*/ false, /*IsReplace=*/ false);
12339 SDValue FIST = Vals.first, StackSlot = Vals.second;
12340 assert(FIST.getNode() && "Unexpected failure");
12342 if (StackSlot.getNode())
12343 // Load the result.
12344 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12345 FIST, StackSlot, MachinePointerInfo(),
12346 false, false, false, 0);
12348 // The node is the result.
12352 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12354 MVT VT = Op.getSimpleValueType();
12355 SDValue In = Op.getOperand(0);
12356 MVT SVT = In.getSimpleValueType();
12358 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12360 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12361 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12362 In, DAG.getUNDEF(SVT)));
12365 // The only differences between FABS and FNEG are the mask and the logic op.
12366 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12367 assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12368 "Wrong opcode for lowering FABS or FNEG.");
12370 bool IsFABS = (Op.getOpcode() == ISD::FABS);
12372 MVT VT = Op.getSimpleValueType();
12373 // Assume scalar op for initialization; update for vector if needed.
12374 // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12375 // generate a 16-byte vector constant and logic op even for the scalar case.
12376 // Using a 16-byte mask allows folding the load of the mask with
12377 // the logic op, so it can save (~4 bytes) on code size.
12379 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12380 // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12381 // decide if we should generate a 16-byte constant mask when we only need 4 or
12382 // 8 bytes for the scalar case.
12383 if (VT.isVector()) {
12384 EltVT = VT.getVectorElementType();
12385 NumElts = VT.getVectorNumElements();
12388 unsigned EltBits = EltVT.getSizeInBits();
12389 LLVMContext *Context = DAG.getContext();
12390 // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12392 IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12393 Constant *C = ConstantInt::get(*Context, MaskElt);
12394 C = ConstantVector::getSplat(NumElts, C);
12395 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12396 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12397 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12398 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12399 MachinePointerInfo::getConstantPool(),
12400 false, false, false, Alignment);
12402 if (VT.isVector()) {
12403 // For a vector, cast operands to a vector type, perform the logic op,
12404 // and cast the result back to the original value type.
12405 MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12406 SDValue Op0Casted = DAG.getNode(ISD::BITCAST, dl, VecVT, Op.getOperand(0));
12407 SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12408 unsigned LogicOp = IsFABS ? ISD::AND : ISD::XOR;
12409 return DAG.getNode(ISD::BITCAST, dl, VT,
12410 DAG.getNode(LogicOp, dl, VecVT, Op0Casted, MaskCasted));
12412 // If not vector, then scalar.
12413 unsigned LogicOp = IsFABS ? X86ISD::FAND : X86ISD::FXOR;
12414 return DAG.getNode(LogicOp, dl, VT, Op.getOperand(0), Mask);
12417 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12418 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12419 LLVMContext *Context = DAG.getContext();
12420 SDValue Op0 = Op.getOperand(0);
12421 SDValue Op1 = Op.getOperand(1);
12423 MVT VT = Op.getSimpleValueType();
12424 MVT SrcVT = Op1.getSimpleValueType();
12426 // If second operand is smaller, extend it first.
12427 if (SrcVT.bitsLT(VT)) {
12428 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12431 // And if it is bigger, shrink it first.
12432 if (SrcVT.bitsGT(VT)) {
12433 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12437 // At this point the operands and the result should have the same
12438 // type, and that won't be f80 since that is not custom lowered.
12440 // First get the sign bit of second operand.
12441 SmallVector<Constant*,4> CV;
12442 if (SrcVT == MVT::f64) {
12443 const fltSemantics &Sem = APFloat::IEEEdouble;
12444 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
12445 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12447 const fltSemantics &Sem = APFloat::IEEEsingle;
12448 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
12449 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12450 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12451 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12453 Constant *C = ConstantVector::get(CV);
12454 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12455 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12456 MachinePointerInfo::getConstantPool(),
12457 false, false, false, 16);
12458 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12460 // Shift sign bit right or left if the two operands have different types.
12461 if (SrcVT.bitsGT(VT)) {
12462 // Op0 is MVT::f32, Op1 is MVT::f64.
12463 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
12464 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
12465 DAG.getConstant(32, MVT::i32));
12466 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
12467 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
12468 DAG.getIntPtrConstant(0));
12471 // Clear first operand sign bit.
12473 if (VT == MVT::f64) {
12474 const fltSemantics &Sem = APFloat::IEEEdouble;
12475 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12476 APInt(64, ~(1ULL << 63)))));
12477 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12479 const fltSemantics &Sem = APFloat::IEEEsingle;
12480 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12481 APInt(32, ~(1U << 31)))));
12482 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12483 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12484 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12486 C = ConstantVector::get(CV);
12487 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12488 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12489 MachinePointerInfo::getConstantPool(),
12490 false, false, false, 16);
12491 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
12493 // Or the value with the sign bit.
12494 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12497 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12498 SDValue N0 = Op.getOperand(0);
12500 MVT VT = Op.getSimpleValueType();
12502 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12503 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12504 DAG.getConstant(1, VT));
12505 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12508 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
12510 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12511 SelectionDAG &DAG) {
12512 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12514 if (!Subtarget->hasSSE41())
12517 if (!Op->hasOneUse())
12520 SDNode *N = Op.getNode();
12523 SmallVector<SDValue, 8> Opnds;
12524 DenseMap<SDValue, unsigned> VecInMap;
12525 SmallVector<SDValue, 8> VecIns;
12526 EVT VT = MVT::Other;
12528 // Recognize a special case where a vector is casted into wide integer to
12530 Opnds.push_back(N->getOperand(0));
12531 Opnds.push_back(N->getOperand(1));
12533 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12534 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12535 // BFS traverse all OR'd operands.
12536 if (I->getOpcode() == ISD::OR) {
12537 Opnds.push_back(I->getOperand(0));
12538 Opnds.push_back(I->getOperand(1));
12539 // Re-evaluate the number of nodes to be traversed.
12540 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12544 // Quit if a non-EXTRACT_VECTOR_ELT
12545 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12548 // Quit if without a constant index.
12549 SDValue Idx = I->getOperand(1);
12550 if (!isa<ConstantSDNode>(Idx))
12553 SDValue ExtractedFromVec = I->getOperand(0);
12554 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12555 if (M == VecInMap.end()) {
12556 VT = ExtractedFromVec.getValueType();
12557 // Quit if not 128/256-bit vector.
12558 if (!VT.is128BitVector() && !VT.is256BitVector())
12560 // Quit if not the same type.
12561 if (VecInMap.begin() != VecInMap.end() &&
12562 VT != VecInMap.begin()->first.getValueType())
12564 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12565 VecIns.push_back(ExtractedFromVec);
12567 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12570 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12571 "Not extracted from 128-/256-bit vector.");
12573 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12575 for (DenseMap<SDValue, unsigned>::const_iterator
12576 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12577 // Quit if not all elements are used.
12578 if (I->second != FullMask)
12582 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12584 // Cast all vectors into TestVT for PTEST.
12585 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12586 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12588 // If more than one full vectors are evaluated, OR them first before PTEST.
12589 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12590 // Each iteration will OR 2 nodes and append the result until there is only
12591 // 1 node left, i.e. the final OR'd value of all vectors.
12592 SDValue LHS = VecIns[Slot];
12593 SDValue RHS = VecIns[Slot + 1];
12594 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12597 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12598 VecIns.back(), VecIns.back());
12601 /// \brief return true if \c Op has a use that doesn't just read flags.
12602 static bool hasNonFlagsUse(SDValue Op) {
12603 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12605 SDNode *User = *UI;
12606 unsigned UOpNo = UI.getOperandNo();
12607 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12608 // Look pass truncate.
12609 UOpNo = User->use_begin().getOperandNo();
12610 User = *User->use_begin();
12613 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12614 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12620 /// Emit nodes that will be selected as "test Op0,Op0", or something
12622 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12623 SelectionDAG &DAG) const {
12624 if (Op.getValueType() == MVT::i1)
12625 // KORTEST instruction should be selected
12626 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12627 DAG.getConstant(0, Op.getValueType()));
12629 // CF and OF aren't always set the way we want. Determine which
12630 // of these we need.
12631 bool NeedCF = false;
12632 bool NeedOF = false;
12635 case X86::COND_A: case X86::COND_AE:
12636 case X86::COND_B: case X86::COND_BE:
12639 case X86::COND_G: case X86::COND_GE:
12640 case X86::COND_L: case X86::COND_LE:
12641 case X86::COND_O: case X86::COND_NO: {
12642 // Check if we really need to set the
12643 // Overflow flag. If NoSignedWrap is present
12644 // that is not actually needed.
12645 switch (Op->getOpcode()) {
12650 const BinaryWithFlagsSDNode *BinNode =
12651 cast<BinaryWithFlagsSDNode>(Op.getNode());
12652 if (BinNode->hasNoSignedWrap())
12662 // See if we can use the EFLAGS value from the operand instead of
12663 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12664 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12665 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12666 // Emit a CMP with 0, which is the TEST pattern.
12667 //if (Op.getValueType() == MVT::i1)
12668 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12669 // DAG.getConstant(0, MVT::i1));
12670 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12671 DAG.getConstant(0, Op.getValueType()));
12673 unsigned Opcode = 0;
12674 unsigned NumOperands = 0;
12676 // Truncate operations may prevent the merge of the SETCC instruction
12677 // and the arithmetic instruction before it. Attempt to truncate the operands
12678 // of the arithmetic instruction and use a reduced bit-width instruction.
12679 bool NeedTruncation = false;
12680 SDValue ArithOp = Op;
12681 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12682 SDValue Arith = Op->getOperand(0);
12683 // Both the trunc and the arithmetic op need to have one user each.
12684 if (Arith->hasOneUse())
12685 switch (Arith.getOpcode()) {
12692 NeedTruncation = true;
12698 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12699 // which may be the result of a CAST. We use the variable 'Op', which is the
12700 // non-casted variable when we check for possible users.
12701 switch (ArithOp.getOpcode()) {
12703 // Due to an isel shortcoming, be conservative if this add is likely to be
12704 // selected as part of a load-modify-store instruction. When the root node
12705 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12706 // uses of other nodes in the match, such as the ADD in this case. This
12707 // leads to the ADD being left around and reselected, with the result being
12708 // two adds in the output. Alas, even if none our users are stores, that
12709 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12710 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12711 // climbing the DAG back to the root, and it doesn't seem to be worth the
12713 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12714 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12715 if (UI->getOpcode() != ISD::CopyToReg &&
12716 UI->getOpcode() != ISD::SETCC &&
12717 UI->getOpcode() != ISD::STORE)
12720 if (ConstantSDNode *C =
12721 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12722 // An add of one will be selected as an INC.
12723 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12724 Opcode = X86ISD::INC;
12729 // An add of negative one (subtract of one) will be selected as a DEC.
12730 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12731 Opcode = X86ISD::DEC;
12737 // Otherwise use a regular EFLAGS-setting add.
12738 Opcode = X86ISD::ADD;
12743 // If we have a constant logical shift that's only used in a comparison
12744 // against zero turn it into an equivalent AND. This allows turning it into
12745 // a TEST instruction later.
12746 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12747 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12748 EVT VT = Op.getValueType();
12749 unsigned BitWidth = VT.getSizeInBits();
12750 unsigned ShAmt = Op->getConstantOperandVal(1);
12751 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12753 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12754 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12755 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12756 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12758 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12759 DAG.getConstant(Mask, VT));
12760 DAG.ReplaceAllUsesWith(Op, New);
12766 // If the primary and result isn't used, don't bother using X86ISD::AND,
12767 // because a TEST instruction will be better.
12768 if (!hasNonFlagsUse(Op))
12774 // Due to the ISEL shortcoming noted above, be conservative if this op is
12775 // likely to be selected as part of a load-modify-store instruction.
12776 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12777 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12778 if (UI->getOpcode() == ISD::STORE)
12781 // Otherwise use a regular EFLAGS-setting instruction.
12782 switch (ArithOp.getOpcode()) {
12783 default: llvm_unreachable("unexpected operator!");
12784 case ISD::SUB: Opcode = X86ISD::SUB; break;
12785 case ISD::XOR: Opcode = X86ISD::XOR; break;
12786 case ISD::AND: Opcode = X86ISD::AND; break;
12788 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12789 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12790 if (EFLAGS.getNode())
12793 Opcode = X86ISD::OR;
12807 return SDValue(Op.getNode(), 1);
12813 // If we found that truncation is beneficial, perform the truncation and
12815 if (NeedTruncation) {
12816 EVT VT = Op.getValueType();
12817 SDValue WideVal = Op->getOperand(0);
12818 EVT WideVT = WideVal.getValueType();
12819 unsigned ConvertedOp = 0;
12820 // Use a target machine opcode to prevent further DAGCombine
12821 // optimizations that may separate the arithmetic operations
12822 // from the setcc node.
12823 switch (WideVal.getOpcode()) {
12825 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12826 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12827 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12828 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12829 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12833 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12834 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12835 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12836 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12837 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12843 // Emit a CMP with 0, which is the TEST pattern.
12844 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12845 DAG.getConstant(0, Op.getValueType()));
12847 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12848 SmallVector<SDValue, 4> Ops;
12849 for (unsigned i = 0; i != NumOperands; ++i)
12850 Ops.push_back(Op.getOperand(i));
12852 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12853 DAG.ReplaceAllUsesWith(Op, New);
12854 return SDValue(New.getNode(), 1);
12857 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12859 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12860 SDLoc dl, SelectionDAG &DAG) const {
12861 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12862 if (C->getAPIntValue() == 0)
12863 return EmitTest(Op0, X86CC, dl, DAG);
12865 if (Op0.getValueType() == MVT::i1)
12866 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12869 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12870 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12871 // Do the comparison at i32 if it's smaller, besides the Atom case.
12872 // This avoids subregister aliasing issues. Keep the smaller reference
12873 // if we're optimizing for size, however, as that'll allow better folding
12874 // of memory operations.
12875 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12876 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12877 AttributeSet::FunctionIndex, Attribute::MinSize) &&
12878 !Subtarget->isAtom()) {
12879 unsigned ExtendOp =
12880 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12881 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12882 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12884 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12885 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12886 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12888 return SDValue(Sub.getNode(), 1);
12890 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12893 /// Convert a comparison if required by the subtarget.
12894 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12895 SelectionDAG &DAG) const {
12896 // If the subtarget does not support the FUCOMI instruction, floating-point
12897 // comparisons have to be converted.
12898 if (Subtarget->hasCMov() ||
12899 Cmp.getOpcode() != X86ISD::CMP ||
12900 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12901 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12904 // The instruction selector will select an FUCOM instruction instead of
12905 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12906 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12907 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12909 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12910 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12911 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12912 DAG.getConstant(8, MVT::i8));
12913 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12914 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12917 static bool isAllOnes(SDValue V) {
12918 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12919 return C && C->isAllOnesValue();
12922 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12923 /// if it's possible.
12924 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12925 SDLoc dl, SelectionDAG &DAG) const {
12926 SDValue Op0 = And.getOperand(0);
12927 SDValue Op1 = And.getOperand(1);
12928 if (Op0.getOpcode() == ISD::TRUNCATE)
12929 Op0 = Op0.getOperand(0);
12930 if (Op1.getOpcode() == ISD::TRUNCATE)
12931 Op1 = Op1.getOperand(0);
12934 if (Op1.getOpcode() == ISD::SHL)
12935 std::swap(Op0, Op1);
12936 if (Op0.getOpcode() == ISD::SHL) {
12937 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12938 if (And00C->getZExtValue() == 1) {
12939 // If we looked past a truncate, check that it's only truncating away
12941 unsigned BitWidth = Op0.getValueSizeInBits();
12942 unsigned AndBitWidth = And.getValueSizeInBits();
12943 if (BitWidth > AndBitWidth) {
12945 DAG.computeKnownBits(Op0, Zeros, Ones);
12946 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12950 RHS = Op0.getOperand(1);
12952 } else if (Op1.getOpcode() == ISD::Constant) {
12953 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12954 uint64_t AndRHSVal = AndRHS->getZExtValue();
12955 SDValue AndLHS = Op0;
12957 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12958 LHS = AndLHS.getOperand(0);
12959 RHS = AndLHS.getOperand(1);
12962 // Use BT if the immediate can't be encoded in a TEST instruction.
12963 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12965 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12969 if (LHS.getNode()) {
12970 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12971 // instruction. Since the shift amount is in-range-or-undefined, we know
12972 // that doing a bittest on the i32 value is ok. We extend to i32 because
12973 // the encoding for the i16 version is larger than the i32 version.
12974 // Also promote i16 to i32 for performance / code size reason.
12975 if (LHS.getValueType() == MVT::i8 ||
12976 LHS.getValueType() == MVT::i16)
12977 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12979 // If the operand types disagree, extend the shift amount to match. Since
12980 // BT ignores high bits (like shifts) we can use anyextend.
12981 if (LHS.getValueType() != RHS.getValueType())
12982 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12984 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12985 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12986 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12987 DAG.getConstant(Cond, MVT::i8), BT);
12993 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12995 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13000 // SSE Condition code mapping:
13009 switch (SetCCOpcode) {
13010 default: llvm_unreachable("Unexpected SETCC condition");
13012 case ISD::SETEQ: SSECC = 0; break;
13014 case ISD::SETGT: Swap = true; // Fallthrough
13016 case ISD::SETOLT: SSECC = 1; break;
13018 case ISD::SETGE: Swap = true; // Fallthrough
13020 case ISD::SETOLE: SSECC = 2; break;
13021 case ISD::SETUO: SSECC = 3; break;
13023 case ISD::SETNE: SSECC = 4; break;
13024 case ISD::SETULE: Swap = true; // Fallthrough
13025 case ISD::SETUGE: SSECC = 5; break;
13026 case ISD::SETULT: Swap = true; // Fallthrough
13027 case ISD::SETUGT: SSECC = 6; break;
13028 case ISD::SETO: SSECC = 7; break;
13030 case ISD::SETONE: SSECC = 8; break;
13033 std::swap(Op0, Op1);
13038 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13039 // ones, and then concatenate the result back.
13040 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13041 MVT VT = Op.getSimpleValueType();
13043 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13044 "Unsupported value type for operation");
13046 unsigned NumElems = VT.getVectorNumElements();
13048 SDValue CC = Op.getOperand(2);
13050 // Extract the LHS vectors
13051 SDValue LHS = Op.getOperand(0);
13052 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13053 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13055 // Extract the RHS vectors
13056 SDValue RHS = Op.getOperand(1);
13057 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13058 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13060 // Issue the operation on the smaller types and concatenate the result back
13061 MVT EltVT = VT.getVectorElementType();
13062 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13063 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13064 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13065 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13068 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13069 const X86Subtarget *Subtarget) {
13070 SDValue Op0 = Op.getOperand(0);
13071 SDValue Op1 = Op.getOperand(1);
13072 SDValue CC = Op.getOperand(2);
13073 MVT VT = Op.getSimpleValueType();
13076 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13077 Op.getValueType().getScalarType() == MVT::i1 &&
13078 "Cannot set masked compare for this operation");
13080 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13082 bool Unsigned = false;
13085 switch (SetCCOpcode) {
13086 default: llvm_unreachable("Unexpected SETCC condition");
13087 case ISD::SETNE: SSECC = 4; break;
13088 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
13089 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13090 case ISD::SETLT: Swap = true; //fall-through
13091 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
13092 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13093 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13094 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
13095 case ISD::SETULE: Unsigned = true; //fall-through
13096 case ISD::SETLE: SSECC = 2; break;
13100 std::swap(Op0, Op1);
13102 return DAG.getNode(Opc, dl, VT, Op0, Op1);
13103 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13104 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13105 DAG.getConstant(SSECC, MVT::i8));
13108 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13109 /// operand \p Op1. If non-trivial (for example because it's not constant)
13110 /// return an empty value.
13111 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13113 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13117 MVT VT = Op1.getSimpleValueType();
13118 MVT EVT = VT.getVectorElementType();
13119 unsigned n = VT.getVectorNumElements();
13120 SmallVector<SDValue, 8> ULTOp1;
13122 for (unsigned i = 0; i < n; ++i) {
13123 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13124 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13127 // Avoid underflow.
13128 APInt Val = Elt->getAPIntValue();
13132 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
13135 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13138 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13139 SelectionDAG &DAG) {
13140 SDValue Op0 = Op.getOperand(0);
13141 SDValue Op1 = Op.getOperand(1);
13142 SDValue CC = Op.getOperand(2);
13143 MVT VT = Op.getSimpleValueType();
13144 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13145 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13150 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13151 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13154 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13155 unsigned Opc = X86ISD::CMPP;
13156 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13157 assert(VT.getVectorNumElements() <= 16);
13158 Opc = X86ISD::CMPM;
13160 // In the two special cases we can't handle, emit two comparisons.
13163 unsigned CombineOpc;
13164 if (SetCCOpcode == ISD::SETUEQ) {
13165 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13167 assert(SetCCOpcode == ISD::SETONE);
13168 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13171 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13172 DAG.getConstant(CC0, MVT::i8));
13173 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13174 DAG.getConstant(CC1, MVT::i8));
13175 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13177 // Handle all other FP comparisons here.
13178 return DAG.getNode(Opc, dl, VT, Op0, Op1,
13179 DAG.getConstant(SSECC, MVT::i8));
13182 // Break 256-bit integer vector compare into smaller ones.
13183 if (VT.is256BitVector() && !Subtarget->hasInt256())
13184 return Lower256IntVSETCC(Op, DAG);
13186 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13187 EVT OpVT = Op1.getValueType();
13188 if (Subtarget->hasAVX512()) {
13189 if (Op1.getValueType().is512BitVector() ||
13190 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13191 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13192 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13194 // In AVX-512 architecture setcc returns mask with i1 elements,
13195 // But there is no compare instruction for i8 and i16 elements in KNL.
13196 // We are not talking about 512-bit operands in this case, these
13197 // types are illegal.
13199 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13200 OpVT.getVectorElementType().getSizeInBits() >= 8))
13201 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13202 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13205 // We are handling one of the integer comparisons here. Since SSE only has
13206 // GT and EQ comparisons for integer, swapping operands and multiple
13207 // operations may be required for some comparisons.
13209 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13210 bool Subus = false;
13212 switch (SetCCOpcode) {
13213 default: llvm_unreachable("Unexpected SETCC condition");
13214 case ISD::SETNE: Invert = true;
13215 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13216 case ISD::SETLT: Swap = true;
13217 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13218 case ISD::SETGE: Swap = true;
13219 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13220 Invert = true; break;
13221 case ISD::SETULT: Swap = true;
13222 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13223 FlipSigns = true; break;
13224 case ISD::SETUGE: Swap = true;
13225 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13226 FlipSigns = true; Invert = true; break;
13229 // Special case: Use min/max operations for SETULE/SETUGE
13230 MVT VET = VT.getVectorElementType();
13232 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13233 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13236 switch (SetCCOpcode) {
13238 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13239 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13242 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13245 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13246 if (!MinMax && hasSubus) {
13247 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13249 // t = psubus Op0, Op1
13250 // pcmpeq t, <0..0>
13251 switch (SetCCOpcode) {
13253 case ISD::SETULT: {
13254 // If the comparison is against a constant we can turn this into a
13255 // setule. With psubus, setule does not require a swap. This is
13256 // beneficial because the constant in the register is no longer
13257 // destructed as the destination so it can be hoisted out of a loop.
13258 // Only do this pre-AVX since vpcmp* is no longer destructive.
13259 if (Subtarget->hasAVX())
13261 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13262 if (ULEOp1.getNode()) {
13264 Subus = true; Invert = false; Swap = false;
13268 // Psubus is better than flip-sign because it requires no inversion.
13269 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13270 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13274 Opc = X86ISD::SUBUS;
13280 std::swap(Op0, Op1);
13282 // Check that the operation in question is available (most are plain SSE2,
13283 // but PCMPGTQ and PCMPEQQ have different requirements).
13284 if (VT == MVT::v2i64) {
13285 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13286 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13288 // First cast everything to the right type.
13289 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13290 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13292 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13293 // bits of the inputs before performing those operations. The lower
13294 // compare is always unsigned.
13297 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13299 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13300 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13301 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13302 Sign, Zero, Sign, Zero);
13304 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13305 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13307 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13308 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13309 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13311 // Create masks for only the low parts/high parts of the 64 bit integers.
13312 static const int MaskHi[] = { 1, 1, 3, 3 };
13313 static const int MaskLo[] = { 0, 0, 2, 2 };
13314 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13315 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13316 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13318 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13319 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13322 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13324 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13327 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13328 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13329 // pcmpeqd + pshufd + pand.
13330 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13332 // First cast everything to the right type.
13333 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13334 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13337 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13339 // Make sure the lower and upper halves are both all-ones.
13340 static const int Mask[] = { 1, 0, 3, 2 };
13341 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13342 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13345 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13347 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13351 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13352 // bits of the inputs before performing those operations.
13354 EVT EltVT = VT.getVectorElementType();
13355 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13356 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13357 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13360 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13362 // If the logical-not of the result is required, perform that now.
13364 Result = DAG.getNOT(dl, Result, VT);
13367 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13370 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13371 getZeroVector(VT, Subtarget, DAG, dl));
13376 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13378 MVT VT = Op.getSimpleValueType();
13380 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13382 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13383 && "SetCC type must be 8-bit or 1-bit integer");
13384 SDValue Op0 = Op.getOperand(0);
13385 SDValue Op1 = Op.getOperand(1);
13387 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13389 // Optimize to BT if possible.
13390 // Lower (X & (1 << N)) == 0 to BT(X, N).
13391 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13392 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13393 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13394 Op1.getOpcode() == ISD::Constant &&
13395 cast<ConstantSDNode>(Op1)->isNullValue() &&
13396 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13397 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13398 if (NewSetCC.getNode())
13402 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13404 if (Op1.getOpcode() == ISD::Constant &&
13405 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13406 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13407 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13409 // If the input is a setcc, then reuse the input setcc or use a new one with
13410 // the inverted condition.
13411 if (Op0.getOpcode() == X86ISD::SETCC) {
13412 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13413 bool Invert = (CC == ISD::SETNE) ^
13414 cast<ConstantSDNode>(Op1)->isNullValue();
13418 CCode = X86::GetOppositeBranchCondition(CCode);
13419 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13420 DAG.getConstant(CCode, MVT::i8),
13421 Op0.getOperand(1));
13423 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13427 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13428 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13429 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13431 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13432 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13435 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13436 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13437 if (X86CC == X86::COND_INVALID)
13440 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13441 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13442 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13443 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13445 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13449 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13450 static bool isX86LogicalCmp(SDValue Op) {
13451 unsigned Opc = Op.getNode()->getOpcode();
13452 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13453 Opc == X86ISD::SAHF)
13455 if (Op.getResNo() == 1 &&
13456 (Opc == X86ISD::ADD ||
13457 Opc == X86ISD::SUB ||
13458 Opc == X86ISD::ADC ||
13459 Opc == X86ISD::SBB ||
13460 Opc == X86ISD::SMUL ||
13461 Opc == X86ISD::UMUL ||
13462 Opc == X86ISD::INC ||
13463 Opc == X86ISD::DEC ||
13464 Opc == X86ISD::OR ||
13465 Opc == X86ISD::XOR ||
13466 Opc == X86ISD::AND))
13469 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13475 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13476 if (V.getOpcode() != ISD::TRUNCATE)
13479 SDValue VOp0 = V.getOperand(0);
13480 unsigned InBits = VOp0.getValueSizeInBits();
13481 unsigned Bits = V.getValueSizeInBits();
13482 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13485 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13486 bool addTest = true;
13487 SDValue Cond = Op.getOperand(0);
13488 SDValue Op1 = Op.getOperand(1);
13489 SDValue Op2 = Op.getOperand(2);
13491 EVT VT = Op1.getValueType();
13494 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13495 // are available. Otherwise fp cmovs get lowered into a less efficient branch
13496 // sequence later on.
13497 if (Cond.getOpcode() == ISD::SETCC &&
13498 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13499 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13500 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13501 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13502 int SSECC = translateX86FSETCC(
13503 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13506 if (Subtarget->hasAVX512()) {
13507 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13508 DAG.getConstant(SSECC, MVT::i8));
13509 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13511 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13512 DAG.getConstant(SSECC, MVT::i8));
13513 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13514 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13515 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13519 if (Cond.getOpcode() == ISD::SETCC) {
13520 SDValue NewCond = LowerSETCC(Cond, DAG);
13521 if (NewCond.getNode())
13525 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13526 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13527 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13528 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13529 if (Cond.getOpcode() == X86ISD::SETCC &&
13530 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13531 isZero(Cond.getOperand(1).getOperand(1))) {
13532 SDValue Cmp = Cond.getOperand(1);
13534 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13536 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13537 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13538 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13540 SDValue CmpOp0 = Cmp.getOperand(0);
13541 // Apply further optimizations for special cases
13542 // (select (x != 0), -1, 0) -> neg & sbb
13543 // (select (x == 0), 0, -1) -> neg & sbb
13544 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13545 if (YC->isNullValue() &&
13546 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13547 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13548 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13549 DAG.getConstant(0, CmpOp0.getValueType()),
13551 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13552 DAG.getConstant(X86::COND_B, MVT::i8),
13553 SDValue(Neg.getNode(), 1));
13557 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13558 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13559 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13561 SDValue Res = // Res = 0 or -1.
13562 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13563 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13565 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13566 Res = DAG.getNOT(DL, Res, Res.getValueType());
13568 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13569 if (!N2C || !N2C->isNullValue())
13570 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13575 // Look past (and (setcc_carry (cmp ...)), 1).
13576 if (Cond.getOpcode() == ISD::AND &&
13577 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13578 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13579 if (C && C->getAPIntValue() == 1)
13580 Cond = Cond.getOperand(0);
13583 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13584 // setting operand in place of the X86ISD::SETCC.
13585 unsigned CondOpcode = Cond.getOpcode();
13586 if (CondOpcode == X86ISD::SETCC ||
13587 CondOpcode == X86ISD::SETCC_CARRY) {
13588 CC = Cond.getOperand(0);
13590 SDValue Cmp = Cond.getOperand(1);
13591 unsigned Opc = Cmp.getOpcode();
13592 MVT VT = Op.getSimpleValueType();
13594 bool IllegalFPCMov = false;
13595 if (VT.isFloatingPoint() && !VT.isVector() &&
13596 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13597 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13599 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13600 Opc == X86ISD::BT) { // FIXME
13604 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13605 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13606 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13607 Cond.getOperand(0).getValueType() != MVT::i8)) {
13608 SDValue LHS = Cond.getOperand(0);
13609 SDValue RHS = Cond.getOperand(1);
13610 unsigned X86Opcode;
13613 switch (CondOpcode) {
13614 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13615 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13616 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13617 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13618 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13619 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13620 default: llvm_unreachable("unexpected overflowing operator");
13622 if (CondOpcode == ISD::UMULO)
13623 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13626 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13628 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13630 if (CondOpcode == ISD::UMULO)
13631 Cond = X86Op.getValue(2);
13633 Cond = X86Op.getValue(1);
13635 CC = DAG.getConstant(X86Cond, MVT::i8);
13640 // Look pass the truncate if the high bits are known zero.
13641 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13642 Cond = Cond.getOperand(0);
13644 // We know the result of AND is compared against zero. Try to match
13646 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13647 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13648 if (NewSetCC.getNode()) {
13649 CC = NewSetCC.getOperand(0);
13650 Cond = NewSetCC.getOperand(1);
13657 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13658 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13661 // a < b ? -1 : 0 -> RES = ~setcc_carry
13662 // a < b ? 0 : -1 -> RES = setcc_carry
13663 // a >= b ? -1 : 0 -> RES = setcc_carry
13664 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13665 if (Cond.getOpcode() == X86ISD::SUB) {
13666 Cond = ConvertCmpIfNecessary(Cond, DAG);
13667 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13669 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13670 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13671 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13672 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13673 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13674 return DAG.getNOT(DL, Res, Res.getValueType());
13679 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13680 // widen the cmov and push the truncate through. This avoids introducing a new
13681 // branch during isel and doesn't add any extensions.
13682 if (Op.getValueType() == MVT::i8 &&
13683 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13684 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13685 if (T1.getValueType() == T2.getValueType() &&
13686 // Blacklist CopyFromReg to avoid partial register stalls.
13687 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13688 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13689 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13690 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13694 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13695 // condition is true.
13696 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13697 SDValue Ops[] = { Op2, Op1, CC, Cond };
13698 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13701 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13702 MVT VT = Op->getSimpleValueType(0);
13703 SDValue In = Op->getOperand(0);
13704 MVT InVT = In.getSimpleValueType();
13707 unsigned int NumElts = VT.getVectorNumElements();
13708 if (NumElts != 8 && NumElts != 16)
13711 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13712 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13714 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13715 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13717 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13718 Constant *C = ConstantInt::get(*DAG.getContext(),
13719 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13721 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13722 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13723 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13724 MachinePointerInfo::getConstantPool(),
13725 false, false, false, Alignment);
13726 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13727 if (VT.is512BitVector())
13729 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13732 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13733 SelectionDAG &DAG) {
13734 MVT VT = Op->getSimpleValueType(0);
13735 SDValue In = Op->getOperand(0);
13736 MVT InVT = In.getSimpleValueType();
13739 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13740 return LowerSIGN_EXTEND_AVX512(Op, DAG);
13742 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13743 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13744 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13747 if (Subtarget->hasInt256())
13748 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13750 // Optimize vectors in AVX mode
13751 // Sign extend v8i16 to v8i32 and
13754 // Divide input vector into two parts
13755 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13756 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13757 // concat the vectors to original VT
13759 unsigned NumElems = InVT.getVectorNumElements();
13760 SDValue Undef = DAG.getUNDEF(InVT);
13762 SmallVector<int,8> ShufMask1(NumElems, -1);
13763 for (unsigned i = 0; i != NumElems/2; ++i)
13766 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13768 SmallVector<int,8> ShufMask2(NumElems, -1);
13769 for (unsigned i = 0; i != NumElems/2; ++i)
13770 ShufMask2[i] = i + NumElems/2;
13772 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13774 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13775 VT.getVectorNumElements()/2);
13777 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13778 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13780 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13783 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13784 // may emit an illegal shuffle but the expansion is still better than scalar
13785 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13786 // we'll emit a shuffle and a arithmetic shift.
13787 // TODO: It is possible to support ZExt by zeroing the undef values during
13788 // the shuffle phase or after the shuffle.
13789 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13790 SelectionDAG &DAG) {
13791 MVT RegVT = Op.getSimpleValueType();
13792 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13793 assert(RegVT.isInteger() &&
13794 "We only custom lower integer vector sext loads.");
13796 // Nothing useful we can do without SSE2 shuffles.
13797 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13799 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13801 EVT MemVT = Ld->getMemoryVT();
13802 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13803 unsigned RegSz = RegVT.getSizeInBits();
13805 ISD::LoadExtType Ext = Ld->getExtensionType();
13807 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13808 && "Only anyext and sext are currently implemented.");
13809 assert(MemVT != RegVT && "Cannot extend to the same type");
13810 assert(MemVT.isVector() && "Must load a vector from memory");
13812 unsigned NumElems = RegVT.getVectorNumElements();
13813 unsigned MemSz = MemVT.getSizeInBits();
13814 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13816 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13817 // The only way in which we have a legal 256-bit vector result but not the
13818 // integer 256-bit operations needed to directly lower a sextload is if we
13819 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13820 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13821 // correctly legalized. We do this late to allow the canonical form of
13822 // sextload to persist throughout the rest of the DAG combiner -- it wants
13823 // to fold together any extensions it can, and so will fuse a sign_extend
13824 // of an sextload into a sextload targeting a wider value.
13826 if (MemSz == 128) {
13827 // Just switch this to a normal load.
13828 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13829 "it must be a legal 128-bit vector "
13831 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13832 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13833 Ld->isInvariant(), Ld->getAlignment());
13835 assert(MemSz < 128 &&
13836 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13837 // Do an sext load to a 128-bit vector type. We want to use the same
13838 // number of elements, but elements half as wide. This will end up being
13839 // recursively lowered by this routine, but will succeed as we definitely
13840 // have all the necessary features if we're using AVX1.
13842 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13843 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13845 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13846 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13847 Ld->isNonTemporal(), Ld->isInvariant(),
13848 Ld->getAlignment());
13851 // Replace chain users with the new chain.
13852 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13853 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13855 // Finally, do a normal sign-extend to the desired register.
13856 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13859 // All sizes must be a power of two.
13860 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13861 "Non-power-of-two elements are not custom lowered!");
13863 // Attempt to load the original value using scalar loads.
13864 // Find the largest scalar type that divides the total loaded size.
13865 MVT SclrLoadTy = MVT::i8;
13866 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13867 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13868 MVT Tp = (MVT::SimpleValueType)tp;
13869 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13874 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13875 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13877 SclrLoadTy = MVT::f64;
13879 // Calculate the number of scalar loads that we need to perform
13880 // in order to load our vector from memory.
13881 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13883 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13884 "Can only lower sext loads with a single scalar load!");
13886 unsigned loadRegZize = RegSz;
13887 if (Ext == ISD::SEXTLOAD && RegSz == 256)
13890 // Represent our vector as a sequence of elements which are the
13891 // largest scalar that we can load.
13892 EVT LoadUnitVecVT = EVT::getVectorVT(
13893 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13895 // Represent the data using the same element type that is stored in
13896 // memory. In practice, we ''widen'' MemVT.
13898 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13899 loadRegZize / MemVT.getScalarType().getSizeInBits());
13901 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13902 "Invalid vector type");
13904 // We can't shuffle using an illegal type.
13905 assert(TLI.isTypeLegal(WideVecVT) &&
13906 "We only lower types that form legal widened vector types");
13908 SmallVector<SDValue, 8> Chains;
13909 SDValue Ptr = Ld->getBasePtr();
13910 SDValue Increment =
13911 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13912 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13914 for (unsigned i = 0; i < NumLoads; ++i) {
13915 // Perform a single load.
13916 SDValue ScalarLoad =
13917 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13918 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13919 Ld->getAlignment());
13920 Chains.push_back(ScalarLoad.getValue(1));
13921 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13922 // another round of DAGCombining.
13924 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13926 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13927 ScalarLoad, DAG.getIntPtrConstant(i));
13929 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13932 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13934 // Bitcast the loaded value to a vector of the original element type, in
13935 // the size of the target vector type.
13936 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13937 unsigned SizeRatio = RegSz / MemSz;
13939 if (Ext == ISD::SEXTLOAD) {
13940 // If we have SSE4.1, we can directly emit a VSEXT node.
13941 if (Subtarget->hasSSE41()) {
13942 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13943 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13947 // Otherwise we'll shuffle the small elements in the high bits of the
13948 // larger type and perform an arithmetic shift. If the shift is not legal
13949 // it's better to scalarize.
13950 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13951 "We can't implement a sext load without an arithmetic right shift!");
13953 // Redistribute the loaded elements into the different locations.
13954 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13955 for (unsigned i = 0; i != NumElems; ++i)
13956 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13958 SDValue Shuff = DAG.getVectorShuffle(
13959 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13961 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13963 // Build the arithmetic shift.
13964 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13965 MemVT.getVectorElementType().getSizeInBits();
13967 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13969 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13973 // Redistribute the loaded elements into the different locations.
13974 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13975 for (unsigned i = 0; i != NumElems; ++i)
13976 ShuffleVec[i * SizeRatio] = i;
13978 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13979 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13981 // Bitcast to the requested type.
13982 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13983 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13987 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13988 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13989 // from the AND / OR.
13990 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13991 Opc = Op.getOpcode();
13992 if (Opc != ISD::OR && Opc != ISD::AND)
13994 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13995 Op.getOperand(0).hasOneUse() &&
13996 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13997 Op.getOperand(1).hasOneUse());
14000 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14001 // 1 and that the SETCC node has a single use.
14002 static bool isXor1OfSetCC(SDValue Op) {
14003 if (Op.getOpcode() != ISD::XOR)
14005 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14006 if (N1C && N1C->getAPIntValue() == 1) {
14007 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14008 Op.getOperand(0).hasOneUse();
14013 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14014 bool addTest = true;
14015 SDValue Chain = Op.getOperand(0);
14016 SDValue Cond = Op.getOperand(1);
14017 SDValue Dest = Op.getOperand(2);
14020 bool Inverted = false;
14022 if (Cond.getOpcode() == ISD::SETCC) {
14023 // Check for setcc([su]{add,sub,mul}o == 0).
14024 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14025 isa<ConstantSDNode>(Cond.getOperand(1)) &&
14026 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14027 Cond.getOperand(0).getResNo() == 1 &&
14028 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14029 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14030 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14031 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14032 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14033 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14035 Cond = Cond.getOperand(0);
14037 SDValue NewCond = LowerSETCC(Cond, DAG);
14038 if (NewCond.getNode())
14043 // FIXME: LowerXALUO doesn't handle these!!
14044 else if (Cond.getOpcode() == X86ISD::ADD ||
14045 Cond.getOpcode() == X86ISD::SUB ||
14046 Cond.getOpcode() == X86ISD::SMUL ||
14047 Cond.getOpcode() == X86ISD::UMUL)
14048 Cond = LowerXALUO(Cond, DAG);
14051 // Look pass (and (setcc_carry (cmp ...)), 1).
14052 if (Cond.getOpcode() == ISD::AND &&
14053 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14054 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14055 if (C && C->getAPIntValue() == 1)
14056 Cond = Cond.getOperand(0);
14059 // If condition flag is set by a X86ISD::CMP, then use it as the condition
14060 // setting operand in place of the X86ISD::SETCC.
14061 unsigned CondOpcode = Cond.getOpcode();
14062 if (CondOpcode == X86ISD::SETCC ||
14063 CondOpcode == X86ISD::SETCC_CARRY) {
14064 CC = Cond.getOperand(0);
14066 SDValue Cmp = Cond.getOperand(1);
14067 unsigned Opc = Cmp.getOpcode();
14068 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14069 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14073 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14077 // These can only come from an arithmetic instruction with overflow,
14078 // e.g. SADDO, UADDO.
14079 Cond = Cond.getNode()->getOperand(1);
14085 CondOpcode = Cond.getOpcode();
14086 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14087 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14088 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14089 Cond.getOperand(0).getValueType() != MVT::i8)) {
14090 SDValue LHS = Cond.getOperand(0);
14091 SDValue RHS = Cond.getOperand(1);
14092 unsigned X86Opcode;
14095 // Keep this in sync with LowerXALUO, otherwise we might create redundant
14096 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14098 switch (CondOpcode) {
14099 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14101 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14103 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14106 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14107 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14109 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14111 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14114 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14115 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14116 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14117 default: llvm_unreachable("unexpected overflowing operator");
14120 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14121 if (CondOpcode == ISD::UMULO)
14122 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14125 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14127 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14129 if (CondOpcode == ISD::UMULO)
14130 Cond = X86Op.getValue(2);
14132 Cond = X86Op.getValue(1);
14134 CC = DAG.getConstant(X86Cond, MVT::i8);
14138 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14139 SDValue Cmp = Cond.getOperand(0).getOperand(1);
14140 if (CondOpc == ISD::OR) {
14141 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14142 // two branches instead of an explicit OR instruction with a
14144 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14145 isX86LogicalCmp(Cmp)) {
14146 CC = Cond.getOperand(0).getOperand(0);
14147 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14148 Chain, Dest, CC, Cmp);
14149 CC = Cond.getOperand(1).getOperand(0);
14153 } else { // ISD::AND
14154 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14155 // two branches instead of an explicit AND instruction with a
14156 // separate test. However, we only do this if this block doesn't
14157 // have a fall-through edge, because this requires an explicit
14158 // jmp when the condition is false.
14159 if (Cmp == Cond.getOperand(1).getOperand(1) &&
14160 isX86LogicalCmp(Cmp) &&
14161 Op.getNode()->hasOneUse()) {
14162 X86::CondCode CCode =
14163 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14164 CCode = X86::GetOppositeBranchCondition(CCode);
14165 CC = DAG.getConstant(CCode, MVT::i8);
14166 SDNode *User = *Op.getNode()->use_begin();
14167 // Look for an unconditional branch following this conditional branch.
14168 // We need this because we need to reverse the successors in order
14169 // to implement FCMP_OEQ.
14170 if (User->getOpcode() == ISD::BR) {
14171 SDValue FalseBB = User->getOperand(1);
14173 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14174 assert(NewBR == User);
14178 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14179 Chain, Dest, CC, Cmp);
14180 X86::CondCode CCode =
14181 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14182 CCode = X86::GetOppositeBranchCondition(CCode);
14183 CC = DAG.getConstant(CCode, MVT::i8);
14189 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14190 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14191 // It should be transformed during dag combiner except when the condition
14192 // is set by a arithmetics with overflow node.
14193 X86::CondCode CCode =
14194 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14195 CCode = X86::GetOppositeBranchCondition(CCode);
14196 CC = DAG.getConstant(CCode, MVT::i8);
14197 Cond = Cond.getOperand(0).getOperand(1);
14199 } else if (Cond.getOpcode() == ISD::SETCC &&
14200 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14201 // For FCMP_OEQ, we can emit
14202 // two branches instead of an explicit AND instruction with a
14203 // separate test. However, we only do this if this block doesn't
14204 // have a fall-through edge, because this requires an explicit
14205 // jmp when the condition is false.
14206 if (Op.getNode()->hasOneUse()) {
14207 SDNode *User = *Op.getNode()->use_begin();
14208 // Look for an unconditional branch following this conditional branch.
14209 // We need this because we need to reverse the successors in order
14210 // to implement FCMP_OEQ.
14211 if (User->getOpcode() == ISD::BR) {
14212 SDValue FalseBB = User->getOperand(1);
14214 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14215 assert(NewBR == User);
14219 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14220 Cond.getOperand(0), Cond.getOperand(1));
14221 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14222 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14223 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14224 Chain, Dest, CC, Cmp);
14225 CC = DAG.getConstant(X86::COND_P, MVT::i8);
14230 } else if (Cond.getOpcode() == ISD::SETCC &&
14231 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14232 // For FCMP_UNE, we can emit
14233 // two branches instead of an explicit AND instruction with a
14234 // separate test. However, we only do this if this block doesn't
14235 // have a fall-through edge, because this requires an explicit
14236 // jmp when the condition is false.
14237 if (Op.getNode()->hasOneUse()) {
14238 SDNode *User = *Op.getNode()->use_begin();
14239 // Look for an unconditional branch following this conditional branch.
14240 // We need this because we need to reverse the successors in order
14241 // to implement FCMP_UNE.
14242 if (User->getOpcode() == ISD::BR) {
14243 SDValue FalseBB = User->getOperand(1);
14245 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14246 assert(NewBR == User);
14249 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14250 Cond.getOperand(0), Cond.getOperand(1));
14251 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14252 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14253 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14254 Chain, Dest, CC, Cmp);
14255 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14265 // Look pass the truncate if the high bits are known zero.
14266 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14267 Cond = Cond.getOperand(0);
14269 // We know the result of AND is compared against zero. Try to match
14271 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14272 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14273 if (NewSetCC.getNode()) {
14274 CC = NewSetCC.getOperand(0);
14275 Cond = NewSetCC.getOperand(1);
14282 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14283 CC = DAG.getConstant(X86Cond, MVT::i8);
14284 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14286 Cond = ConvertCmpIfNecessary(Cond, DAG);
14287 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14288 Chain, Dest, CC, Cond);
14291 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14292 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14293 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14294 // that the guard pages used by the OS virtual memory manager are allocated in
14295 // correct sequence.
14297 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14298 SelectionDAG &DAG) const {
14299 MachineFunction &MF = DAG.getMachineFunction();
14300 bool SplitStack = MF.shouldSplitStack();
14301 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
14306 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14307 SDNode* Node = Op.getNode();
14309 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14310 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14311 " not tell us which reg is the stack pointer!");
14312 EVT VT = Node->getValueType(0);
14313 SDValue Tmp1 = SDValue(Node, 0);
14314 SDValue Tmp2 = SDValue(Node, 1);
14315 SDValue Tmp3 = Node->getOperand(2);
14316 SDValue Chain = Tmp1.getOperand(0);
14318 // Chain the dynamic stack allocation so that it doesn't modify the stack
14319 // pointer when other instructions are using the stack.
14320 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14323 SDValue Size = Tmp2.getOperand(1);
14324 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14325 Chain = SP.getValue(1);
14326 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14327 const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
14328 unsigned StackAlign = TFI.getStackAlignment();
14329 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14330 if (Align > StackAlign)
14331 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14332 DAG.getConstant(-(uint64_t)Align, VT));
14333 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14335 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14336 DAG.getIntPtrConstant(0, true), SDValue(),
14339 SDValue Ops[2] = { Tmp1, Tmp2 };
14340 return DAG.getMergeValues(Ops, dl);
14344 SDValue Chain = Op.getOperand(0);
14345 SDValue Size = Op.getOperand(1);
14346 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14347 EVT VT = Op.getNode()->getValueType(0);
14349 bool Is64Bit = Subtarget->is64Bit();
14350 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
14353 MachineRegisterInfo &MRI = MF.getRegInfo();
14356 // The 64 bit implementation of segmented stacks needs to clobber both r10
14357 // r11. This makes it impossible to use it along with nested parameters.
14358 const Function *F = MF.getFunction();
14360 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14362 if (I->hasNestAttr())
14363 report_fatal_error("Cannot use segmented stacks with functions that "
14364 "have nested arguments.");
14367 const TargetRegisterClass *AddrRegClass =
14368 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
14369 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14370 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14371 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14372 DAG.getRegister(Vreg, SPTy));
14373 SDValue Ops1[2] = { Value, Chain };
14374 return DAG.getMergeValues(Ops1, dl);
14377 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
14379 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14380 Flag = Chain.getValue(1);
14381 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14383 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14385 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
14386 DAG.getSubtarget().getRegisterInfo());
14387 unsigned SPReg = RegInfo->getStackRegister();
14388 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14389 Chain = SP.getValue(1);
14392 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14393 DAG.getConstant(-(uint64_t)Align, VT));
14394 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14397 SDValue Ops1[2] = { SP, Chain };
14398 return DAG.getMergeValues(Ops1, dl);
14402 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14403 MachineFunction &MF = DAG.getMachineFunction();
14404 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14406 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14409 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14410 // vastart just stores the address of the VarArgsFrameIndex slot into the
14411 // memory location argument.
14412 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14414 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14415 MachinePointerInfo(SV), false, false, 0);
14419 // gp_offset (0 - 6 * 8)
14420 // fp_offset (48 - 48 + 8 * 16)
14421 // overflow_arg_area (point to parameters coming in memory).
14423 SmallVector<SDValue, 8> MemOps;
14424 SDValue FIN = Op.getOperand(1);
14426 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14427 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14429 FIN, MachinePointerInfo(SV), false, false, 0);
14430 MemOps.push_back(Store);
14433 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14434 FIN, DAG.getIntPtrConstant(4));
14435 Store = DAG.getStore(Op.getOperand(0), DL,
14436 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14438 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14439 MemOps.push_back(Store);
14441 // Store ptr to overflow_arg_area
14442 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14443 FIN, DAG.getIntPtrConstant(4));
14444 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14446 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14447 MachinePointerInfo(SV, 8),
14449 MemOps.push_back(Store);
14451 // Store ptr to reg_save_area.
14452 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14453 FIN, DAG.getIntPtrConstant(8));
14454 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14456 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14457 MachinePointerInfo(SV, 16), false, false, 0);
14458 MemOps.push_back(Store);
14459 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14462 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14463 assert(Subtarget->is64Bit() &&
14464 "LowerVAARG only handles 64-bit va_arg!");
14465 assert((Subtarget->isTargetLinux() ||
14466 Subtarget->isTargetDarwin()) &&
14467 "Unhandled target in LowerVAARG");
14468 assert(Op.getNode()->getNumOperands() == 4);
14469 SDValue Chain = Op.getOperand(0);
14470 SDValue SrcPtr = Op.getOperand(1);
14471 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14472 unsigned Align = Op.getConstantOperandVal(3);
14475 EVT ArgVT = Op.getNode()->getValueType(0);
14476 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14477 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14480 // Decide which area this value should be read from.
14481 // TODO: Implement the AMD64 ABI in its entirety. This simple
14482 // selection mechanism works only for the basic types.
14483 if (ArgVT == MVT::f80) {
14484 llvm_unreachable("va_arg for f80 not yet implemented");
14485 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14486 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14487 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14488 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14490 llvm_unreachable("Unhandled argument type in LowerVAARG");
14493 if (ArgMode == 2) {
14494 // Sanity Check: Make sure using fp_offset makes sense.
14495 assert(!DAG.getTarget().Options.UseSoftFloat &&
14496 !(DAG.getMachineFunction()
14497 .getFunction()->getAttributes()
14498 .hasAttribute(AttributeSet::FunctionIndex,
14499 Attribute::NoImplicitFloat)) &&
14500 Subtarget->hasSSE1());
14503 // Insert VAARG_64 node into the DAG
14504 // VAARG_64 returns two values: Variable Argument Address, Chain
14505 SmallVector<SDValue, 11> InstOps;
14506 InstOps.push_back(Chain);
14507 InstOps.push_back(SrcPtr);
14508 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
14509 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
14510 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
14511 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14512 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14513 VTs, InstOps, MVT::i64,
14514 MachinePointerInfo(SV),
14516 /*Volatile=*/false,
14518 /*WriteMem=*/true);
14519 Chain = VAARG.getValue(1);
14521 // Load the next argument and return it
14522 return DAG.getLoad(ArgVT, dl,
14525 MachinePointerInfo(),
14526 false, false, false, 0);
14529 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14530 SelectionDAG &DAG) {
14531 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14532 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14533 SDValue Chain = Op.getOperand(0);
14534 SDValue DstPtr = Op.getOperand(1);
14535 SDValue SrcPtr = Op.getOperand(2);
14536 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14537 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14540 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14541 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14543 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14546 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14547 // amount is a constant. Takes immediate version of shift as input.
14548 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14549 SDValue SrcOp, uint64_t ShiftAmt,
14550 SelectionDAG &DAG) {
14551 MVT ElementType = VT.getVectorElementType();
14553 // Fold this packed shift into its first operand if ShiftAmt is 0.
14557 // Check for ShiftAmt >= element width
14558 if (ShiftAmt >= ElementType.getSizeInBits()) {
14559 if (Opc == X86ISD::VSRAI)
14560 ShiftAmt = ElementType.getSizeInBits() - 1;
14562 return DAG.getConstant(0, VT);
14565 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14566 && "Unknown target vector shift-by-constant node");
14568 // Fold this packed vector shift into a build vector if SrcOp is a
14569 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14570 if (VT == SrcOp.getSimpleValueType() &&
14571 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14572 SmallVector<SDValue, 8> Elts;
14573 unsigned NumElts = SrcOp->getNumOperands();
14574 ConstantSDNode *ND;
14577 default: llvm_unreachable(nullptr);
14578 case X86ISD::VSHLI:
14579 for (unsigned i=0; i!=NumElts; ++i) {
14580 SDValue CurrentOp = SrcOp->getOperand(i);
14581 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14582 Elts.push_back(CurrentOp);
14585 ND = cast<ConstantSDNode>(CurrentOp);
14586 const APInt &C = ND->getAPIntValue();
14587 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14590 case X86ISD::VSRLI:
14591 for (unsigned i=0; i!=NumElts; ++i) {
14592 SDValue CurrentOp = SrcOp->getOperand(i);
14593 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14594 Elts.push_back(CurrentOp);
14597 ND = cast<ConstantSDNode>(CurrentOp);
14598 const APInt &C = ND->getAPIntValue();
14599 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14602 case X86ISD::VSRAI:
14603 for (unsigned i=0; i!=NumElts; ++i) {
14604 SDValue CurrentOp = SrcOp->getOperand(i);
14605 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14606 Elts.push_back(CurrentOp);
14609 ND = cast<ConstantSDNode>(CurrentOp);
14610 const APInt &C = ND->getAPIntValue();
14611 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14616 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14619 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14622 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14623 // may or may not be a constant. Takes immediate version of shift as input.
14624 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14625 SDValue SrcOp, SDValue ShAmt,
14626 SelectionDAG &DAG) {
14627 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14629 // Catch shift-by-constant.
14630 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14631 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14632 CShAmt->getZExtValue(), DAG);
14634 // Change opcode to non-immediate version
14636 default: llvm_unreachable("Unknown target vector shift node");
14637 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14638 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14639 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14642 // Need to build a vector containing shift amount
14643 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14646 ShOps[1] = DAG.getConstant(0, MVT::i32);
14647 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14648 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14650 // The return type has to be a 128-bit type with the same element
14651 // type as the input type.
14652 MVT EltVT = VT.getVectorElementType();
14653 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14655 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14656 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14659 /// \brief Return (vselect \p Mask, \p Op, \p PreservedSrc) along with the
14660 /// necessary casting for \p Mask when lowering masking intrinsics.
14661 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14662 SDValue PreservedSrc, SelectionDAG &DAG) {
14663 EVT VT = Op.getValueType();
14664 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14665 MVT::i1, VT.getVectorNumElements());
14668 assert(MaskVT.isSimple() && "invalid mask type");
14669 return DAG.getNode(ISD::VSELECT, dl, VT,
14670 DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask),
14674 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
14676 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14677 case Intrinsic::x86_fma_vfmadd_ps:
14678 case Intrinsic::x86_fma_vfmadd_pd:
14679 case Intrinsic::x86_fma_vfmadd_ps_256:
14680 case Intrinsic::x86_fma_vfmadd_pd_256:
14681 case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14682 case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14683 return X86ISD::FMADD;
14684 case Intrinsic::x86_fma_vfmsub_ps:
14685 case Intrinsic::x86_fma_vfmsub_pd:
14686 case Intrinsic::x86_fma_vfmsub_ps_256:
14687 case Intrinsic::x86_fma_vfmsub_pd_256:
14688 case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14689 case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14690 return X86ISD::FMSUB;
14691 case Intrinsic::x86_fma_vfnmadd_ps:
14692 case Intrinsic::x86_fma_vfnmadd_pd:
14693 case Intrinsic::x86_fma_vfnmadd_ps_256:
14694 case Intrinsic::x86_fma_vfnmadd_pd_256:
14695 case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14696 case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14697 return X86ISD::FNMADD;
14698 case Intrinsic::x86_fma_vfnmsub_ps:
14699 case Intrinsic::x86_fma_vfnmsub_pd:
14700 case Intrinsic::x86_fma_vfnmsub_ps_256:
14701 case Intrinsic::x86_fma_vfnmsub_pd_256:
14702 case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14703 case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14704 return X86ISD::FNMSUB;
14705 case Intrinsic::x86_fma_vfmaddsub_ps:
14706 case Intrinsic::x86_fma_vfmaddsub_pd:
14707 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14708 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14709 case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14710 case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14711 return X86ISD::FMADDSUB;
14712 case Intrinsic::x86_fma_vfmsubadd_ps:
14713 case Intrinsic::x86_fma_vfmsubadd_pd:
14714 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14715 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14716 case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14717 case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
14718 return X86ISD::FMSUBADD;
14722 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14724 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14726 const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14728 switch(IntrData->Type) {
14729 case INTR_TYPE_1OP:
14730 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14731 case INTR_TYPE_2OP:
14732 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14734 case INTR_TYPE_3OP:
14735 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14736 Op.getOperand(2), Op.getOperand(3));
14737 case COMI: { // Comparison intrinsics
14738 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14739 SDValue LHS = Op.getOperand(1);
14740 SDValue RHS = Op.getOperand(2);
14741 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14742 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14743 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14744 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14745 DAG.getConstant(X86CC, MVT::i8), Cond);
14746 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14749 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14750 Op.getOperand(1), Op.getOperand(2), DAG);
14757 default: return SDValue(); // Don't custom lower most intrinsics.
14759 // Arithmetic intrinsics.
14760 case Intrinsic::x86_sse2_pmulu_dq:
14761 case Intrinsic::x86_avx2_pmulu_dq:
14762 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14763 Op.getOperand(1), Op.getOperand(2));
14765 case Intrinsic::x86_sse41_pmuldq:
14766 case Intrinsic::x86_avx2_pmul_dq:
14767 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14768 Op.getOperand(1), Op.getOperand(2));
14770 case Intrinsic::x86_sse2_pmulhu_w:
14771 case Intrinsic::x86_avx2_pmulhu_w:
14772 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14773 Op.getOperand(1), Op.getOperand(2));
14775 case Intrinsic::x86_sse2_pmulh_w:
14776 case Intrinsic::x86_avx2_pmulh_w:
14777 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14778 Op.getOperand(1), Op.getOperand(2));
14780 // SSE/SSE2/AVX floating point max/min intrinsics.
14781 case Intrinsic::x86_sse_max_ps:
14782 case Intrinsic::x86_sse2_max_pd:
14783 case Intrinsic::x86_avx_max_ps_256:
14784 case Intrinsic::x86_avx_max_pd_256:
14785 case Intrinsic::x86_sse_min_ps:
14786 case Intrinsic::x86_sse2_min_pd:
14787 case Intrinsic::x86_avx_min_ps_256:
14788 case Intrinsic::x86_avx_min_pd_256: {
14791 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14792 case Intrinsic::x86_sse_max_ps:
14793 case Intrinsic::x86_sse2_max_pd:
14794 case Intrinsic::x86_avx_max_ps_256:
14795 case Intrinsic::x86_avx_max_pd_256:
14796 Opcode = X86ISD::FMAX;
14798 case Intrinsic::x86_sse_min_ps:
14799 case Intrinsic::x86_sse2_min_pd:
14800 case Intrinsic::x86_avx_min_ps_256:
14801 case Intrinsic::x86_avx_min_pd_256:
14802 Opcode = X86ISD::FMIN;
14805 return DAG.getNode(Opcode, dl, Op.getValueType(),
14806 Op.getOperand(1), Op.getOperand(2));
14809 // AVX2 variable shift intrinsics
14810 case Intrinsic::x86_avx2_psllv_d:
14811 case Intrinsic::x86_avx2_psllv_q:
14812 case Intrinsic::x86_avx2_psllv_d_256:
14813 case Intrinsic::x86_avx2_psllv_q_256:
14814 case Intrinsic::x86_avx2_psrlv_d:
14815 case Intrinsic::x86_avx2_psrlv_q:
14816 case Intrinsic::x86_avx2_psrlv_d_256:
14817 case Intrinsic::x86_avx2_psrlv_q_256:
14818 case Intrinsic::x86_avx2_psrav_d:
14819 case Intrinsic::x86_avx2_psrav_d_256: {
14822 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14823 case Intrinsic::x86_avx2_psllv_d:
14824 case Intrinsic::x86_avx2_psllv_q:
14825 case Intrinsic::x86_avx2_psllv_d_256:
14826 case Intrinsic::x86_avx2_psllv_q_256:
14829 case Intrinsic::x86_avx2_psrlv_d:
14830 case Intrinsic::x86_avx2_psrlv_q:
14831 case Intrinsic::x86_avx2_psrlv_d_256:
14832 case Intrinsic::x86_avx2_psrlv_q_256:
14835 case Intrinsic::x86_avx2_psrav_d:
14836 case Intrinsic::x86_avx2_psrav_d_256:
14840 return DAG.getNode(Opcode, dl, Op.getValueType(),
14841 Op.getOperand(1), Op.getOperand(2));
14844 case Intrinsic::x86_sse2_packssdw_128:
14845 case Intrinsic::x86_sse2_packsswb_128:
14846 case Intrinsic::x86_avx2_packssdw:
14847 case Intrinsic::x86_avx2_packsswb:
14848 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14849 Op.getOperand(1), Op.getOperand(2));
14851 case Intrinsic::x86_sse2_packuswb_128:
14852 case Intrinsic::x86_sse41_packusdw:
14853 case Intrinsic::x86_avx2_packuswb:
14854 case Intrinsic::x86_avx2_packusdw:
14855 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14856 Op.getOperand(1), Op.getOperand(2));
14858 case Intrinsic::x86_ssse3_pshuf_b_128:
14859 case Intrinsic::x86_avx2_pshuf_b:
14860 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14861 Op.getOperand(1), Op.getOperand(2));
14863 case Intrinsic::x86_sse2_pshuf_d:
14864 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14865 Op.getOperand(1), Op.getOperand(2));
14867 case Intrinsic::x86_sse2_pshufl_w:
14868 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14869 Op.getOperand(1), Op.getOperand(2));
14871 case Intrinsic::x86_sse2_pshufh_w:
14872 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14873 Op.getOperand(1), Op.getOperand(2));
14875 case Intrinsic::x86_ssse3_psign_b_128:
14876 case Intrinsic::x86_ssse3_psign_w_128:
14877 case Intrinsic::x86_ssse3_psign_d_128:
14878 case Intrinsic::x86_avx2_psign_b:
14879 case Intrinsic::x86_avx2_psign_w:
14880 case Intrinsic::x86_avx2_psign_d:
14881 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14882 Op.getOperand(1), Op.getOperand(2));
14884 case Intrinsic::x86_avx2_permd:
14885 case Intrinsic::x86_avx2_permps:
14886 // Operands intentionally swapped. Mask is last operand to intrinsic,
14887 // but second operand for node/instruction.
14888 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14889 Op.getOperand(2), Op.getOperand(1));
14891 case Intrinsic::x86_avx512_mask_valign_q_512:
14892 case Intrinsic::x86_avx512_mask_valign_d_512:
14893 // Vector source operands are swapped.
14894 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14895 Op.getValueType(), Op.getOperand(2),
14898 Op.getOperand(5), Op.getOperand(4), DAG);
14900 // ptest and testp intrinsics. The intrinsic these come from are designed to
14901 // return an integer value, not just an instruction so lower it to the ptest
14902 // or testp pattern and a setcc for the result.
14903 case Intrinsic::x86_sse41_ptestz:
14904 case Intrinsic::x86_sse41_ptestc:
14905 case Intrinsic::x86_sse41_ptestnzc:
14906 case Intrinsic::x86_avx_ptestz_256:
14907 case Intrinsic::x86_avx_ptestc_256:
14908 case Intrinsic::x86_avx_ptestnzc_256:
14909 case Intrinsic::x86_avx_vtestz_ps:
14910 case Intrinsic::x86_avx_vtestc_ps:
14911 case Intrinsic::x86_avx_vtestnzc_ps:
14912 case Intrinsic::x86_avx_vtestz_pd:
14913 case Intrinsic::x86_avx_vtestc_pd:
14914 case Intrinsic::x86_avx_vtestnzc_pd:
14915 case Intrinsic::x86_avx_vtestz_ps_256:
14916 case Intrinsic::x86_avx_vtestc_ps_256:
14917 case Intrinsic::x86_avx_vtestnzc_ps_256:
14918 case Intrinsic::x86_avx_vtestz_pd_256:
14919 case Intrinsic::x86_avx_vtestc_pd_256:
14920 case Intrinsic::x86_avx_vtestnzc_pd_256: {
14921 bool IsTestPacked = false;
14924 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14925 case Intrinsic::x86_avx_vtestz_ps:
14926 case Intrinsic::x86_avx_vtestz_pd:
14927 case Intrinsic::x86_avx_vtestz_ps_256:
14928 case Intrinsic::x86_avx_vtestz_pd_256:
14929 IsTestPacked = true; // Fallthrough
14930 case Intrinsic::x86_sse41_ptestz:
14931 case Intrinsic::x86_avx_ptestz_256:
14933 X86CC = X86::COND_E;
14935 case Intrinsic::x86_avx_vtestc_ps:
14936 case Intrinsic::x86_avx_vtestc_pd:
14937 case Intrinsic::x86_avx_vtestc_ps_256:
14938 case Intrinsic::x86_avx_vtestc_pd_256:
14939 IsTestPacked = true; // Fallthrough
14940 case Intrinsic::x86_sse41_ptestc:
14941 case Intrinsic::x86_avx_ptestc_256:
14943 X86CC = X86::COND_B;
14945 case Intrinsic::x86_avx_vtestnzc_ps:
14946 case Intrinsic::x86_avx_vtestnzc_pd:
14947 case Intrinsic::x86_avx_vtestnzc_ps_256:
14948 case Intrinsic::x86_avx_vtestnzc_pd_256:
14949 IsTestPacked = true; // Fallthrough
14950 case Intrinsic::x86_sse41_ptestnzc:
14951 case Intrinsic::x86_avx_ptestnzc_256:
14953 X86CC = X86::COND_A;
14957 SDValue LHS = Op.getOperand(1);
14958 SDValue RHS = Op.getOperand(2);
14959 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14960 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14961 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14962 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14963 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14965 case Intrinsic::x86_avx512_kortestz_w:
14966 case Intrinsic::x86_avx512_kortestc_w: {
14967 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14968 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14969 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14970 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14971 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14972 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14973 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14976 case Intrinsic::x86_sse42_pcmpistria128:
14977 case Intrinsic::x86_sse42_pcmpestria128:
14978 case Intrinsic::x86_sse42_pcmpistric128:
14979 case Intrinsic::x86_sse42_pcmpestric128:
14980 case Intrinsic::x86_sse42_pcmpistrio128:
14981 case Intrinsic::x86_sse42_pcmpestrio128:
14982 case Intrinsic::x86_sse42_pcmpistris128:
14983 case Intrinsic::x86_sse42_pcmpestris128:
14984 case Intrinsic::x86_sse42_pcmpistriz128:
14985 case Intrinsic::x86_sse42_pcmpestriz128: {
14989 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14990 case Intrinsic::x86_sse42_pcmpistria128:
14991 Opcode = X86ISD::PCMPISTRI;
14992 X86CC = X86::COND_A;
14994 case Intrinsic::x86_sse42_pcmpestria128:
14995 Opcode = X86ISD::PCMPESTRI;
14996 X86CC = X86::COND_A;
14998 case Intrinsic::x86_sse42_pcmpistric128:
14999 Opcode = X86ISD::PCMPISTRI;
15000 X86CC = X86::COND_B;
15002 case Intrinsic::x86_sse42_pcmpestric128:
15003 Opcode = X86ISD::PCMPESTRI;
15004 X86CC = X86::COND_B;
15006 case Intrinsic::x86_sse42_pcmpistrio128:
15007 Opcode = X86ISD::PCMPISTRI;
15008 X86CC = X86::COND_O;
15010 case Intrinsic::x86_sse42_pcmpestrio128:
15011 Opcode = X86ISD::PCMPESTRI;
15012 X86CC = X86::COND_O;
15014 case Intrinsic::x86_sse42_pcmpistris128:
15015 Opcode = X86ISD::PCMPISTRI;
15016 X86CC = X86::COND_S;
15018 case Intrinsic::x86_sse42_pcmpestris128:
15019 Opcode = X86ISD::PCMPESTRI;
15020 X86CC = X86::COND_S;
15022 case Intrinsic::x86_sse42_pcmpistriz128:
15023 Opcode = X86ISD::PCMPISTRI;
15024 X86CC = X86::COND_E;
15026 case Intrinsic::x86_sse42_pcmpestriz128:
15027 Opcode = X86ISD::PCMPESTRI;
15028 X86CC = X86::COND_E;
15031 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15032 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15033 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15034 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15035 DAG.getConstant(X86CC, MVT::i8),
15036 SDValue(PCMP.getNode(), 1));
15037 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15040 case Intrinsic::x86_sse42_pcmpistri128:
15041 case Intrinsic::x86_sse42_pcmpestri128: {
15043 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15044 Opcode = X86ISD::PCMPISTRI;
15046 Opcode = X86ISD::PCMPESTRI;
15048 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15049 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15050 return DAG.getNode(Opcode, dl, VTs, NewOps);
15053 case Intrinsic::x86_fma_mask_vfmadd_ps_512:
15054 case Intrinsic::x86_fma_mask_vfmadd_pd_512:
15055 case Intrinsic::x86_fma_mask_vfmsub_ps_512:
15056 case Intrinsic::x86_fma_mask_vfmsub_pd_512:
15057 case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
15058 case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
15059 case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
15060 case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
15061 case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
15062 case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
15063 case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
15064 case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
15065 auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
15066 if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
15067 return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
15068 dl, Op.getValueType(),
15072 Op.getOperand(4), Op.getOperand(1), DAG);
15077 case Intrinsic::x86_fma_vfmadd_ps:
15078 case Intrinsic::x86_fma_vfmadd_pd:
15079 case Intrinsic::x86_fma_vfmsub_ps:
15080 case Intrinsic::x86_fma_vfmsub_pd:
15081 case Intrinsic::x86_fma_vfnmadd_ps:
15082 case Intrinsic::x86_fma_vfnmadd_pd:
15083 case Intrinsic::x86_fma_vfnmsub_ps:
15084 case Intrinsic::x86_fma_vfnmsub_pd:
15085 case Intrinsic::x86_fma_vfmaddsub_ps:
15086 case Intrinsic::x86_fma_vfmaddsub_pd:
15087 case Intrinsic::x86_fma_vfmsubadd_ps:
15088 case Intrinsic::x86_fma_vfmsubadd_pd:
15089 case Intrinsic::x86_fma_vfmadd_ps_256:
15090 case Intrinsic::x86_fma_vfmadd_pd_256:
15091 case Intrinsic::x86_fma_vfmsub_ps_256:
15092 case Intrinsic::x86_fma_vfmsub_pd_256:
15093 case Intrinsic::x86_fma_vfnmadd_ps_256:
15094 case Intrinsic::x86_fma_vfnmadd_pd_256:
15095 case Intrinsic::x86_fma_vfnmsub_ps_256:
15096 case Intrinsic::x86_fma_vfnmsub_pd_256:
15097 case Intrinsic::x86_fma_vfmaddsub_ps_256:
15098 case Intrinsic::x86_fma_vfmaddsub_pd_256:
15099 case Intrinsic::x86_fma_vfmsubadd_ps_256:
15100 case Intrinsic::x86_fma_vfmsubadd_pd_256:
15101 return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
15102 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
15106 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15107 SDValue Src, SDValue Mask, SDValue Base,
15108 SDValue Index, SDValue ScaleOp, SDValue Chain,
15109 const X86Subtarget * Subtarget) {
15111 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15112 assert(C && "Invalid scale type");
15113 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15114 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15115 Index.getSimpleValueType().getVectorNumElements());
15117 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15119 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15121 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15122 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15123 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15124 SDValue Segment = DAG.getRegister(0, MVT::i32);
15125 if (Src.getOpcode() == ISD::UNDEF)
15126 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15127 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15128 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15129 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15130 return DAG.getMergeValues(RetOps, dl);
15133 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15134 SDValue Src, SDValue Mask, SDValue Base,
15135 SDValue Index, SDValue ScaleOp, SDValue Chain) {
15137 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15138 assert(C && "Invalid scale type");
15139 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15140 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15141 SDValue Segment = DAG.getRegister(0, MVT::i32);
15142 EVT MaskVT = MVT::getVectorVT(MVT::i1,
15143 Index.getSimpleValueType().getVectorNumElements());
15145 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15147 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15149 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15150 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15151 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15152 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15153 return SDValue(Res, 1);
15156 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15157 SDValue Mask, SDValue Base, SDValue Index,
15158 SDValue ScaleOp, SDValue Chain) {
15160 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15161 assert(C && "Invalid scale type");
15162 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15163 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15164 SDValue Segment = DAG.getRegister(0, MVT::i32);
15166 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15168 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15170 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15172 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15173 //SDVTList VTs = DAG.getVTList(MVT::Other);
15174 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15175 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15176 return SDValue(Res, 0);
15179 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15180 // read performance monitor counters (x86_rdpmc).
15181 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15182 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15183 SmallVectorImpl<SDValue> &Results) {
15184 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15185 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15188 // The ECX register is used to select the index of the performance counter
15190 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15192 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15194 // Reads the content of a 64-bit performance counter and returns it in the
15195 // registers EDX:EAX.
15196 if (Subtarget->is64Bit()) {
15197 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15198 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15201 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15202 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15205 Chain = HI.getValue(1);
15207 if (Subtarget->is64Bit()) {
15208 // The EAX register is loaded with the low-order 32 bits. The EDX register
15209 // is loaded with the supported high-order bits of the counter.
15210 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15211 DAG.getConstant(32, MVT::i8));
15212 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15213 Results.push_back(Chain);
15217 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15218 SDValue Ops[] = { LO, HI };
15219 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15220 Results.push_back(Pair);
15221 Results.push_back(Chain);
15224 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15225 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15226 // also used to custom lower READCYCLECOUNTER nodes.
15227 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15228 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15229 SmallVectorImpl<SDValue> &Results) {
15230 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15231 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15234 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15235 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15236 // and the EAX register is loaded with the low-order 32 bits.
15237 if (Subtarget->is64Bit()) {
15238 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15239 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15242 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15243 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15246 SDValue Chain = HI.getValue(1);
15248 if (Opcode == X86ISD::RDTSCP_DAG) {
15249 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15251 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15252 // the ECX register. Add 'ecx' explicitly to the chain.
15253 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15255 // Explicitly store the content of ECX at the location passed in input
15256 // to the 'rdtscp' intrinsic.
15257 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15258 MachinePointerInfo(), false, false, 0);
15261 if (Subtarget->is64Bit()) {
15262 // The EDX register is loaded with the high-order 32 bits of the MSR, and
15263 // the EAX register is loaded with the low-order 32 bits.
15264 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15265 DAG.getConstant(32, MVT::i8));
15266 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15267 Results.push_back(Chain);
15271 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15272 SDValue Ops[] = { LO, HI };
15273 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15274 Results.push_back(Pair);
15275 Results.push_back(Chain);
15278 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15279 SelectionDAG &DAG) {
15280 SmallVector<SDValue, 2> Results;
15282 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15284 return DAG.getMergeValues(Results, DL);
15288 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15289 SelectionDAG &DAG) {
15290 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15292 const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15297 switch(IntrData->Type) {
15299 llvm_unreachable("Unknown Intrinsic Type");
15303 // Emit the node with the right value type.
15304 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15305 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15307 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15308 // Otherwise return the value from Rand, which is always 0, casted to i32.
15309 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15310 DAG.getConstant(1, Op->getValueType(1)),
15311 DAG.getConstant(X86::COND_B, MVT::i32),
15312 SDValue(Result.getNode(), 1) };
15313 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15314 DAG.getVTList(Op->getValueType(1), MVT::Glue),
15317 // Return { result, isValid, chain }.
15318 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15319 SDValue(Result.getNode(), 2));
15322 //gather(v1, mask, index, base, scale);
15323 SDValue Chain = Op.getOperand(0);
15324 SDValue Src = Op.getOperand(2);
15325 SDValue Base = Op.getOperand(3);
15326 SDValue Index = Op.getOperand(4);
15327 SDValue Mask = Op.getOperand(5);
15328 SDValue Scale = Op.getOperand(6);
15329 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15333 //scatter(base, mask, index, v1, scale);
15334 SDValue Chain = Op.getOperand(0);
15335 SDValue Base = Op.getOperand(2);
15336 SDValue Mask = Op.getOperand(3);
15337 SDValue Index = Op.getOperand(4);
15338 SDValue Src = Op.getOperand(5);
15339 SDValue Scale = Op.getOperand(6);
15340 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15343 SDValue Hint = Op.getOperand(6);
15345 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15346 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15347 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15348 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15349 SDValue Chain = Op.getOperand(0);
15350 SDValue Mask = Op.getOperand(2);
15351 SDValue Index = Op.getOperand(3);
15352 SDValue Base = Op.getOperand(4);
15353 SDValue Scale = Op.getOperand(5);
15354 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15356 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15358 SmallVector<SDValue, 2> Results;
15359 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15360 return DAG.getMergeValues(Results, dl);
15362 // Read Performance Monitoring Counters.
15364 SmallVector<SDValue, 2> Results;
15365 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15366 return DAG.getMergeValues(Results, dl);
15368 // XTEST intrinsics.
15370 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15371 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15372 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15373 DAG.getConstant(X86::COND_NE, MVT::i8),
15375 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15376 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15377 Ret, SDValue(InTrans.getNode(), 1));
15381 SmallVector<SDValue, 2> Results;
15382 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15383 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15384 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15385 DAG.getConstant(-1, MVT::i8));
15386 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15387 Op.getOperand(4), GenCF.getValue(1));
15388 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15389 Op.getOperand(5), MachinePointerInfo(),
15391 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15392 DAG.getConstant(X86::COND_B, MVT::i8),
15394 Results.push_back(SetCC);
15395 Results.push_back(Store);
15396 return DAG.getMergeValues(Results, dl);
15401 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15402 SelectionDAG &DAG) const {
15403 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15404 MFI->setReturnAddressIsTaken(true);
15406 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15409 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15411 EVT PtrVT = getPointerTy();
15414 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15415 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15416 DAG.getSubtarget().getRegisterInfo());
15417 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15418 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15419 DAG.getNode(ISD::ADD, dl, PtrVT,
15420 FrameAddr, Offset),
15421 MachinePointerInfo(), false, false, false, 0);
15424 // Just load the return address.
15425 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15426 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15427 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15430 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15431 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15432 MFI->setFrameAddressIsTaken(true);
15434 EVT VT = Op.getValueType();
15435 SDLoc dl(Op); // FIXME probably not meaningful
15436 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15437 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15438 DAG.getSubtarget().getRegisterInfo());
15439 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15440 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15441 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15442 "Invalid Frame Register!");
15443 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15445 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15446 MachinePointerInfo(),
15447 false, false, false, 0);
15451 // FIXME? Maybe this could be a TableGen attribute on some registers and
15452 // this table could be generated automatically from RegInfo.
15453 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15455 unsigned Reg = StringSwitch<unsigned>(RegName)
15456 .Case("esp", X86::ESP)
15457 .Case("rsp", X86::RSP)
15461 report_fatal_error("Invalid register name global variable");
15464 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15465 SelectionDAG &DAG) const {
15466 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15467 DAG.getSubtarget().getRegisterInfo());
15468 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15471 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15472 SDValue Chain = Op.getOperand(0);
15473 SDValue Offset = Op.getOperand(1);
15474 SDValue Handler = Op.getOperand(2);
15477 EVT PtrVT = getPointerTy();
15478 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15479 DAG.getSubtarget().getRegisterInfo());
15480 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15481 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15482 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15483 "Invalid Frame Register!");
15484 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15485 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15487 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15488 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15489 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15490 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15492 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15494 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15495 DAG.getRegister(StoreAddrReg, PtrVT));
15498 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15499 SelectionDAG &DAG) const {
15501 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15502 DAG.getVTList(MVT::i32, MVT::Other),
15503 Op.getOperand(0), Op.getOperand(1));
15506 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15507 SelectionDAG &DAG) const {
15509 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15510 Op.getOperand(0), Op.getOperand(1));
15513 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15514 return Op.getOperand(0);
15517 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15518 SelectionDAG &DAG) const {
15519 SDValue Root = Op.getOperand(0);
15520 SDValue Trmp = Op.getOperand(1); // trampoline
15521 SDValue FPtr = Op.getOperand(2); // nested function
15522 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15525 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15526 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15528 if (Subtarget->is64Bit()) {
15529 SDValue OutChains[6];
15531 // Large code-model.
15532 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15533 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15535 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15536 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15538 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15540 // Load the pointer to the nested function into R11.
15541 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15542 SDValue Addr = Trmp;
15543 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15544 Addr, MachinePointerInfo(TrmpAddr),
15547 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15548 DAG.getConstant(2, MVT::i64));
15549 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15550 MachinePointerInfo(TrmpAddr, 2),
15553 // Load the 'nest' parameter value into R10.
15554 // R10 is specified in X86CallingConv.td
15555 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15556 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15557 DAG.getConstant(10, MVT::i64));
15558 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15559 Addr, MachinePointerInfo(TrmpAddr, 10),
15562 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15563 DAG.getConstant(12, MVT::i64));
15564 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15565 MachinePointerInfo(TrmpAddr, 12),
15568 // Jump to the nested function.
15569 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15570 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15571 DAG.getConstant(20, MVT::i64));
15572 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15573 Addr, MachinePointerInfo(TrmpAddr, 20),
15576 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15577 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15578 DAG.getConstant(22, MVT::i64));
15579 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15580 MachinePointerInfo(TrmpAddr, 22),
15583 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15585 const Function *Func =
15586 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15587 CallingConv::ID CC = Func->getCallingConv();
15592 llvm_unreachable("Unsupported calling convention");
15593 case CallingConv::C:
15594 case CallingConv::X86_StdCall: {
15595 // Pass 'nest' parameter in ECX.
15596 // Must be kept in sync with X86CallingConv.td
15597 NestReg = X86::ECX;
15599 // Check that ECX wasn't needed by an 'inreg' parameter.
15600 FunctionType *FTy = Func->getFunctionType();
15601 const AttributeSet &Attrs = Func->getAttributes();
15603 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15604 unsigned InRegCount = 0;
15607 for (FunctionType::param_iterator I = FTy->param_begin(),
15608 E = FTy->param_end(); I != E; ++I, ++Idx)
15609 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15610 // FIXME: should only count parameters that are lowered to integers.
15611 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15613 if (InRegCount > 2) {
15614 report_fatal_error("Nest register in use - reduce number of inreg"
15620 case CallingConv::X86_FastCall:
15621 case CallingConv::X86_ThisCall:
15622 case CallingConv::Fast:
15623 // Pass 'nest' parameter in EAX.
15624 // Must be kept in sync with X86CallingConv.td
15625 NestReg = X86::EAX;
15629 SDValue OutChains[4];
15630 SDValue Addr, Disp;
15632 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15633 DAG.getConstant(10, MVT::i32));
15634 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15636 // This is storing the opcode for MOV32ri.
15637 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15638 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15639 OutChains[0] = DAG.getStore(Root, dl,
15640 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15641 Trmp, MachinePointerInfo(TrmpAddr),
15644 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15645 DAG.getConstant(1, MVT::i32));
15646 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15647 MachinePointerInfo(TrmpAddr, 1),
15650 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15651 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15652 DAG.getConstant(5, MVT::i32));
15653 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15654 MachinePointerInfo(TrmpAddr, 5),
15657 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15658 DAG.getConstant(6, MVT::i32));
15659 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15660 MachinePointerInfo(TrmpAddr, 6),
15663 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15667 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15668 SelectionDAG &DAG) const {
15670 The rounding mode is in bits 11:10 of FPSR, and has the following
15672 00 Round to nearest
15677 FLT_ROUNDS, on the other hand, expects the following:
15684 To perform the conversion, we do:
15685 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15688 MachineFunction &MF = DAG.getMachineFunction();
15689 const TargetMachine &TM = MF.getTarget();
15690 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15691 unsigned StackAlignment = TFI.getStackAlignment();
15692 MVT VT = Op.getSimpleValueType();
15695 // Save FP Control Word to stack slot
15696 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15697 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15699 MachineMemOperand *MMO =
15700 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15701 MachineMemOperand::MOStore, 2, 2);
15703 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15704 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15705 DAG.getVTList(MVT::Other),
15706 Ops, MVT::i16, MMO);
15708 // Load FP Control Word from stack slot
15709 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15710 MachinePointerInfo(), false, false, false, 0);
15712 // Transform as necessary
15714 DAG.getNode(ISD::SRL, DL, MVT::i16,
15715 DAG.getNode(ISD::AND, DL, MVT::i16,
15716 CWD, DAG.getConstant(0x800, MVT::i16)),
15717 DAG.getConstant(11, MVT::i8));
15719 DAG.getNode(ISD::SRL, DL, MVT::i16,
15720 DAG.getNode(ISD::AND, DL, MVT::i16,
15721 CWD, DAG.getConstant(0x400, MVT::i16)),
15722 DAG.getConstant(9, MVT::i8));
15725 DAG.getNode(ISD::AND, DL, MVT::i16,
15726 DAG.getNode(ISD::ADD, DL, MVT::i16,
15727 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15728 DAG.getConstant(1, MVT::i16)),
15729 DAG.getConstant(3, MVT::i16));
15731 return DAG.getNode((VT.getSizeInBits() < 16 ?
15732 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15735 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15736 MVT VT = Op.getSimpleValueType();
15738 unsigned NumBits = VT.getSizeInBits();
15741 Op = Op.getOperand(0);
15742 if (VT == MVT::i8) {
15743 // Zero extend to i32 since there is not an i8 bsr.
15745 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15748 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15749 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15750 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15752 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15755 DAG.getConstant(NumBits+NumBits-1, OpVT),
15756 DAG.getConstant(X86::COND_E, MVT::i8),
15759 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15761 // Finally xor with NumBits-1.
15762 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15765 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15769 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15770 MVT VT = Op.getSimpleValueType();
15772 unsigned NumBits = VT.getSizeInBits();
15775 Op = Op.getOperand(0);
15776 if (VT == MVT::i8) {
15777 // Zero extend to i32 since there is not an i8 bsr.
15779 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15782 // Issue a bsr (scan bits in reverse).
15783 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15784 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15786 // And xor with NumBits-1.
15787 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15790 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15794 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15795 MVT VT = Op.getSimpleValueType();
15796 unsigned NumBits = VT.getSizeInBits();
15798 Op = Op.getOperand(0);
15800 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15801 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15802 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15804 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15807 DAG.getConstant(NumBits, VT),
15808 DAG.getConstant(X86::COND_E, MVT::i8),
15811 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15814 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15815 // ones, and then concatenate the result back.
15816 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15817 MVT VT = Op.getSimpleValueType();
15819 assert(VT.is256BitVector() && VT.isInteger() &&
15820 "Unsupported value type for operation");
15822 unsigned NumElems = VT.getVectorNumElements();
15825 // Extract the LHS vectors
15826 SDValue LHS = Op.getOperand(0);
15827 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15828 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15830 // Extract the RHS vectors
15831 SDValue RHS = Op.getOperand(1);
15832 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15833 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15835 MVT EltVT = VT.getVectorElementType();
15836 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15838 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15839 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15840 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15843 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15844 assert(Op.getSimpleValueType().is256BitVector() &&
15845 Op.getSimpleValueType().isInteger() &&
15846 "Only handle AVX 256-bit vector integer operation");
15847 return Lower256IntArith(Op, DAG);
15850 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15851 assert(Op.getSimpleValueType().is256BitVector() &&
15852 Op.getSimpleValueType().isInteger() &&
15853 "Only handle AVX 256-bit vector integer operation");
15854 return Lower256IntArith(Op, DAG);
15857 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15858 SelectionDAG &DAG) {
15860 MVT VT = Op.getSimpleValueType();
15862 // Decompose 256-bit ops into smaller 128-bit ops.
15863 if (VT.is256BitVector() && !Subtarget->hasInt256())
15864 return Lower256IntArith(Op, DAG);
15866 SDValue A = Op.getOperand(0);
15867 SDValue B = Op.getOperand(1);
15869 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15870 if (VT == MVT::v4i32) {
15871 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15872 "Should not custom lower when pmuldq is available!");
15874 // Extract the odd parts.
15875 static const int UnpackMask[] = { 1, -1, 3, -1 };
15876 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15877 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15879 // Multiply the even parts.
15880 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15881 // Now multiply odd parts.
15882 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15884 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15885 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15887 // Merge the two vectors back together with a shuffle. This expands into 2
15889 static const int ShufMask[] = { 0, 4, 2, 6 };
15890 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15893 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15894 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15896 // Ahi = psrlqi(a, 32);
15897 // Bhi = psrlqi(b, 32);
15899 // AloBlo = pmuludq(a, b);
15900 // AloBhi = pmuludq(a, Bhi);
15901 // AhiBlo = pmuludq(Ahi, b);
15903 // AloBhi = psllqi(AloBhi, 32);
15904 // AhiBlo = psllqi(AhiBlo, 32);
15905 // return AloBlo + AloBhi + AhiBlo;
15907 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15908 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15910 // Bit cast to 32-bit vectors for MULUDQ
15911 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15912 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15913 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15914 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15915 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15916 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15918 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15919 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15920 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15922 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15923 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15925 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15926 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15929 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15930 assert(Subtarget->isTargetWin64() && "Unexpected target");
15931 EVT VT = Op.getValueType();
15932 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15933 "Unexpected return type for lowering");
15937 switch (Op->getOpcode()) {
15938 default: llvm_unreachable("Unexpected request for libcall!");
15939 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15940 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15941 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15942 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15943 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15944 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15948 SDValue InChain = DAG.getEntryNode();
15950 TargetLowering::ArgListTy Args;
15951 TargetLowering::ArgListEntry Entry;
15952 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15953 EVT ArgVT = Op->getOperand(i).getValueType();
15954 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15955 "Unexpected argument type for lowering");
15956 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15957 Entry.Node = StackPtr;
15958 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15960 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15961 Entry.Ty = PointerType::get(ArgTy,0);
15962 Entry.isSExt = false;
15963 Entry.isZExt = false;
15964 Args.push_back(Entry);
15967 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15970 TargetLowering::CallLoweringInfo CLI(DAG);
15971 CLI.setDebugLoc(dl).setChain(InChain)
15972 .setCallee(getLibcallCallingConv(LC),
15973 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15974 Callee, std::move(Args), 0)
15975 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15977 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15978 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15981 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15982 SelectionDAG &DAG) {
15983 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15984 EVT VT = Op0.getValueType();
15987 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15988 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15990 // PMULxD operations multiply each even value (starting at 0) of LHS with
15991 // the related value of RHS and produce a widen result.
15992 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15993 // => <2 x i64> <ae|cg>
15995 // In other word, to have all the results, we need to perform two PMULxD:
15996 // 1. one with the even values.
15997 // 2. one with the odd values.
15998 // To achieve #2, with need to place the odd values at an even position.
16000 // Place the odd value at an even position (basically, shift all values 1
16001 // step to the left):
16002 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16003 // <a|b|c|d> => <b|undef|d|undef>
16004 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16005 // <e|f|g|h> => <f|undef|h|undef>
16006 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16008 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16010 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16011 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16013 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16014 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16015 // => <2 x i64> <ae|cg>
16016 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16017 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16018 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16019 // => <2 x i64> <bf|dh>
16020 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16021 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16023 // Shuffle it back into the right order.
16024 SDValue Highs, Lows;
16025 if (VT == MVT::v8i32) {
16026 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16027 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16028 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16029 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16031 const int HighMask[] = {1, 5, 3, 7};
16032 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16033 const int LowMask[] = {0, 4, 2, 6};
16034 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16037 // If we have a signed multiply but no PMULDQ fix up the high parts of a
16038 // unsigned multiply.
16039 if (IsSigned && !Subtarget->hasSSE41()) {
16041 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16042 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16043 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16044 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16045 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16047 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16048 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16051 // The first result of MUL_LOHI is actually the low value, followed by the
16053 SDValue Ops[] = {Lows, Highs};
16054 return DAG.getMergeValues(Ops, dl);
16057 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16058 const X86Subtarget *Subtarget) {
16059 MVT VT = Op.getSimpleValueType();
16061 SDValue R = Op.getOperand(0);
16062 SDValue Amt = Op.getOperand(1);
16064 // Optimize shl/srl/sra with constant shift amount.
16065 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16066 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16067 uint64_t ShiftAmt = ShiftConst->getZExtValue();
16069 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16070 (Subtarget->hasInt256() &&
16071 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16072 (Subtarget->hasAVX512() &&
16073 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16074 if (Op.getOpcode() == ISD::SHL)
16075 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16077 if (Op.getOpcode() == ISD::SRL)
16078 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16080 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16081 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16085 if (VT == MVT::v16i8) {
16086 if (Op.getOpcode() == ISD::SHL) {
16087 // Make a large shift.
16088 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16089 MVT::v8i16, R, ShiftAmt,
16091 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16092 // Zero out the rightmost bits.
16093 SmallVector<SDValue, 16> V(16,
16094 DAG.getConstant(uint8_t(-1U << ShiftAmt),
16096 return DAG.getNode(ISD::AND, dl, VT, SHL,
16097 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16099 if (Op.getOpcode() == ISD::SRL) {
16100 // Make a large shift.
16101 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16102 MVT::v8i16, R, ShiftAmt,
16104 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16105 // Zero out the leftmost bits.
16106 SmallVector<SDValue, 16> V(16,
16107 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16109 return DAG.getNode(ISD::AND, dl, VT, SRL,
16110 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16112 if (Op.getOpcode() == ISD::SRA) {
16113 if (ShiftAmt == 7) {
16114 // R s>> 7 === R s< 0
16115 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16116 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16119 // R s>> a === ((R u>> a) ^ m) - m
16120 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16121 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
16123 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16124 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16125 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16128 llvm_unreachable("Unknown shift opcode.");
16131 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
16132 if (Op.getOpcode() == ISD::SHL) {
16133 // Make a large shift.
16134 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16135 MVT::v16i16, R, ShiftAmt,
16137 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16138 // Zero out the rightmost bits.
16139 SmallVector<SDValue, 32> V(32,
16140 DAG.getConstant(uint8_t(-1U << ShiftAmt),
16142 return DAG.getNode(ISD::AND, dl, VT, SHL,
16143 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16145 if (Op.getOpcode() == ISD::SRL) {
16146 // Make a large shift.
16147 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16148 MVT::v16i16, R, ShiftAmt,
16150 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16151 // Zero out the leftmost bits.
16152 SmallVector<SDValue, 32> V(32,
16153 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16155 return DAG.getNode(ISD::AND, dl, VT, SRL,
16156 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16158 if (Op.getOpcode() == ISD::SRA) {
16159 if (ShiftAmt == 7) {
16160 // R s>> 7 === R s< 0
16161 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16162 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16165 // R s>> a === ((R u>> a) ^ m) - m
16166 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16167 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
16169 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16170 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16171 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16174 llvm_unreachable("Unknown shift opcode.");
16179 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16180 if (!Subtarget->is64Bit() &&
16181 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16182 Amt.getOpcode() == ISD::BITCAST &&
16183 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16184 Amt = Amt.getOperand(0);
16185 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16186 VT.getVectorNumElements();
16187 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16188 uint64_t ShiftAmt = 0;
16189 for (unsigned i = 0; i != Ratio; ++i) {
16190 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16194 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16196 // Check remaining shift amounts.
16197 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16198 uint64_t ShAmt = 0;
16199 for (unsigned j = 0; j != Ratio; ++j) {
16200 ConstantSDNode *C =
16201 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16205 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16207 if (ShAmt != ShiftAmt)
16210 switch (Op.getOpcode()) {
16212 llvm_unreachable("Unknown shift opcode!");
16214 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16217 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16220 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16228 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16229 const X86Subtarget* Subtarget) {
16230 MVT VT = Op.getSimpleValueType();
16232 SDValue R = Op.getOperand(0);
16233 SDValue Amt = Op.getOperand(1);
16235 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16236 VT == MVT::v4i32 || VT == MVT::v8i16 ||
16237 (Subtarget->hasInt256() &&
16238 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16239 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16240 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16242 EVT EltVT = VT.getVectorElementType();
16244 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16245 unsigned NumElts = VT.getVectorNumElements();
16247 for (i = 0; i != NumElts; ++i) {
16248 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
16252 for (j = i; j != NumElts; ++j) {
16253 SDValue Arg = Amt.getOperand(j);
16254 if (Arg.getOpcode() == ISD::UNDEF) continue;
16255 if (Arg != Amt.getOperand(i))
16258 if (i != NumElts && j == NumElts)
16259 BaseShAmt = Amt.getOperand(i);
16261 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16262 Amt = Amt.getOperand(0);
16263 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
16264 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
16265 SDValue InVec = Amt.getOperand(0);
16266 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16267 unsigned NumElts = InVec.getValueType().getVectorNumElements();
16269 for (; i != NumElts; ++i) {
16270 SDValue Arg = InVec.getOperand(i);
16271 if (Arg.getOpcode() == ISD::UNDEF) continue;
16275 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16276 if (ConstantSDNode *C =
16277 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16278 unsigned SplatIdx =
16279 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16280 if (C->getZExtValue() == SplatIdx)
16281 BaseShAmt = InVec.getOperand(1);
16284 if (!BaseShAmt.getNode())
16285 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16286 DAG.getIntPtrConstant(0));
16290 if (BaseShAmt.getNode()) {
16291 if (EltVT.bitsGT(MVT::i32))
16292 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16293 else if (EltVT.bitsLT(MVT::i32))
16294 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16296 switch (Op.getOpcode()) {
16298 llvm_unreachable("Unknown shift opcode!");
16300 switch (VT.SimpleTy) {
16301 default: return SDValue();
16310 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16313 switch (VT.SimpleTy) {
16314 default: return SDValue();
16321 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16324 switch (VT.SimpleTy) {
16325 default: return SDValue();
16334 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16340 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16341 if (!Subtarget->is64Bit() &&
16342 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16343 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16344 Amt.getOpcode() == ISD::BITCAST &&
16345 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16346 Amt = Amt.getOperand(0);
16347 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16348 VT.getVectorNumElements();
16349 std::vector<SDValue> Vals(Ratio);
16350 for (unsigned i = 0; i != Ratio; ++i)
16351 Vals[i] = Amt.getOperand(i);
16352 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16353 for (unsigned j = 0; j != Ratio; ++j)
16354 if (Vals[j] != Amt.getOperand(i + j))
16357 switch (Op.getOpcode()) {
16359 llvm_unreachable("Unknown shift opcode!");
16361 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16363 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16365 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16372 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16373 SelectionDAG &DAG) {
16374 MVT VT = Op.getSimpleValueType();
16376 SDValue R = Op.getOperand(0);
16377 SDValue Amt = Op.getOperand(1);
16380 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16381 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16383 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16387 V = LowerScalarVariableShift(Op, DAG, Subtarget);
16391 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16393 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16394 if (Subtarget->hasInt256()) {
16395 if (Op.getOpcode() == ISD::SRL &&
16396 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16397 VT == MVT::v4i64 || VT == MVT::v8i32))
16399 if (Op.getOpcode() == ISD::SHL &&
16400 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16401 VT == MVT::v4i64 || VT == MVT::v8i32))
16403 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16407 // If possible, lower this packed shift into a vector multiply instead of
16408 // expanding it into a sequence of scalar shifts.
16409 // Do this only if the vector shift count is a constant build_vector.
16410 if (Op.getOpcode() == ISD::SHL &&
16411 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16412 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16413 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16414 SmallVector<SDValue, 8> Elts;
16415 EVT SVT = VT.getScalarType();
16416 unsigned SVTBits = SVT.getSizeInBits();
16417 const APInt &One = APInt(SVTBits, 1);
16418 unsigned NumElems = VT.getVectorNumElements();
16420 for (unsigned i=0; i !=NumElems; ++i) {
16421 SDValue Op = Amt->getOperand(i);
16422 if (Op->getOpcode() == ISD::UNDEF) {
16423 Elts.push_back(Op);
16427 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16428 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16429 uint64_t ShAmt = C.getZExtValue();
16430 if (ShAmt >= SVTBits) {
16431 Elts.push_back(DAG.getUNDEF(SVT));
16434 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16436 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16437 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16440 // Lower SHL with variable shift amount.
16441 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16442 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16444 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16445 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16446 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16447 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16450 // If possible, lower this shift as a sequence of two shifts by
16451 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16453 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16455 // Could be rewritten as:
16456 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16458 // The advantage is that the two shifts from the example would be
16459 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16460 // the vector shift into four scalar shifts plus four pairs of vector
16462 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16463 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16464 unsigned TargetOpcode = X86ISD::MOVSS;
16465 bool CanBeSimplified;
16466 // The splat value for the first packed shift (the 'X' from the example).
16467 SDValue Amt1 = Amt->getOperand(0);
16468 // The splat value for the second packed shift (the 'Y' from the example).
16469 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16470 Amt->getOperand(2);
16472 // See if it is possible to replace this node with a sequence of
16473 // two shifts followed by a MOVSS/MOVSD
16474 if (VT == MVT::v4i32) {
16475 // Check if it is legal to use a MOVSS.
16476 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16477 Amt2 == Amt->getOperand(3);
16478 if (!CanBeSimplified) {
16479 // Otherwise, check if we can still simplify this node using a MOVSD.
16480 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16481 Amt->getOperand(2) == Amt->getOperand(3);
16482 TargetOpcode = X86ISD::MOVSD;
16483 Amt2 = Amt->getOperand(2);
16486 // Do similar checks for the case where the machine value type
16488 CanBeSimplified = Amt1 == Amt->getOperand(1);
16489 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16490 CanBeSimplified = Amt2 == Amt->getOperand(i);
16492 if (!CanBeSimplified) {
16493 TargetOpcode = X86ISD::MOVSD;
16494 CanBeSimplified = true;
16495 Amt2 = Amt->getOperand(4);
16496 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16497 CanBeSimplified = Amt1 == Amt->getOperand(i);
16498 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16499 CanBeSimplified = Amt2 == Amt->getOperand(j);
16503 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16504 isa<ConstantSDNode>(Amt2)) {
16505 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16506 EVT CastVT = MVT::v4i32;
16508 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16509 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16511 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16512 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16513 if (TargetOpcode == X86ISD::MOVSD)
16514 CastVT = MVT::v2i64;
16515 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16516 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16517 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16519 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16523 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16524 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16527 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16528 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16530 // Turn 'a' into a mask suitable for VSELECT
16531 SDValue VSelM = DAG.getConstant(0x80, VT);
16532 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16533 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16535 SDValue CM1 = DAG.getConstant(0x0f, VT);
16536 SDValue CM2 = DAG.getConstant(0x3f, VT);
16538 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16539 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16540 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16541 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16542 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16545 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16546 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16547 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16549 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16550 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16551 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16552 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16553 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16556 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16557 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16558 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16560 // return VSELECT(r, r+r, a);
16561 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16562 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16566 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16567 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16568 // solution better.
16569 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16570 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16572 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16573 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16574 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16575 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16576 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16579 // Decompose 256-bit shifts into smaller 128-bit shifts.
16580 if (VT.is256BitVector()) {
16581 unsigned NumElems = VT.getVectorNumElements();
16582 MVT EltVT = VT.getVectorElementType();
16583 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16585 // Extract the two vectors
16586 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16587 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16589 // Recreate the shift amount vectors
16590 SDValue Amt1, Amt2;
16591 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16592 // Constant shift amount
16593 SmallVector<SDValue, 4> Amt1Csts;
16594 SmallVector<SDValue, 4> Amt2Csts;
16595 for (unsigned i = 0; i != NumElems/2; ++i)
16596 Amt1Csts.push_back(Amt->getOperand(i));
16597 for (unsigned i = NumElems/2; i != NumElems; ++i)
16598 Amt2Csts.push_back(Amt->getOperand(i));
16600 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16601 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16603 // Variable shift amount
16604 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16605 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16608 // Issue new vector shifts for the smaller types
16609 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16610 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16612 // Concatenate the result back
16613 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16619 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16620 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16621 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16622 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16623 // has only one use.
16624 SDNode *N = Op.getNode();
16625 SDValue LHS = N->getOperand(0);
16626 SDValue RHS = N->getOperand(1);
16627 unsigned BaseOp = 0;
16630 switch (Op.getOpcode()) {
16631 default: llvm_unreachable("Unknown ovf instruction!");
16633 // A subtract of one will be selected as a INC. Note that INC doesn't
16634 // set CF, so we can't do this for UADDO.
16635 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16637 BaseOp = X86ISD::INC;
16638 Cond = X86::COND_O;
16641 BaseOp = X86ISD::ADD;
16642 Cond = X86::COND_O;
16645 BaseOp = X86ISD::ADD;
16646 Cond = X86::COND_B;
16649 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16650 // set CF, so we can't do this for USUBO.
16651 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16653 BaseOp = X86ISD::DEC;
16654 Cond = X86::COND_O;
16657 BaseOp = X86ISD::SUB;
16658 Cond = X86::COND_O;
16661 BaseOp = X86ISD::SUB;
16662 Cond = X86::COND_B;
16665 BaseOp = X86ISD::SMUL;
16666 Cond = X86::COND_O;
16668 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16669 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16671 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16674 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16675 DAG.getConstant(X86::COND_O, MVT::i32),
16676 SDValue(Sum.getNode(), 2));
16678 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16682 // Also sets EFLAGS.
16683 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16684 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16687 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16688 DAG.getConstant(Cond, MVT::i32),
16689 SDValue(Sum.getNode(), 1));
16691 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16694 // Sign extension of the low part of vector elements. This may be used either
16695 // when sign extend instructions are not available or if the vector element
16696 // sizes already match the sign-extended size. If the vector elements are in
16697 // their pre-extended size and sign extend instructions are available, that will
16698 // be handled by LowerSIGN_EXTEND.
16699 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16700 SelectionDAG &DAG) const {
16702 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16703 MVT VT = Op.getSimpleValueType();
16705 if (!Subtarget->hasSSE2() || !VT.isVector())
16708 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16709 ExtraVT.getScalarType().getSizeInBits();
16711 switch (VT.SimpleTy) {
16712 default: return SDValue();
16715 if (!Subtarget->hasFp256())
16717 if (!Subtarget->hasInt256()) {
16718 // needs to be split
16719 unsigned NumElems = VT.getVectorNumElements();
16721 // Extract the LHS vectors
16722 SDValue LHS = Op.getOperand(0);
16723 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16724 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16726 MVT EltVT = VT.getVectorElementType();
16727 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16729 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16730 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16731 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16733 SDValue Extra = DAG.getValueType(ExtraVT);
16735 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16736 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16738 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16743 SDValue Op0 = Op.getOperand(0);
16745 // This is a sign extension of some low part of vector elements without
16746 // changing the size of the vector elements themselves:
16747 // Shift-Left + Shift-Right-Algebraic.
16748 SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
16750 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
16756 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16757 SelectionDAG &DAG) {
16759 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16760 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16761 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16762 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16764 // The only fence that needs an instruction is a sequentially-consistent
16765 // cross-thread fence.
16766 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16767 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16768 // no-sse2). There isn't any reason to disable it if the target processor
16770 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16771 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16773 SDValue Chain = Op.getOperand(0);
16774 SDValue Zero = DAG.getConstant(0, MVT::i32);
16776 DAG.getRegister(X86::ESP, MVT::i32), // Base
16777 DAG.getTargetConstant(1, MVT::i8), // Scale
16778 DAG.getRegister(0, MVT::i32), // Index
16779 DAG.getTargetConstant(0, MVT::i32), // Disp
16780 DAG.getRegister(0, MVT::i32), // Segment.
16784 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16785 return SDValue(Res, 0);
16788 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16789 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16792 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16793 SelectionDAG &DAG) {
16794 MVT T = Op.getSimpleValueType();
16798 switch(T.SimpleTy) {
16799 default: llvm_unreachable("Invalid value type!");
16800 case MVT::i8: Reg = X86::AL; size = 1; break;
16801 case MVT::i16: Reg = X86::AX; size = 2; break;
16802 case MVT::i32: Reg = X86::EAX; size = 4; break;
16804 assert(Subtarget->is64Bit() && "Node not type legal!");
16805 Reg = X86::RAX; size = 8;
16808 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16809 Op.getOperand(2), SDValue());
16810 SDValue Ops[] = { cpIn.getValue(0),
16813 DAG.getTargetConstant(size, MVT::i8),
16814 cpIn.getValue(1) };
16815 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16816 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16817 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16821 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16822 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16823 MVT::i32, cpOut.getValue(2));
16824 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16825 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16827 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16828 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16829 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16833 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16834 SelectionDAG &DAG) {
16835 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16836 MVT DstVT = Op.getSimpleValueType();
16838 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16839 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16840 if (DstVT != MVT::f64)
16841 // This conversion needs to be expanded.
16844 SDValue InVec = Op->getOperand(0);
16846 unsigned NumElts = SrcVT.getVectorNumElements();
16847 EVT SVT = SrcVT.getVectorElementType();
16849 // Widen the vector in input in the case of MVT::v2i32.
16850 // Example: from MVT::v2i32 to MVT::v4i32.
16851 SmallVector<SDValue, 16> Elts;
16852 for (unsigned i = 0, e = NumElts; i != e; ++i)
16853 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16854 DAG.getIntPtrConstant(i)));
16856 // Explicitly mark the extra elements as Undef.
16857 SDValue Undef = DAG.getUNDEF(SVT);
16858 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16859 Elts.push_back(Undef);
16861 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16862 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16863 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16864 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16865 DAG.getIntPtrConstant(0));
16868 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16869 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16870 assert((DstVT == MVT::i64 ||
16871 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16872 "Unexpected custom BITCAST");
16873 // i64 <=> MMX conversions are Legal.
16874 if (SrcVT==MVT::i64 && DstVT.isVector())
16876 if (DstVT==MVT::i64 && SrcVT.isVector())
16878 // MMX <=> MMX conversions are Legal.
16879 if (SrcVT.isVector() && DstVT.isVector())
16881 // All other conversions need to be expanded.
16885 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16886 SDNode *Node = Op.getNode();
16888 EVT T = Node->getValueType(0);
16889 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16890 DAG.getConstant(0, T), Node->getOperand(2));
16891 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16892 cast<AtomicSDNode>(Node)->getMemoryVT(),
16893 Node->getOperand(0),
16894 Node->getOperand(1), negOp,
16895 cast<AtomicSDNode>(Node)->getMemOperand(),
16896 cast<AtomicSDNode>(Node)->getOrdering(),
16897 cast<AtomicSDNode>(Node)->getSynchScope());
16900 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16901 SDNode *Node = Op.getNode();
16903 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16905 // Convert seq_cst store -> xchg
16906 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16907 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16908 // (The only way to get a 16-byte store is cmpxchg16b)
16909 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16910 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16911 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16912 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16913 cast<AtomicSDNode>(Node)->getMemoryVT(),
16914 Node->getOperand(0),
16915 Node->getOperand(1), Node->getOperand(2),
16916 cast<AtomicSDNode>(Node)->getMemOperand(),
16917 cast<AtomicSDNode>(Node)->getOrdering(),
16918 cast<AtomicSDNode>(Node)->getSynchScope());
16919 return Swap.getValue(1);
16921 // Other atomic stores have a simple pattern.
16925 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16926 EVT VT = Op.getNode()->getSimpleValueType(0);
16928 // Let legalize expand this if it isn't a legal type yet.
16929 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16932 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16935 bool ExtraOp = false;
16936 switch (Op.getOpcode()) {
16937 default: llvm_unreachable("Invalid code");
16938 case ISD::ADDC: Opc = X86ISD::ADD; break;
16939 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16940 case ISD::SUBC: Opc = X86ISD::SUB; break;
16941 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16945 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16947 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16948 Op.getOperand(1), Op.getOperand(2));
16951 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16952 SelectionDAG &DAG) {
16953 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16955 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16956 // which returns the values as { float, float } (in XMM0) or
16957 // { double, double } (which is returned in XMM0, XMM1).
16959 SDValue Arg = Op.getOperand(0);
16960 EVT ArgVT = Arg.getValueType();
16961 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16963 TargetLowering::ArgListTy Args;
16964 TargetLowering::ArgListEntry Entry;
16968 Entry.isSExt = false;
16969 Entry.isZExt = false;
16970 Args.push_back(Entry);
16972 bool isF64 = ArgVT == MVT::f64;
16973 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16974 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16975 // the results are returned via SRet in memory.
16976 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16977 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16978 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16980 Type *RetTy = isF64
16981 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16982 : (Type*)VectorType::get(ArgTy, 4);
16984 TargetLowering::CallLoweringInfo CLI(DAG);
16985 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16986 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16988 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16991 // Returned in xmm0 and xmm1.
16992 return CallResult.first;
16994 // Returned in bits 0:31 and 32:64 xmm0.
16995 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16996 CallResult.first, DAG.getIntPtrConstant(0));
16997 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16998 CallResult.first, DAG.getIntPtrConstant(1));
16999 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17000 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17003 /// LowerOperation - Provide custom lowering hooks for some operations.
17005 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17006 switch (Op.getOpcode()) {
17007 default: llvm_unreachable("Should not custom lower this!");
17008 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
17009 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17010 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17011 return LowerCMP_SWAP(Op, Subtarget, DAG);
17012 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
17013 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
17014 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
17015 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
17016 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
17017 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
17018 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17019 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
17020 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17021 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17022 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
17023 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
17024 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
17025 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
17026 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
17027 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
17028 case ISD::SHL_PARTS:
17029 case ISD::SRA_PARTS:
17030 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
17031 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
17032 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
17033 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
17034 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
17035 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17036 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
17037 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
17038 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
17039 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
17040 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
17042 case ISD::FNEG: return LowerFABSorFNEG(Op, DAG);
17043 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
17044 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
17045 case ISD::SETCC: return LowerSETCC(Op, DAG);
17046 case ISD::SELECT: return LowerSELECT(Op, DAG);
17047 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
17048 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
17049 case ISD::VASTART: return LowerVASTART(Op, DAG);
17050 case ISD::VAARG: return LowerVAARG(Op, DAG);
17051 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
17052 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
17053 case ISD::INTRINSIC_VOID:
17054 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17055 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
17056 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
17057 case ISD::FRAME_TO_ARGS_OFFSET:
17058 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17059 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17060 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
17061 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
17062 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
17063 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
17064 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
17065 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
17066 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
17067 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17068 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
17069 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
17070 case ISD::UMUL_LOHI:
17071 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
17074 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
17080 case ISD::UMULO: return LowerXALUO(Op, DAG);
17081 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17082 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
17086 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17087 case ISD::ADD: return LowerADD(Op, DAG);
17088 case ISD::SUB: return LowerSUB(Op, DAG);
17089 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
17093 static void ReplaceATOMIC_LOAD(SDNode *Node,
17094 SmallVectorImpl<SDValue> &Results,
17095 SelectionDAG &DAG) {
17097 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17099 // Convert wide load -> cmpxchg8b/cmpxchg16b
17100 // FIXME: On 32-bit, load -> fild or movq would be more efficient
17101 // (The only way to get a 16-byte load is cmpxchg16b)
17102 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
17103 SDValue Zero = DAG.getConstant(0, VT);
17104 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
17106 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
17107 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
17108 cast<AtomicSDNode>(Node)->getMemOperand(),
17109 cast<AtomicSDNode>(Node)->getOrdering(),
17110 cast<AtomicSDNode>(Node)->getOrdering(),
17111 cast<AtomicSDNode>(Node)->getSynchScope());
17112 Results.push_back(Swap.getValue(0));
17113 Results.push_back(Swap.getValue(2));
17116 /// ReplaceNodeResults - Replace a node with an illegal result type
17117 /// with a new node built out of custom code.
17118 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17119 SmallVectorImpl<SDValue>&Results,
17120 SelectionDAG &DAG) const {
17122 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17123 switch (N->getOpcode()) {
17125 llvm_unreachable("Do not know how to custom type legalize this operation!");
17126 case ISD::SIGN_EXTEND_INREG:
17131 // We don't want to expand or promote these.
17138 case ISD::UDIVREM: {
17139 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17140 Results.push_back(V);
17143 case ISD::FP_TO_SINT:
17144 case ISD::FP_TO_UINT: {
17145 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17147 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17150 std::pair<SDValue,SDValue> Vals =
17151 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17152 SDValue FIST = Vals.first, StackSlot = Vals.second;
17153 if (FIST.getNode()) {
17154 EVT VT = N->getValueType(0);
17155 // Return a load from the stack slot.
17156 if (StackSlot.getNode())
17157 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17158 MachinePointerInfo(),
17159 false, false, false, 0));
17161 Results.push_back(FIST);
17165 case ISD::UINT_TO_FP: {
17166 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17167 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17168 N->getValueType(0) != MVT::v2f32)
17170 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17172 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17174 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17175 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17176 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17177 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17178 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17179 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17182 case ISD::FP_ROUND: {
17183 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17185 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17186 Results.push_back(V);
17189 case ISD::INTRINSIC_W_CHAIN: {
17190 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17192 default : llvm_unreachable("Do not know how to custom type "
17193 "legalize this intrinsic operation!");
17194 case Intrinsic::x86_rdtsc:
17195 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17197 case Intrinsic::x86_rdtscp:
17198 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17200 case Intrinsic::x86_rdpmc:
17201 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17204 case ISD::READCYCLECOUNTER: {
17205 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17208 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17209 EVT T = N->getValueType(0);
17210 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17211 bool Regs64bit = T == MVT::i128;
17212 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17213 SDValue cpInL, cpInH;
17214 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17215 DAG.getConstant(0, HalfT));
17216 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17217 DAG.getConstant(1, HalfT));
17218 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17219 Regs64bit ? X86::RAX : X86::EAX,
17221 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17222 Regs64bit ? X86::RDX : X86::EDX,
17223 cpInH, cpInL.getValue(1));
17224 SDValue swapInL, swapInH;
17225 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17226 DAG.getConstant(0, HalfT));
17227 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17228 DAG.getConstant(1, HalfT));
17229 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17230 Regs64bit ? X86::RBX : X86::EBX,
17231 swapInL, cpInH.getValue(1));
17232 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17233 Regs64bit ? X86::RCX : X86::ECX,
17234 swapInH, swapInL.getValue(1));
17235 SDValue Ops[] = { swapInH.getValue(0),
17237 swapInH.getValue(1) };
17238 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17239 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17240 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17241 X86ISD::LCMPXCHG8_DAG;
17242 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17243 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17244 Regs64bit ? X86::RAX : X86::EAX,
17245 HalfT, Result.getValue(1));
17246 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17247 Regs64bit ? X86::RDX : X86::EDX,
17248 HalfT, cpOutL.getValue(2));
17249 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17251 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17252 MVT::i32, cpOutH.getValue(2));
17254 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17255 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17256 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17258 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17259 Results.push_back(Success);
17260 Results.push_back(EFLAGS.getValue(1));
17263 case ISD::ATOMIC_SWAP:
17264 case ISD::ATOMIC_LOAD_ADD:
17265 case ISD::ATOMIC_LOAD_SUB:
17266 case ISD::ATOMIC_LOAD_AND:
17267 case ISD::ATOMIC_LOAD_OR:
17268 case ISD::ATOMIC_LOAD_XOR:
17269 case ISD::ATOMIC_LOAD_NAND:
17270 case ISD::ATOMIC_LOAD_MIN:
17271 case ISD::ATOMIC_LOAD_MAX:
17272 case ISD::ATOMIC_LOAD_UMIN:
17273 case ISD::ATOMIC_LOAD_UMAX:
17274 // Delegate to generic TypeLegalization. Situations we can really handle
17275 // should have already been dealt with by X86AtomicExpandPass.cpp.
17277 case ISD::ATOMIC_LOAD: {
17278 ReplaceATOMIC_LOAD(N, Results, DAG);
17281 case ISD::BITCAST: {
17282 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17283 EVT DstVT = N->getValueType(0);
17284 EVT SrcVT = N->getOperand(0)->getValueType(0);
17286 if (SrcVT != MVT::f64 ||
17287 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17290 unsigned NumElts = DstVT.getVectorNumElements();
17291 EVT SVT = DstVT.getVectorElementType();
17292 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17293 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17294 MVT::v2f64, N->getOperand(0));
17295 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17297 if (ExperimentalVectorWideningLegalization) {
17298 // If we are legalizing vectors by widening, we already have the desired
17299 // legal vector type, just return it.
17300 Results.push_back(ToVecInt);
17304 SmallVector<SDValue, 8> Elts;
17305 for (unsigned i = 0, e = NumElts; i != e; ++i)
17306 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17307 ToVecInt, DAG.getIntPtrConstant(i)));
17309 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17314 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17316 default: return nullptr;
17317 case X86ISD::BSF: return "X86ISD::BSF";
17318 case X86ISD::BSR: return "X86ISD::BSR";
17319 case X86ISD::SHLD: return "X86ISD::SHLD";
17320 case X86ISD::SHRD: return "X86ISD::SHRD";
17321 case X86ISD::FAND: return "X86ISD::FAND";
17322 case X86ISD::FANDN: return "X86ISD::FANDN";
17323 case X86ISD::FOR: return "X86ISD::FOR";
17324 case X86ISD::FXOR: return "X86ISD::FXOR";
17325 case X86ISD::FSRL: return "X86ISD::FSRL";
17326 case X86ISD::FILD: return "X86ISD::FILD";
17327 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17328 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17329 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17330 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17331 case X86ISD::FLD: return "X86ISD::FLD";
17332 case X86ISD::FST: return "X86ISD::FST";
17333 case X86ISD::CALL: return "X86ISD::CALL";
17334 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17335 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17336 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17337 case X86ISD::BT: return "X86ISD::BT";
17338 case X86ISD::CMP: return "X86ISD::CMP";
17339 case X86ISD::COMI: return "X86ISD::COMI";
17340 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17341 case X86ISD::CMPM: return "X86ISD::CMPM";
17342 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17343 case X86ISD::SETCC: return "X86ISD::SETCC";
17344 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17345 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17346 case X86ISD::CMOV: return "X86ISD::CMOV";
17347 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17348 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17349 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17350 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17351 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17352 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17353 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17354 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17355 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17356 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17357 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17358 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17359 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17360 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17361 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17362 case X86ISD::BLENDV: return "X86ISD::BLENDV";
17363 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17364 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17365 case X86ISD::HADD: return "X86ISD::HADD";
17366 case X86ISD::HSUB: return "X86ISD::HSUB";
17367 case X86ISD::FHADD: return "X86ISD::FHADD";
17368 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17369 case X86ISD::UMAX: return "X86ISD::UMAX";
17370 case X86ISD::UMIN: return "X86ISD::UMIN";
17371 case X86ISD::SMAX: return "X86ISD::SMAX";
17372 case X86ISD::SMIN: return "X86ISD::SMIN";
17373 case X86ISD::FMAX: return "X86ISD::FMAX";
17374 case X86ISD::FMIN: return "X86ISD::FMIN";
17375 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17376 case X86ISD::FMINC: return "X86ISD::FMINC";
17377 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17378 case X86ISD::FRCP: return "X86ISD::FRCP";
17379 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17380 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17381 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17382 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17383 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17384 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17385 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17386 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17387 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17388 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17389 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17390 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17391 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17392 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17393 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17394 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17395 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17396 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17397 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17398 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17399 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17400 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17401 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17402 case X86ISD::VSHL: return "X86ISD::VSHL";
17403 case X86ISD::VSRL: return "X86ISD::VSRL";
17404 case X86ISD::VSRA: return "X86ISD::VSRA";
17405 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17406 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17407 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17408 case X86ISD::CMPP: return "X86ISD::CMPP";
17409 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17410 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17411 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17412 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17413 case X86ISD::ADD: return "X86ISD::ADD";
17414 case X86ISD::SUB: return "X86ISD::SUB";
17415 case X86ISD::ADC: return "X86ISD::ADC";
17416 case X86ISD::SBB: return "X86ISD::SBB";
17417 case X86ISD::SMUL: return "X86ISD::SMUL";
17418 case X86ISD::UMUL: return "X86ISD::UMUL";
17419 case X86ISD::INC: return "X86ISD::INC";
17420 case X86ISD::DEC: return "X86ISD::DEC";
17421 case X86ISD::OR: return "X86ISD::OR";
17422 case X86ISD::XOR: return "X86ISD::XOR";
17423 case X86ISD::AND: return "X86ISD::AND";
17424 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17425 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17426 case X86ISD::PTEST: return "X86ISD::PTEST";
17427 case X86ISD::TESTP: return "X86ISD::TESTP";
17428 case X86ISD::TESTM: return "X86ISD::TESTM";
17429 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17430 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17431 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17432 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17433 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17434 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17435 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17436 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17437 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17438 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17439 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17440 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17441 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17442 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17443 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17444 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17445 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17446 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17447 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17448 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17449 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17450 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17451 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17452 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
17453 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17454 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
17455 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17456 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17457 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17458 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17459 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17460 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17461 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17462 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17463 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17464 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17465 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17466 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17467 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17468 case X86ISD::SAHF: return "X86ISD::SAHF";
17469 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17470 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17471 case X86ISD::FMADD: return "X86ISD::FMADD";
17472 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17473 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17474 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17475 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17476 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17477 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
17478 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
17479 case X86ISD::XTEST: return "X86ISD::XTEST";
17483 // isLegalAddressingMode - Return true if the addressing mode represented
17484 // by AM is legal for this target, for a load/store of the specified type.
17485 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17487 // X86 supports extremely general addressing modes.
17488 CodeModel::Model M = getTargetMachine().getCodeModel();
17489 Reloc::Model R = getTargetMachine().getRelocationModel();
17491 // X86 allows a sign-extended 32-bit immediate field as a displacement.
17492 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17497 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17499 // If a reference to this global requires an extra load, we can't fold it.
17500 if (isGlobalStubReference(GVFlags))
17503 // If BaseGV requires a register for the PIC base, we cannot also have a
17504 // BaseReg specified.
17505 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17508 // If lower 4G is not available, then we must use rip-relative addressing.
17509 if ((M != CodeModel::Small || R != Reloc::Static) &&
17510 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17514 switch (AM.Scale) {
17520 // These scales always work.
17525 // These scales are formed with basereg+scalereg. Only accept if there is
17530 default: // Other stuff never works.
17537 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17538 unsigned Bits = Ty->getScalarSizeInBits();
17540 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17541 // particularly cheaper than those without.
17545 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17546 // variable shifts just as cheap as scalar ones.
17547 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17550 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17551 // fully general vector.
17555 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17556 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17558 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17559 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17560 return NumBits1 > NumBits2;
17563 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17564 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17567 if (!isTypeLegal(EVT::getEVT(Ty1)))
17570 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17572 // Assuming the caller doesn't have a zeroext or signext return parameter,
17573 // truncation all the way down to i1 is valid.
17577 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17578 return isInt<32>(Imm);
17581 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17582 // Can also use sub to handle negated immediates.
17583 return isInt<32>(Imm);
17586 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17587 if (!VT1.isInteger() || !VT2.isInteger())
17589 unsigned NumBits1 = VT1.getSizeInBits();
17590 unsigned NumBits2 = VT2.getSizeInBits();
17591 return NumBits1 > NumBits2;
17594 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17595 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17596 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17599 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17600 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17601 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17604 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17605 EVT VT1 = Val.getValueType();
17606 if (isZExtFree(VT1, VT2))
17609 if (Val.getOpcode() != ISD::LOAD)
17612 if (!VT1.isSimple() || !VT1.isInteger() ||
17613 !VT2.isSimple() || !VT2.isInteger())
17616 switch (VT1.getSimpleVT().SimpleTy) {
17621 // X86 has 8, 16, and 32-bit zero-extending loads.
17629 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17630 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17633 VT = VT.getScalarType();
17635 if (!VT.isSimple())
17638 switch (VT.getSimpleVT().SimpleTy) {
17649 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17650 // i16 instructions are longer (0x66 prefix) and potentially slower.
17651 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17654 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17655 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17656 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17657 /// are assumed to be legal.
17659 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17661 if (!VT.isSimple())
17664 MVT SVT = VT.getSimpleVT();
17666 // Very little shuffling can be done for 64-bit vectors right now.
17667 if (VT.getSizeInBits() == 64)
17670 // If this is a single-input shuffle with no 128 bit lane crossings we can
17671 // lower it into pshufb.
17672 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17673 (SVT.is256BitVector() && Subtarget->hasInt256())) {
17674 bool isLegal = true;
17675 for (unsigned I = 0, E = M.size(); I != E; ++I) {
17676 if (M[I] >= (int)SVT.getVectorNumElements() ||
17677 ShuffleCrosses128bitLane(SVT, I, M[I])) {
17686 // FIXME: blends, shifts.
17687 return (SVT.getVectorNumElements() == 2 ||
17688 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17689 isMOVLMask(M, SVT) ||
17690 isMOVHLPSMask(M, SVT) ||
17691 isSHUFPMask(M, SVT) ||
17692 isPSHUFDMask(M, SVT) ||
17693 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17694 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17695 isPALIGNRMask(M, SVT, Subtarget) ||
17696 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17697 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17698 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17699 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17700 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17704 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17706 if (!VT.isSimple())
17709 MVT SVT = VT.getSimpleVT();
17710 unsigned NumElts = SVT.getVectorNumElements();
17711 // FIXME: This collection of masks seems suspect.
17714 if (NumElts == 4 && SVT.is128BitVector()) {
17715 return (isMOVLMask(Mask, SVT) ||
17716 isCommutedMOVLMask(Mask, SVT, true) ||
17717 isSHUFPMask(Mask, SVT) ||
17718 isSHUFPMask(Mask, SVT, /* Commuted */ true));
17723 //===----------------------------------------------------------------------===//
17724 // X86 Scheduler Hooks
17725 //===----------------------------------------------------------------------===//
17727 /// Utility function to emit xbegin specifying the start of an RTM region.
17728 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17729 const TargetInstrInfo *TII) {
17730 DebugLoc DL = MI->getDebugLoc();
17732 const BasicBlock *BB = MBB->getBasicBlock();
17733 MachineFunction::iterator I = MBB;
17736 // For the v = xbegin(), we generate
17747 MachineBasicBlock *thisMBB = MBB;
17748 MachineFunction *MF = MBB->getParent();
17749 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17750 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17751 MF->insert(I, mainMBB);
17752 MF->insert(I, sinkMBB);
17754 // Transfer the remainder of BB and its successor edges to sinkMBB.
17755 sinkMBB->splice(sinkMBB->begin(), MBB,
17756 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17757 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17761 // # fallthrough to mainMBB
17762 // # abortion to sinkMBB
17763 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17764 thisMBB->addSuccessor(mainMBB);
17765 thisMBB->addSuccessor(sinkMBB);
17769 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17770 mainMBB->addSuccessor(sinkMBB);
17773 // EAX is live into the sinkMBB
17774 sinkMBB->addLiveIn(X86::EAX);
17775 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17776 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17779 MI->eraseFromParent();
17783 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17784 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17785 // in the .td file.
17786 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17787 const TargetInstrInfo *TII) {
17789 switch (MI->getOpcode()) {
17790 default: llvm_unreachable("illegal opcode!");
17791 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17792 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17793 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17794 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17795 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17796 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17797 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17798 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17801 DebugLoc dl = MI->getDebugLoc();
17802 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17804 unsigned NumArgs = MI->getNumOperands();
17805 for (unsigned i = 1; i < NumArgs; ++i) {
17806 MachineOperand &Op = MI->getOperand(i);
17807 if (!(Op.isReg() && Op.isImplicit()))
17808 MIB.addOperand(Op);
17810 if (MI->hasOneMemOperand())
17811 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17813 BuildMI(*BB, MI, dl,
17814 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17815 .addReg(X86::XMM0);
17817 MI->eraseFromParent();
17821 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17822 // defs in an instruction pattern
17823 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17824 const TargetInstrInfo *TII) {
17826 switch (MI->getOpcode()) {
17827 default: llvm_unreachable("illegal opcode!");
17828 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17829 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17830 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17831 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17832 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17833 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17834 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17835 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17838 DebugLoc dl = MI->getDebugLoc();
17839 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17841 unsigned NumArgs = MI->getNumOperands(); // remove the results
17842 for (unsigned i = 1; i < NumArgs; ++i) {
17843 MachineOperand &Op = MI->getOperand(i);
17844 if (!(Op.isReg() && Op.isImplicit()))
17845 MIB.addOperand(Op);
17847 if (MI->hasOneMemOperand())
17848 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17850 BuildMI(*BB, MI, dl,
17851 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17854 MI->eraseFromParent();
17858 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17859 const TargetInstrInfo *TII,
17860 const X86Subtarget* Subtarget) {
17861 DebugLoc dl = MI->getDebugLoc();
17863 // Address into RAX/EAX, other two args into ECX, EDX.
17864 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17865 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17866 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17867 for (int i = 0; i < X86::AddrNumOperands; ++i)
17868 MIB.addOperand(MI->getOperand(i));
17870 unsigned ValOps = X86::AddrNumOperands;
17871 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17872 .addReg(MI->getOperand(ValOps).getReg());
17873 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17874 .addReg(MI->getOperand(ValOps+1).getReg());
17876 // The instruction doesn't actually take any operands though.
17877 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17879 MI->eraseFromParent(); // The pseudo is gone now.
17883 MachineBasicBlock *
17884 X86TargetLowering::EmitVAARG64WithCustomInserter(
17886 MachineBasicBlock *MBB) const {
17887 // Emit va_arg instruction on X86-64.
17889 // Operands to this pseudo-instruction:
17890 // 0 ) Output : destination address (reg)
17891 // 1-5) Input : va_list address (addr, i64mem)
17892 // 6 ) ArgSize : Size (in bytes) of vararg type
17893 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17894 // 8 ) Align : Alignment of type
17895 // 9 ) EFLAGS (implicit-def)
17897 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17898 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17900 unsigned DestReg = MI->getOperand(0).getReg();
17901 MachineOperand &Base = MI->getOperand(1);
17902 MachineOperand &Scale = MI->getOperand(2);
17903 MachineOperand &Index = MI->getOperand(3);
17904 MachineOperand &Disp = MI->getOperand(4);
17905 MachineOperand &Segment = MI->getOperand(5);
17906 unsigned ArgSize = MI->getOperand(6).getImm();
17907 unsigned ArgMode = MI->getOperand(7).getImm();
17908 unsigned Align = MI->getOperand(8).getImm();
17910 // Memory Reference
17911 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17912 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17913 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17915 // Machine Information
17916 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17917 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17918 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17919 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17920 DebugLoc DL = MI->getDebugLoc();
17922 // struct va_list {
17925 // i64 overflow_area (address)
17926 // i64 reg_save_area (address)
17928 // sizeof(va_list) = 24
17929 // alignment(va_list) = 8
17931 unsigned TotalNumIntRegs = 6;
17932 unsigned TotalNumXMMRegs = 8;
17933 bool UseGPOffset = (ArgMode == 1);
17934 bool UseFPOffset = (ArgMode == 2);
17935 unsigned MaxOffset = TotalNumIntRegs * 8 +
17936 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17938 /* Align ArgSize to a multiple of 8 */
17939 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17940 bool NeedsAlign = (Align > 8);
17942 MachineBasicBlock *thisMBB = MBB;
17943 MachineBasicBlock *overflowMBB;
17944 MachineBasicBlock *offsetMBB;
17945 MachineBasicBlock *endMBB;
17947 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17948 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17949 unsigned OffsetReg = 0;
17951 if (!UseGPOffset && !UseFPOffset) {
17952 // If we only pull from the overflow region, we don't create a branch.
17953 // We don't need to alter control flow.
17954 OffsetDestReg = 0; // unused
17955 OverflowDestReg = DestReg;
17957 offsetMBB = nullptr;
17958 overflowMBB = thisMBB;
17961 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17962 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17963 // If not, pull from overflow_area. (branch to overflowMBB)
17968 // offsetMBB overflowMBB
17973 // Registers for the PHI in endMBB
17974 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17975 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17977 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17978 MachineFunction *MF = MBB->getParent();
17979 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17980 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17981 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17983 MachineFunction::iterator MBBIter = MBB;
17986 // Insert the new basic blocks
17987 MF->insert(MBBIter, offsetMBB);
17988 MF->insert(MBBIter, overflowMBB);
17989 MF->insert(MBBIter, endMBB);
17991 // Transfer the remainder of MBB and its successor edges to endMBB.
17992 endMBB->splice(endMBB->begin(), thisMBB,
17993 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17994 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17996 // Make offsetMBB and overflowMBB successors of thisMBB
17997 thisMBB->addSuccessor(offsetMBB);
17998 thisMBB->addSuccessor(overflowMBB);
18000 // endMBB is a successor of both offsetMBB and overflowMBB
18001 offsetMBB->addSuccessor(endMBB);
18002 overflowMBB->addSuccessor(endMBB);
18004 // Load the offset value into a register
18005 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18006 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18010 .addDisp(Disp, UseFPOffset ? 4 : 0)
18011 .addOperand(Segment)
18012 .setMemRefs(MMOBegin, MMOEnd);
18014 // Check if there is enough room left to pull this argument.
18015 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18017 .addImm(MaxOffset + 8 - ArgSizeA8);
18019 // Branch to "overflowMBB" if offset >= max
18020 // Fall through to "offsetMBB" otherwise
18021 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18022 .addMBB(overflowMBB);
18025 // In offsetMBB, emit code to use the reg_save_area.
18027 assert(OffsetReg != 0);
18029 // Read the reg_save_area address.
18030 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18031 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18036 .addOperand(Segment)
18037 .setMemRefs(MMOBegin, MMOEnd);
18039 // Zero-extend the offset
18040 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18041 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18044 .addImm(X86::sub_32bit);
18046 // Add the offset to the reg_save_area to get the final address.
18047 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18048 .addReg(OffsetReg64)
18049 .addReg(RegSaveReg);
18051 // Compute the offset for the next argument
18052 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18053 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18055 .addImm(UseFPOffset ? 16 : 8);
18057 // Store it back into the va_list.
18058 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18062 .addDisp(Disp, UseFPOffset ? 4 : 0)
18063 .addOperand(Segment)
18064 .addReg(NextOffsetReg)
18065 .setMemRefs(MMOBegin, MMOEnd);
18068 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
18073 // Emit code to use overflow area
18076 // Load the overflow_area address into a register.
18077 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18078 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18083 .addOperand(Segment)
18084 .setMemRefs(MMOBegin, MMOEnd);
18086 // If we need to align it, do so. Otherwise, just copy the address
18087 // to OverflowDestReg.
18089 // Align the overflow address
18090 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18091 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18093 // aligned_addr = (addr + (align-1)) & ~(align-1)
18094 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18095 .addReg(OverflowAddrReg)
18098 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18100 .addImm(~(uint64_t)(Align-1));
18102 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18103 .addReg(OverflowAddrReg);
18106 // Compute the next overflow address after this argument.
18107 // (the overflow address should be kept 8-byte aligned)
18108 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18109 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18110 .addReg(OverflowDestReg)
18111 .addImm(ArgSizeA8);
18113 // Store the new overflow address.
18114 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18119 .addOperand(Segment)
18120 .addReg(NextAddrReg)
18121 .setMemRefs(MMOBegin, MMOEnd);
18123 // If we branched, emit the PHI to the front of endMBB.
18125 BuildMI(*endMBB, endMBB->begin(), DL,
18126 TII->get(X86::PHI), DestReg)
18127 .addReg(OffsetDestReg).addMBB(offsetMBB)
18128 .addReg(OverflowDestReg).addMBB(overflowMBB);
18131 // Erase the pseudo instruction
18132 MI->eraseFromParent();
18137 MachineBasicBlock *
18138 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18140 MachineBasicBlock *MBB) const {
18141 // Emit code to save XMM registers to the stack. The ABI says that the
18142 // number of registers to save is given in %al, so it's theoretically
18143 // possible to do an indirect jump trick to avoid saving all of them,
18144 // however this code takes a simpler approach and just executes all
18145 // of the stores if %al is non-zero. It's less code, and it's probably
18146 // easier on the hardware branch predictor, and stores aren't all that
18147 // expensive anyway.
18149 // Create the new basic blocks. One block contains all the XMM stores,
18150 // and one block is the final destination regardless of whether any
18151 // stores were performed.
18152 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18153 MachineFunction *F = MBB->getParent();
18154 MachineFunction::iterator MBBIter = MBB;
18156 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18157 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18158 F->insert(MBBIter, XMMSaveMBB);
18159 F->insert(MBBIter, EndMBB);
18161 // Transfer the remainder of MBB and its successor edges to EndMBB.
18162 EndMBB->splice(EndMBB->begin(), MBB,
18163 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18164 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18166 // The original block will now fall through to the XMM save block.
18167 MBB->addSuccessor(XMMSaveMBB);
18168 // The XMMSaveMBB will fall through to the end block.
18169 XMMSaveMBB->addSuccessor(EndMBB);
18171 // Now add the instructions.
18172 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18173 DebugLoc DL = MI->getDebugLoc();
18175 unsigned CountReg = MI->getOperand(0).getReg();
18176 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18177 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18179 if (!Subtarget->isTargetWin64()) {
18180 // If %al is 0, branch around the XMM save block.
18181 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18182 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
18183 MBB->addSuccessor(EndMBB);
18186 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18187 // that was just emitted, but clearly shouldn't be "saved".
18188 assert((MI->getNumOperands() <= 3 ||
18189 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18190 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18191 && "Expected last argument to be EFLAGS");
18192 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18193 // In the XMM save block, save all the XMM argument registers.
18194 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18195 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18196 MachineMemOperand *MMO =
18197 F->getMachineMemOperand(
18198 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18199 MachineMemOperand::MOStore,
18200 /*Size=*/16, /*Align=*/16);
18201 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18202 .addFrameIndex(RegSaveFrameIndex)
18203 .addImm(/*Scale=*/1)
18204 .addReg(/*IndexReg=*/0)
18205 .addImm(/*Disp=*/Offset)
18206 .addReg(/*Segment=*/0)
18207 .addReg(MI->getOperand(i).getReg())
18208 .addMemOperand(MMO);
18211 MI->eraseFromParent(); // The pseudo instruction is gone now.
18216 // The EFLAGS operand of SelectItr might be missing a kill marker
18217 // because there were multiple uses of EFLAGS, and ISel didn't know
18218 // which to mark. Figure out whether SelectItr should have had a
18219 // kill marker, and set it if it should. Returns the correct kill
18221 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18222 MachineBasicBlock* BB,
18223 const TargetRegisterInfo* TRI) {
18224 // Scan forward through BB for a use/def of EFLAGS.
18225 MachineBasicBlock::iterator miI(std::next(SelectItr));
18226 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18227 const MachineInstr& mi = *miI;
18228 if (mi.readsRegister(X86::EFLAGS))
18230 if (mi.definesRegister(X86::EFLAGS))
18231 break; // Should have kill-flag - update below.
18234 // If we hit the end of the block, check whether EFLAGS is live into a
18236 if (miI == BB->end()) {
18237 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18238 sEnd = BB->succ_end();
18239 sItr != sEnd; ++sItr) {
18240 MachineBasicBlock* succ = *sItr;
18241 if (succ->isLiveIn(X86::EFLAGS))
18246 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18247 // out. SelectMI should have a kill flag on EFLAGS.
18248 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18252 MachineBasicBlock *
18253 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18254 MachineBasicBlock *BB) const {
18255 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18256 DebugLoc DL = MI->getDebugLoc();
18258 // To "insert" a SELECT_CC instruction, we actually have to insert the
18259 // diamond control-flow pattern. The incoming instruction knows the
18260 // destination vreg to set, the condition code register to branch on, the
18261 // true/false values to select between, and a branch opcode to use.
18262 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18263 MachineFunction::iterator It = BB;
18269 // cmpTY ccX, r1, r2
18271 // fallthrough --> copy0MBB
18272 MachineBasicBlock *thisMBB = BB;
18273 MachineFunction *F = BB->getParent();
18274 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18275 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18276 F->insert(It, copy0MBB);
18277 F->insert(It, sinkMBB);
18279 // If the EFLAGS register isn't dead in the terminator, then claim that it's
18280 // live into the sink and copy blocks.
18281 const TargetRegisterInfo *TRI =
18282 BB->getParent()->getSubtarget().getRegisterInfo();
18283 if (!MI->killsRegister(X86::EFLAGS) &&
18284 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18285 copy0MBB->addLiveIn(X86::EFLAGS);
18286 sinkMBB->addLiveIn(X86::EFLAGS);
18289 // Transfer the remainder of BB and its successor edges to sinkMBB.
18290 sinkMBB->splice(sinkMBB->begin(), BB,
18291 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18292 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18294 // Add the true and fallthrough blocks as its successors.
18295 BB->addSuccessor(copy0MBB);
18296 BB->addSuccessor(sinkMBB);
18298 // Create the conditional branch instruction.
18300 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18301 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18304 // %FalseValue = ...
18305 // # fallthrough to sinkMBB
18306 copy0MBB->addSuccessor(sinkMBB);
18309 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18311 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18312 TII->get(X86::PHI), MI->getOperand(0).getReg())
18313 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18314 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18316 MI->eraseFromParent(); // The pseudo instruction is gone now.
18320 MachineBasicBlock *
18321 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18322 bool Is64Bit) const {
18323 MachineFunction *MF = BB->getParent();
18324 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18325 DebugLoc DL = MI->getDebugLoc();
18326 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18328 assert(MF->shouldSplitStack());
18330 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18331 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18334 // ... [Till the alloca]
18335 // If stacklet is not large enough, jump to mallocMBB
18338 // Allocate by subtracting from RSP
18339 // Jump to continueMBB
18342 // Allocate by call to runtime
18346 // [rest of original BB]
18349 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18350 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18351 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18353 MachineRegisterInfo &MRI = MF->getRegInfo();
18354 const TargetRegisterClass *AddrRegClass =
18355 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18357 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18358 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18359 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18360 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18361 sizeVReg = MI->getOperand(1).getReg(),
18362 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18364 MachineFunction::iterator MBBIter = BB;
18367 MF->insert(MBBIter, bumpMBB);
18368 MF->insert(MBBIter, mallocMBB);
18369 MF->insert(MBBIter, continueMBB);
18371 continueMBB->splice(continueMBB->begin(), BB,
18372 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18373 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18375 // Add code to the main basic block to check if the stack limit has been hit,
18376 // and if so, jump to mallocMBB otherwise to bumpMBB.
18377 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18378 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18379 .addReg(tmpSPVReg).addReg(sizeVReg);
18380 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18381 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18382 .addReg(SPLimitVReg);
18383 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18385 // bumpMBB simply decreases the stack pointer, since we know the current
18386 // stacklet has enough space.
18387 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18388 .addReg(SPLimitVReg);
18389 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18390 .addReg(SPLimitVReg);
18391 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18393 // Calls into a routine in libgcc to allocate more space from the heap.
18394 const uint32_t *RegMask = MF->getTarget()
18395 .getSubtargetImpl()
18396 ->getRegisterInfo()
18397 ->getCallPreservedMask(CallingConv::C);
18399 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18401 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18402 .addExternalSymbol("__morestack_allocate_stack_space")
18403 .addRegMask(RegMask)
18404 .addReg(X86::RDI, RegState::Implicit)
18405 .addReg(X86::RAX, RegState::ImplicitDefine);
18407 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18409 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18410 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18411 .addExternalSymbol("__morestack_allocate_stack_space")
18412 .addRegMask(RegMask)
18413 .addReg(X86::EAX, RegState::ImplicitDefine);
18417 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18420 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18421 .addReg(Is64Bit ? X86::RAX : X86::EAX);
18422 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18424 // Set up the CFG correctly.
18425 BB->addSuccessor(bumpMBB);
18426 BB->addSuccessor(mallocMBB);
18427 mallocMBB->addSuccessor(continueMBB);
18428 bumpMBB->addSuccessor(continueMBB);
18430 // Take care of the PHI nodes.
18431 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18432 MI->getOperand(0).getReg())
18433 .addReg(mallocPtrVReg).addMBB(mallocMBB)
18434 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18436 // Delete the original pseudo instruction.
18437 MI->eraseFromParent();
18440 return continueMBB;
18443 MachineBasicBlock *
18444 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18445 MachineBasicBlock *BB) const {
18446 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18447 DebugLoc DL = MI->getDebugLoc();
18449 assert(!Subtarget->isTargetMacho());
18451 // The lowering is pretty easy: we're just emitting the call to _alloca. The
18452 // non-trivial part is impdef of ESP.
18454 if (Subtarget->isTargetWin64()) {
18455 if (Subtarget->isTargetCygMing()) {
18456 // ___chkstk(Mingw64):
18457 // Clobbers R10, R11, RAX and EFLAGS.
18459 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18460 .addExternalSymbol("___chkstk")
18461 .addReg(X86::RAX, RegState::Implicit)
18462 .addReg(X86::RSP, RegState::Implicit)
18463 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18464 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18465 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18467 // __chkstk(MSVCRT): does not update stack pointer.
18468 // Clobbers R10, R11 and EFLAGS.
18469 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18470 .addExternalSymbol("__chkstk")
18471 .addReg(X86::RAX, RegState::Implicit)
18472 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18473 // RAX has the offset to be subtracted from RSP.
18474 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18479 const char *StackProbeSymbol =
18480 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18482 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18483 .addExternalSymbol(StackProbeSymbol)
18484 .addReg(X86::EAX, RegState::Implicit)
18485 .addReg(X86::ESP, RegState::Implicit)
18486 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18487 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18488 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18491 MI->eraseFromParent(); // The pseudo instruction is gone now.
18495 MachineBasicBlock *
18496 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18497 MachineBasicBlock *BB) const {
18498 // This is pretty easy. We're taking the value that we received from
18499 // our load from the relocation, sticking it in either RDI (x86-64)
18500 // or EAX and doing an indirect call. The return value will then
18501 // be in the normal return register.
18502 MachineFunction *F = BB->getParent();
18503 const X86InstrInfo *TII =
18504 static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18505 DebugLoc DL = MI->getDebugLoc();
18507 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18508 assert(MI->getOperand(3).isGlobal() && "This should be a global");
18510 // Get a register mask for the lowered call.
18511 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18512 // proper register mask.
18513 const uint32_t *RegMask = F->getTarget()
18514 .getSubtargetImpl()
18515 ->getRegisterInfo()
18516 ->getCallPreservedMask(CallingConv::C);
18517 if (Subtarget->is64Bit()) {
18518 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18519 TII->get(X86::MOV64rm), X86::RDI)
18521 .addImm(0).addReg(0)
18522 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18523 MI->getOperand(3).getTargetFlags())
18525 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18526 addDirectMem(MIB, X86::RDI);
18527 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18528 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18529 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18530 TII->get(X86::MOV32rm), X86::EAX)
18532 .addImm(0).addReg(0)
18533 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18534 MI->getOperand(3).getTargetFlags())
18536 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18537 addDirectMem(MIB, X86::EAX);
18538 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18540 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18541 TII->get(X86::MOV32rm), X86::EAX)
18542 .addReg(TII->getGlobalBaseReg(F))
18543 .addImm(0).addReg(0)
18544 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18545 MI->getOperand(3).getTargetFlags())
18547 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18548 addDirectMem(MIB, X86::EAX);
18549 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18552 MI->eraseFromParent(); // The pseudo instruction is gone now.
18556 MachineBasicBlock *
18557 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18558 MachineBasicBlock *MBB) const {
18559 DebugLoc DL = MI->getDebugLoc();
18560 MachineFunction *MF = MBB->getParent();
18561 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18562 MachineRegisterInfo &MRI = MF->getRegInfo();
18564 const BasicBlock *BB = MBB->getBasicBlock();
18565 MachineFunction::iterator I = MBB;
18568 // Memory Reference
18569 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18570 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18573 unsigned MemOpndSlot = 0;
18575 unsigned CurOp = 0;
18577 DstReg = MI->getOperand(CurOp++).getReg();
18578 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18579 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18580 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18581 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18583 MemOpndSlot = CurOp;
18585 MVT PVT = getPointerTy();
18586 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18587 "Invalid Pointer Size!");
18589 // For v = setjmp(buf), we generate
18592 // buf[LabelOffset] = restoreMBB
18593 // SjLjSetup restoreMBB
18599 // v = phi(main, restore)
18604 MachineBasicBlock *thisMBB = MBB;
18605 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18606 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18607 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18608 MF->insert(I, mainMBB);
18609 MF->insert(I, sinkMBB);
18610 MF->push_back(restoreMBB);
18612 MachineInstrBuilder MIB;
18614 // Transfer the remainder of BB and its successor edges to sinkMBB.
18615 sinkMBB->splice(sinkMBB->begin(), MBB,
18616 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18617 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18620 unsigned PtrStoreOpc = 0;
18621 unsigned LabelReg = 0;
18622 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18623 Reloc::Model RM = MF->getTarget().getRelocationModel();
18624 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18625 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18627 // Prepare IP either in reg or imm.
18628 if (!UseImmLabel) {
18629 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18630 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18631 LabelReg = MRI.createVirtualRegister(PtrRC);
18632 if (Subtarget->is64Bit()) {
18633 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18637 .addMBB(restoreMBB)
18640 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18641 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18642 .addReg(XII->getGlobalBaseReg(MF))
18645 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18649 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18651 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18652 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18653 if (i == X86::AddrDisp)
18654 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18656 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18659 MIB.addReg(LabelReg);
18661 MIB.addMBB(restoreMBB);
18662 MIB.setMemRefs(MMOBegin, MMOEnd);
18664 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18665 .addMBB(restoreMBB);
18667 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18668 MF->getSubtarget().getRegisterInfo());
18669 MIB.addRegMask(RegInfo->getNoPreservedMask());
18670 thisMBB->addSuccessor(mainMBB);
18671 thisMBB->addSuccessor(restoreMBB);
18675 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18676 mainMBB->addSuccessor(sinkMBB);
18679 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18680 TII->get(X86::PHI), DstReg)
18681 .addReg(mainDstReg).addMBB(mainMBB)
18682 .addReg(restoreDstReg).addMBB(restoreMBB);
18685 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18686 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18687 restoreMBB->addSuccessor(sinkMBB);
18689 MI->eraseFromParent();
18693 MachineBasicBlock *
18694 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18695 MachineBasicBlock *MBB) const {
18696 DebugLoc DL = MI->getDebugLoc();
18697 MachineFunction *MF = MBB->getParent();
18698 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18699 MachineRegisterInfo &MRI = MF->getRegInfo();
18701 // Memory Reference
18702 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18703 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18705 MVT PVT = getPointerTy();
18706 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18707 "Invalid Pointer Size!");
18709 const TargetRegisterClass *RC =
18710 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18711 unsigned Tmp = MRI.createVirtualRegister(RC);
18712 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18713 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18714 MF->getSubtarget().getRegisterInfo());
18715 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18716 unsigned SP = RegInfo->getStackRegister();
18718 MachineInstrBuilder MIB;
18720 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18721 const int64_t SPOffset = 2 * PVT.getStoreSize();
18723 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18724 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18727 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18728 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18729 MIB.addOperand(MI->getOperand(i));
18730 MIB.setMemRefs(MMOBegin, MMOEnd);
18732 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18733 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18734 if (i == X86::AddrDisp)
18735 MIB.addDisp(MI->getOperand(i), LabelOffset);
18737 MIB.addOperand(MI->getOperand(i));
18739 MIB.setMemRefs(MMOBegin, MMOEnd);
18741 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18742 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18743 if (i == X86::AddrDisp)
18744 MIB.addDisp(MI->getOperand(i), SPOffset);
18746 MIB.addOperand(MI->getOperand(i));
18748 MIB.setMemRefs(MMOBegin, MMOEnd);
18750 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18752 MI->eraseFromParent();
18756 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18757 // accumulator loops. Writing back to the accumulator allows the coalescer
18758 // to remove extra copies in the loop.
18759 MachineBasicBlock *
18760 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18761 MachineBasicBlock *MBB) const {
18762 MachineOperand &AddendOp = MI->getOperand(3);
18764 // Bail out early if the addend isn't a register - we can't switch these.
18765 if (!AddendOp.isReg())
18768 MachineFunction &MF = *MBB->getParent();
18769 MachineRegisterInfo &MRI = MF.getRegInfo();
18771 // Check whether the addend is defined by a PHI:
18772 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18773 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18774 if (!AddendDef.isPHI())
18777 // Look for the following pattern:
18779 // %addend = phi [%entry, 0], [%loop, %result]
18781 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18785 // %addend = phi [%entry, 0], [%loop, %result]
18787 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18789 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18790 assert(AddendDef.getOperand(i).isReg());
18791 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18792 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18793 if (&PHISrcInst == MI) {
18794 // Found a matching instruction.
18795 unsigned NewFMAOpc = 0;
18796 switch (MI->getOpcode()) {
18797 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18798 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18799 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18800 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18801 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18802 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18803 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18804 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18805 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18806 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18807 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18808 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18809 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18810 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18811 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18812 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18813 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18814 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18815 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18816 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18817 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18818 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18819 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18820 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18821 default: llvm_unreachable("Unrecognized FMA variant.");
18824 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18825 MachineInstrBuilder MIB =
18826 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18827 .addOperand(MI->getOperand(0))
18828 .addOperand(MI->getOperand(3))
18829 .addOperand(MI->getOperand(2))
18830 .addOperand(MI->getOperand(1));
18831 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18832 MI->eraseFromParent();
18839 MachineBasicBlock *
18840 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18841 MachineBasicBlock *BB) const {
18842 switch (MI->getOpcode()) {
18843 default: llvm_unreachable("Unexpected instr type to insert");
18844 case X86::TAILJMPd64:
18845 case X86::TAILJMPr64:
18846 case X86::TAILJMPm64:
18847 llvm_unreachable("TAILJMP64 would not be touched here.");
18848 case X86::TCRETURNdi64:
18849 case X86::TCRETURNri64:
18850 case X86::TCRETURNmi64:
18852 case X86::WIN_ALLOCA:
18853 return EmitLoweredWinAlloca(MI, BB);
18854 case X86::SEG_ALLOCA_32:
18855 return EmitLoweredSegAlloca(MI, BB, false);
18856 case X86::SEG_ALLOCA_64:
18857 return EmitLoweredSegAlloca(MI, BB, true);
18858 case X86::TLSCall_32:
18859 case X86::TLSCall_64:
18860 return EmitLoweredTLSCall(MI, BB);
18861 case X86::CMOV_GR8:
18862 case X86::CMOV_FR32:
18863 case X86::CMOV_FR64:
18864 case X86::CMOV_V4F32:
18865 case X86::CMOV_V2F64:
18866 case X86::CMOV_V2I64:
18867 case X86::CMOV_V8F32:
18868 case X86::CMOV_V4F64:
18869 case X86::CMOV_V4I64:
18870 case X86::CMOV_V16F32:
18871 case X86::CMOV_V8F64:
18872 case X86::CMOV_V8I64:
18873 case X86::CMOV_GR16:
18874 case X86::CMOV_GR32:
18875 case X86::CMOV_RFP32:
18876 case X86::CMOV_RFP64:
18877 case X86::CMOV_RFP80:
18878 return EmitLoweredSelect(MI, BB);
18880 case X86::FP32_TO_INT16_IN_MEM:
18881 case X86::FP32_TO_INT32_IN_MEM:
18882 case X86::FP32_TO_INT64_IN_MEM:
18883 case X86::FP64_TO_INT16_IN_MEM:
18884 case X86::FP64_TO_INT32_IN_MEM:
18885 case X86::FP64_TO_INT64_IN_MEM:
18886 case X86::FP80_TO_INT16_IN_MEM:
18887 case X86::FP80_TO_INT32_IN_MEM:
18888 case X86::FP80_TO_INT64_IN_MEM: {
18889 MachineFunction *F = BB->getParent();
18890 const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
18891 DebugLoc DL = MI->getDebugLoc();
18893 // Change the floating point control register to use "round towards zero"
18894 // mode when truncating to an integer value.
18895 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18896 addFrameReference(BuildMI(*BB, MI, DL,
18897 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18899 // Load the old value of the high byte of the control word...
18901 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18902 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18905 // Set the high part to be round to zero...
18906 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18909 // Reload the modified control word now...
18910 addFrameReference(BuildMI(*BB, MI, DL,
18911 TII->get(X86::FLDCW16m)), CWFrameIdx);
18913 // Restore the memory image of control word to original value
18914 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18917 // Get the X86 opcode to use.
18919 switch (MI->getOpcode()) {
18920 default: llvm_unreachable("illegal opcode!");
18921 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18922 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18923 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18924 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18925 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18926 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18927 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18928 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18929 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18933 MachineOperand &Op = MI->getOperand(0);
18935 AM.BaseType = X86AddressMode::RegBase;
18936 AM.Base.Reg = Op.getReg();
18938 AM.BaseType = X86AddressMode::FrameIndexBase;
18939 AM.Base.FrameIndex = Op.getIndex();
18941 Op = MI->getOperand(1);
18943 AM.Scale = Op.getImm();
18944 Op = MI->getOperand(2);
18946 AM.IndexReg = Op.getImm();
18947 Op = MI->getOperand(3);
18948 if (Op.isGlobal()) {
18949 AM.GV = Op.getGlobal();
18951 AM.Disp = Op.getImm();
18953 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18954 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18956 // Reload the original control word now.
18957 addFrameReference(BuildMI(*BB, MI, DL,
18958 TII->get(X86::FLDCW16m)), CWFrameIdx);
18960 MI->eraseFromParent(); // The pseudo instruction is gone now.
18963 // String/text processing lowering.
18964 case X86::PCMPISTRM128REG:
18965 case X86::VPCMPISTRM128REG:
18966 case X86::PCMPISTRM128MEM:
18967 case X86::VPCMPISTRM128MEM:
18968 case X86::PCMPESTRM128REG:
18969 case X86::VPCMPESTRM128REG:
18970 case X86::PCMPESTRM128MEM:
18971 case X86::VPCMPESTRM128MEM:
18972 assert(Subtarget->hasSSE42() &&
18973 "Target must have SSE4.2 or AVX features enabled");
18974 return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18976 // String/text processing lowering.
18977 case X86::PCMPISTRIREG:
18978 case X86::VPCMPISTRIREG:
18979 case X86::PCMPISTRIMEM:
18980 case X86::VPCMPISTRIMEM:
18981 case X86::PCMPESTRIREG:
18982 case X86::VPCMPESTRIREG:
18983 case X86::PCMPESTRIMEM:
18984 case X86::VPCMPESTRIMEM:
18985 assert(Subtarget->hasSSE42() &&
18986 "Target must have SSE4.2 or AVX features enabled");
18987 return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18989 // Thread synchronization.
18991 return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
18996 return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18998 case X86::VASTART_SAVE_XMM_REGS:
18999 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19001 case X86::VAARG_64:
19002 return EmitVAARG64WithCustomInserter(MI, BB);
19004 case X86::EH_SjLj_SetJmp32:
19005 case X86::EH_SjLj_SetJmp64:
19006 return emitEHSjLjSetJmp(MI, BB);
19008 case X86::EH_SjLj_LongJmp32:
19009 case X86::EH_SjLj_LongJmp64:
19010 return emitEHSjLjLongJmp(MI, BB);
19012 case TargetOpcode::STACKMAP:
19013 case TargetOpcode::PATCHPOINT:
19014 return emitPatchPoint(MI, BB);
19016 case X86::VFMADDPDr213r:
19017 case X86::VFMADDPSr213r:
19018 case X86::VFMADDSDr213r:
19019 case X86::VFMADDSSr213r:
19020 case X86::VFMSUBPDr213r:
19021 case X86::VFMSUBPSr213r:
19022 case X86::VFMSUBSDr213r:
19023 case X86::VFMSUBSSr213r:
19024 case X86::VFNMADDPDr213r:
19025 case X86::VFNMADDPSr213r:
19026 case X86::VFNMADDSDr213r:
19027 case X86::VFNMADDSSr213r:
19028 case X86::VFNMSUBPDr213r:
19029 case X86::VFNMSUBPSr213r:
19030 case X86::VFNMSUBSDr213r:
19031 case X86::VFNMSUBSSr213r:
19032 case X86::VFMADDPDr213rY:
19033 case X86::VFMADDPSr213rY:
19034 case X86::VFMSUBPDr213rY:
19035 case X86::VFMSUBPSr213rY:
19036 case X86::VFNMADDPDr213rY:
19037 case X86::VFNMADDPSr213rY:
19038 case X86::VFNMSUBPDr213rY:
19039 case X86::VFNMSUBPSr213rY:
19040 return emitFMA3Instr(MI, BB);
19044 //===----------------------------------------------------------------------===//
19045 // X86 Optimization Hooks
19046 //===----------------------------------------------------------------------===//
19048 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19051 const SelectionDAG &DAG,
19052 unsigned Depth) const {
19053 unsigned BitWidth = KnownZero.getBitWidth();
19054 unsigned Opc = Op.getOpcode();
19055 assert((Opc >= ISD::BUILTIN_OP_END ||
19056 Opc == ISD::INTRINSIC_WO_CHAIN ||
19057 Opc == ISD::INTRINSIC_W_CHAIN ||
19058 Opc == ISD::INTRINSIC_VOID) &&
19059 "Should use MaskedValueIsZero if you don't know whether Op"
19060 " is a target node!");
19062 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
19076 // These nodes' second result is a boolean.
19077 if (Op.getResNo() == 0)
19080 case X86ISD::SETCC:
19081 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19083 case ISD::INTRINSIC_WO_CHAIN: {
19084 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19085 unsigned NumLoBits = 0;
19088 case Intrinsic::x86_sse_movmsk_ps:
19089 case Intrinsic::x86_avx_movmsk_ps_256:
19090 case Intrinsic::x86_sse2_movmsk_pd:
19091 case Intrinsic::x86_avx_movmsk_pd_256:
19092 case Intrinsic::x86_mmx_pmovmskb:
19093 case Intrinsic::x86_sse2_pmovmskb_128:
19094 case Intrinsic::x86_avx2_pmovmskb: {
19095 // High bits of movmskp{s|d}, pmovmskb are known zero.
19097 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
19098 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
19099 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
19100 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
19101 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
19102 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
19103 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
19104 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
19106 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19115 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19117 const SelectionDAG &,
19118 unsigned Depth) const {
19119 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19120 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19121 return Op.getValueType().getScalarType().getSizeInBits();
19127 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19128 /// node is a GlobalAddress + offset.
19129 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19130 const GlobalValue* &GA,
19131 int64_t &Offset) const {
19132 if (N->getOpcode() == X86ISD::Wrapper) {
19133 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19134 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19135 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19139 return TargetLowering::isGAPlusOffset(N, GA, Offset);
19142 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19143 /// same as extracting the high 128-bit part of 256-bit vector and then
19144 /// inserting the result into the low part of a new 256-bit vector
19145 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19146 EVT VT = SVOp->getValueType(0);
19147 unsigned NumElems = VT.getVectorNumElements();
19149 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19150 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19151 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19152 SVOp->getMaskElt(j) >= 0)
19158 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19159 /// same as extracting the low 128-bit part of 256-bit vector and then
19160 /// inserting the result into the high part of a new 256-bit vector
19161 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19162 EVT VT = SVOp->getValueType(0);
19163 unsigned NumElems = VT.getVectorNumElements();
19165 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19166 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19167 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19168 SVOp->getMaskElt(j) >= 0)
19174 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19175 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19176 TargetLowering::DAGCombinerInfo &DCI,
19177 const X86Subtarget* Subtarget) {
19179 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19180 SDValue V1 = SVOp->getOperand(0);
19181 SDValue V2 = SVOp->getOperand(1);
19182 EVT VT = SVOp->getValueType(0);
19183 unsigned NumElems = VT.getVectorNumElements();
19185 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19186 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19190 // V UNDEF BUILD_VECTOR UNDEF
19192 // CONCAT_VECTOR CONCAT_VECTOR
19195 // RESULT: V + zero extended
19197 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19198 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19199 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19202 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19205 // To match the shuffle mask, the first half of the mask should
19206 // be exactly the first vector, and all the rest a splat with the
19207 // first element of the second one.
19208 for (unsigned i = 0; i != NumElems/2; ++i)
19209 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19210 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19213 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19214 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19215 if (Ld->hasNUsesOfValue(1, 0)) {
19216 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19217 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19219 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19221 Ld->getPointerInfo(),
19222 Ld->getAlignment(),
19223 false/*isVolatile*/, true/*ReadMem*/,
19224 false/*WriteMem*/);
19226 // Make sure the newly-created LOAD is in the same position as Ld in
19227 // terms of dependency. We create a TokenFactor for Ld and ResNode,
19228 // and update uses of Ld's output chain to use the TokenFactor.
19229 if (Ld->hasAnyUseOfValue(1)) {
19230 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19231 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19232 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19233 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19234 SDValue(ResNode.getNode(), 1));
19237 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19241 // Emit a zeroed vector and insert the desired subvector on its
19243 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19244 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19245 return DCI.CombineTo(N, InsV);
19248 //===--------------------------------------------------------------------===//
19249 // Combine some shuffles into subvector extracts and inserts:
19252 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19253 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19254 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19255 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19256 return DCI.CombineTo(N, InsV);
19259 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19260 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19261 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19262 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19263 return DCI.CombineTo(N, InsV);
19269 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19272 /// This is the leaf of the recursive combinine below. When we have found some
19273 /// chain of single-use x86 shuffle instructions and accumulated the combined
19274 /// shuffle mask represented by them, this will try to pattern match that mask
19275 /// into either a single instruction if there is a special purpose instruction
19276 /// for this operation, or into a PSHUFB instruction which is a fully general
19277 /// instruction but should only be used to replace chains over a certain depth.
19278 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19279 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19280 TargetLowering::DAGCombinerInfo &DCI,
19281 const X86Subtarget *Subtarget) {
19282 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19284 // Find the operand that enters the chain. Note that multiple uses are OK
19285 // here, we're not going to remove the operand we find.
19286 SDValue Input = Op.getOperand(0);
19287 while (Input.getOpcode() == ISD::BITCAST)
19288 Input = Input.getOperand(0);
19290 MVT VT = Input.getSimpleValueType();
19291 MVT RootVT = Root.getSimpleValueType();
19294 // Just remove no-op shuffle masks.
19295 if (Mask.size() == 1) {
19296 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19301 // Use the float domain if the operand type is a floating point type.
19302 bool FloatDomain = VT.isFloatingPoint();
19304 // For floating point shuffles, we don't have free copies in the shuffle
19305 // instructions, so this always makes sense to canonicalize.
19307 // For integer shuffles, if we don't have access to VEX encodings, the generic
19308 // PSHUF instructions are preferable to some of the specialized forms despite
19309 // requiring one more byte to encode because they can implicitly copy.
19311 // IF we *do* have VEX encodings, then we can use shorter, more specific
19312 // shuffle instructions freely as they can copy due to the extra register
19314 if (FloatDomain || Subtarget->hasAVX()) {
19315 // We have both floating point and integer variants of shuffles that dup
19316 // either the low or high half of the vector.
19317 if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19318 bool Lo = Mask.equals(0, 0);
19321 // If the input is a floating point, check if we have SSE3 which will let
19322 // us use MOVDDUP. That instruction is no slower than UNPCKLPD but has the
19323 // option to fold the input operand into even an unaligned memory load.
19324 if (FloatDomain && Lo && Subtarget->hasSSE3()) {
19325 Shuffle = X86ISD::MOVDDUP;
19326 ShuffleVT = MVT::v2f64;
19327 } else if (FloatDomain) {
19328 // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19329 // than the UNPCK variants.
19330 Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19331 ShuffleVT = MVT::v4f32;
19332 } else if (Subtarget->hasSSE2()) {
19333 // We model everything else using UNPCK instructions. While MOVLHPS and
19334 // MOVHLPS are shorter encodings they cannot accept a memory operand
19335 // which overly constrains subsequent lowering.
19336 Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19337 ShuffleVT = MVT::v2i64;
19339 // No available instructions here.
19342 if (Depth == 1 && Root->getOpcode() == Shuffle)
19343 return false; // Nothing to do!
19344 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19345 DCI.AddToWorklist(Op.getNode());
19346 if (Shuffle == X86ISD::MOVDDUP)
19347 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19349 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19350 DCI.AddToWorklist(Op.getNode());
19351 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19356 // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19358 // For the integer domain we have specialized instructions for duplicating
19359 // any element size from the low or high half.
19360 if (!FloatDomain &&
19361 (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19362 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19363 Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19364 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19365 Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19367 bool Lo = Mask[0] == 0;
19368 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19369 if (Depth == 1 && Root->getOpcode() == Shuffle)
19370 return false; // Nothing to do!
19372 switch (Mask.size()) {
19373 case 4: ShuffleVT = MVT::v4i32; break;
19374 case 8: ShuffleVT = MVT::v8i16; break;
19375 case 16: ShuffleVT = MVT::v16i8; break;
19377 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19378 DCI.AddToWorklist(Op.getNode());
19379 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19380 DCI.AddToWorklist(Op.getNode());
19381 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19387 // Don't try to re-form single instruction chains under any circumstances now
19388 // that we've done encoding canonicalization for them.
19392 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19393 // can replace them with a single PSHUFB instruction profitably. Intel's
19394 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19395 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19396 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19397 SmallVector<SDValue, 16> PSHUFBMask;
19398 assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19399 int Ratio = 16 / Mask.size();
19400 for (unsigned i = 0; i < 16; ++i) {
19401 int M = Mask[i / Ratio] != SM_SentinelZero
19402 ? Ratio * Mask[i / Ratio] + i % Ratio
19404 PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19406 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19407 DCI.AddToWorklist(Op.getNode());
19408 SDValue PSHUFBMaskOp =
19409 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19410 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19411 Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19412 DCI.AddToWorklist(Op.getNode());
19413 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19418 // Failed to find any combines.
19422 /// \brief Fully generic combining of x86 shuffle instructions.
19424 /// This should be the last combine run over the x86 shuffle instructions. Once
19425 /// they have been fully optimized, this will recursively consider all chains
19426 /// of single-use shuffle instructions, build a generic model of the cumulative
19427 /// shuffle operation, and check for simpler instructions which implement this
19428 /// operation. We use this primarily for two purposes:
19430 /// 1) Collapse generic shuffles to specialized single instructions when
19431 /// equivalent. In most cases, this is just an encoding size win, but
19432 /// sometimes we will collapse multiple generic shuffles into a single
19433 /// special-purpose shuffle.
19434 /// 2) Look for sequences of shuffle instructions with 3 or more total
19435 /// instructions, and replace them with the slightly more expensive SSSE3
19436 /// PSHUFB instruction if available. We do this as the last combining step
19437 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
19438 /// a suitable short sequence of other instructions. The PHUFB will either
19439 /// use a register or have to read from memory and so is slightly (but only
19440 /// slightly) more expensive than the other shuffle instructions.
19442 /// Because this is inherently a quadratic operation (for each shuffle in
19443 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19444 /// This should never be an issue in practice as the shuffle lowering doesn't
19445 /// produce sequences of more than 8 instructions.
19447 /// FIXME: We will currently miss some cases where the redundant shuffling
19448 /// would simplify under the threshold for PSHUFB formation because of
19449 /// combine-ordering. To fix this, we should do the redundant instruction
19450 /// combining in this recursive walk.
19451 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19452 ArrayRef<int> RootMask,
19453 int Depth, bool HasPSHUFB,
19455 TargetLowering::DAGCombinerInfo &DCI,
19456 const X86Subtarget *Subtarget) {
19457 // Bound the depth of our recursive combine because this is ultimately
19458 // quadratic in nature.
19462 // Directly rip through bitcasts to find the underlying operand.
19463 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19464 Op = Op.getOperand(0);
19466 MVT VT = Op.getSimpleValueType();
19467 if (!VT.isVector())
19468 return false; // Bail if we hit a non-vector.
19469 // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19470 // version should be added.
19471 if (VT.getSizeInBits() != 128)
19474 assert(Root.getSimpleValueType().isVector() &&
19475 "Shuffles operate on vector types!");
19476 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19477 "Can only combine shuffles of the same vector register size.");
19479 if (!isTargetShuffle(Op.getOpcode()))
19481 SmallVector<int, 16> OpMask;
19483 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19484 // We only can combine unary shuffles which we can decode the mask for.
19485 if (!HaveMask || !IsUnary)
19488 assert(VT.getVectorNumElements() == OpMask.size() &&
19489 "Different mask size from vector size!");
19490 assert(((RootMask.size() > OpMask.size() &&
19491 RootMask.size() % OpMask.size() == 0) ||
19492 (OpMask.size() > RootMask.size() &&
19493 OpMask.size() % RootMask.size() == 0) ||
19494 OpMask.size() == RootMask.size()) &&
19495 "The smaller number of elements must divide the larger.");
19496 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19497 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19498 assert(((RootRatio == 1 && OpRatio == 1) ||
19499 (RootRatio == 1) != (OpRatio == 1)) &&
19500 "Must not have a ratio for both incoming and op masks!");
19502 SmallVector<int, 16> Mask;
19503 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19505 // Merge this shuffle operation's mask into our accumulated mask. Note that
19506 // this shuffle's mask will be the first applied to the input, followed by the
19507 // root mask to get us all the way to the root value arrangement. The reason
19508 // for this order is that we are recursing up the operation chain.
19509 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19510 int RootIdx = i / RootRatio;
19511 if (RootMask[RootIdx] == SM_SentinelZero) {
19512 // This is a zero-ed lane, we're done.
19513 Mask.push_back(SM_SentinelZero);
19517 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19518 int OpIdx = RootMaskedIdx / OpRatio;
19519 if (OpMask[OpIdx] == SM_SentinelZero) {
19520 // The incoming lanes are zero, it doesn't matter which ones we are using.
19521 Mask.push_back(SM_SentinelZero);
19525 // Ok, we have non-zero lanes, map them through.
19526 Mask.push_back(OpMask[OpIdx] * OpRatio +
19527 RootMaskedIdx % OpRatio);
19530 // See if we can recurse into the operand to combine more things.
19531 switch (Op.getOpcode()) {
19532 case X86ISD::PSHUFB:
19534 case X86ISD::PSHUFD:
19535 case X86ISD::PSHUFHW:
19536 case X86ISD::PSHUFLW:
19537 if (Op.getOperand(0).hasOneUse() &&
19538 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19539 HasPSHUFB, DAG, DCI, Subtarget))
19543 case X86ISD::UNPCKL:
19544 case X86ISD::UNPCKH:
19545 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19546 // We can't check for single use, we have to check that this shuffle is the only user.
19547 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19548 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19549 HasPSHUFB, DAG, DCI, Subtarget))
19554 // Minor canonicalization of the accumulated shuffle mask to make it easier
19555 // to match below. All this does is detect masks with squential pairs of
19556 // elements, and shrink them to the half-width mask. It does this in a loop
19557 // so it will reduce the size of the mask to the minimal width mask which
19558 // performs an equivalent shuffle.
19559 while (Mask.size() > 1 && canWidenShuffleElements(Mask)) {
19560 for (int i = 0, e = Mask.size() / 2; i < e; ++i)
19561 Mask[i] = Mask[2 * i] / 2;
19562 Mask.resize(Mask.size() / 2);
19565 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19569 /// \brief Get the PSHUF-style mask from PSHUF node.
19571 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19572 /// PSHUF-style masks that can be reused with such instructions.
19573 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19574 SmallVector<int, 4> Mask;
19576 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19580 switch (N.getOpcode()) {
19581 case X86ISD::PSHUFD:
19583 case X86ISD::PSHUFLW:
19586 case X86ISD::PSHUFHW:
19587 Mask.erase(Mask.begin(), Mask.begin() + 4);
19588 for (int &M : Mask)
19592 llvm_unreachable("No valid shuffle instruction found!");
19596 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19598 /// We walk up the chain and look for a combinable shuffle, skipping over
19599 /// shuffles that we could hoist this shuffle's transformation past without
19600 /// altering anything.
19602 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19604 TargetLowering::DAGCombinerInfo &DCI) {
19605 assert(N.getOpcode() == X86ISD::PSHUFD &&
19606 "Called with something other than an x86 128-bit half shuffle!");
19609 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19610 // of the shuffles in the chain so that we can form a fresh chain to replace
19612 SmallVector<SDValue, 8> Chain;
19613 SDValue V = N.getOperand(0);
19614 for (; V.hasOneUse(); V = V.getOperand(0)) {
19615 switch (V.getOpcode()) {
19617 return SDValue(); // Nothing combined!
19620 // Skip bitcasts as we always know the type for the target specific
19624 case X86ISD::PSHUFD:
19625 // Found another dword shuffle.
19628 case X86ISD::PSHUFLW:
19629 // Check that the low words (being shuffled) are the identity in the
19630 // dword shuffle, and the high words are self-contained.
19631 if (Mask[0] != 0 || Mask[1] != 1 ||
19632 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19635 Chain.push_back(V);
19638 case X86ISD::PSHUFHW:
19639 // Check that the high words (being shuffled) are the identity in the
19640 // dword shuffle, and the low words are self-contained.
19641 if (Mask[2] != 2 || Mask[3] != 3 ||
19642 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19645 Chain.push_back(V);
19648 case X86ISD::UNPCKL:
19649 case X86ISD::UNPCKH:
19650 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19651 // shuffle into a preceding word shuffle.
19652 if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19655 // Search for a half-shuffle which we can combine with.
19656 unsigned CombineOp =
19657 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19658 if (V.getOperand(0) != V.getOperand(1) ||
19659 !V->isOnlyUserOf(V.getOperand(0).getNode()))
19661 Chain.push_back(V);
19662 V = V.getOperand(0);
19664 switch (V.getOpcode()) {
19666 return SDValue(); // Nothing to combine.
19668 case X86ISD::PSHUFLW:
19669 case X86ISD::PSHUFHW:
19670 if (V.getOpcode() == CombineOp)
19673 Chain.push_back(V);
19677 V = V.getOperand(0);
19681 } while (V.hasOneUse());
19684 // Break out of the loop if we break out of the switch.
19688 if (!V.hasOneUse())
19689 // We fell out of the loop without finding a viable combining instruction.
19692 // Merge this node's mask and our incoming mask.
19693 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19694 for (int &M : Mask)
19696 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19697 getV4X86ShuffleImm8ForMask(Mask, DAG));
19699 // Rebuild the chain around this new shuffle.
19700 while (!Chain.empty()) {
19701 SDValue W = Chain.pop_back_val();
19703 if (V.getValueType() != W.getOperand(0).getValueType())
19704 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19706 switch (W.getOpcode()) {
19708 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19710 case X86ISD::UNPCKL:
19711 case X86ISD::UNPCKH:
19712 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19715 case X86ISD::PSHUFD:
19716 case X86ISD::PSHUFLW:
19717 case X86ISD::PSHUFHW:
19718 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19722 if (V.getValueType() != N.getValueType())
19723 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19725 // Return the new chain to replace N.
19729 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19731 /// We walk up the chain, skipping shuffles of the other half and looking
19732 /// through shuffles which switch halves trying to find a shuffle of the same
19733 /// pair of dwords.
19734 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19736 TargetLowering::DAGCombinerInfo &DCI) {
19738 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19739 "Called with something other than an x86 128-bit half shuffle!");
19741 unsigned CombineOpcode = N.getOpcode();
19743 // Walk up a single-use chain looking for a combinable shuffle.
19744 SDValue V = N.getOperand(0);
19745 for (; V.hasOneUse(); V = V.getOperand(0)) {
19746 switch (V.getOpcode()) {
19748 return false; // Nothing combined!
19751 // Skip bitcasts as we always know the type for the target specific
19755 case X86ISD::PSHUFLW:
19756 case X86ISD::PSHUFHW:
19757 if (V.getOpcode() == CombineOpcode)
19760 // Other-half shuffles are no-ops.
19763 // Break out of the loop if we break out of the switch.
19767 if (!V.hasOneUse())
19768 // We fell out of the loop without finding a viable combining instruction.
19771 // Combine away the bottom node as its shuffle will be accumulated into
19772 // a preceding shuffle.
19773 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19775 // Record the old value.
19778 // Merge this node's mask and our incoming mask (adjusted to account for all
19779 // the pshufd instructions encountered).
19780 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19781 for (int &M : Mask)
19783 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19784 getV4X86ShuffleImm8ForMask(Mask, DAG));
19786 // Check that the shuffles didn't cancel each other out. If not, we need to
19787 // combine to the new one.
19789 // Replace the combinable shuffle with the combined one, updating all users
19790 // so that we re-evaluate the chain here.
19791 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19796 /// \brief Try to combine x86 target specific shuffles.
19797 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19798 TargetLowering::DAGCombinerInfo &DCI,
19799 const X86Subtarget *Subtarget) {
19801 MVT VT = N.getSimpleValueType();
19802 SmallVector<int, 4> Mask;
19804 switch (N.getOpcode()) {
19805 case X86ISD::PSHUFD:
19806 case X86ISD::PSHUFLW:
19807 case X86ISD::PSHUFHW:
19808 Mask = getPSHUFShuffleMask(N);
19809 assert(Mask.size() == 4);
19815 // Nuke no-op shuffles that show up after combining.
19816 if (isNoopShuffleMask(Mask))
19817 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19819 // Look for simplifications involving one or two shuffle instructions.
19820 SDValue V = N.getOperand(0);
19821 switch (N.getOpcode()) {
19824 case X86ISD::PSHUFLW:
19825 case X86ISD::PSHUFHW:
19826 assert(VT == MVT::v8i16);
19829 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19830 return SDValue(); // We combined away this shuffle, so we're done.
19832 // See if this reduces to a PSHUFD which is no more expensive and can
19833 // combine with more operations.
19834 if (canWidenShuffleElements(Mask)) {
19835 int DMask[] = {-1, -1, -1, -1};
19836 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19837 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19838 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19839 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19840 DCI.AddToWorklist(V.getNode());
19841 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19842 getV4X86ShuffleImm8ForMask(DMask, DAG));
19843 DCI.AddToWorklist(V.getNode());
19844 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19847 // Look for shuffle patterns which can be implemented as a single unpack.
19848 // FIXME: This doesn't handle the location of the PSHUFD generically, and
19849 // only works when we have a PSHUFD followed by two half-shuffles.
19850 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19851 (V.getOpcode() == X86ISD::PSHUFLW ||
19852 V.getOpcode() == X86ISD::PSHUFHW) &&
19853 V.getOpcode() != N.getOpcode() &&
19855 SDValue D = V.getOperand(0);
19856 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19857 D = D.getOperand(0);
19858 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19859 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19860 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19861 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19862 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19864 for (int i = 0; i < 4; ++i) {
19865 WordMask[i + NOffset] = Mask[i] + NOffset;
19866 WordMask[i + VOffset] = VMask[i] + VOffset;
19868 // Map the word mask through the DWord mask.
19870 for (int i = 0; i < 8; ++i)
19871 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19872 const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19873 const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19874 if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19875 std::begin(UnpackLoMask)) ||
19876 std::equal(std::begin(MappedMask), std::end(MappedMask),
19877 std::begin(UnpackHiMask))) {
19878 // We can replace all three shuffles with an unpack.
19879 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19880 DCI.AddToWorklist(V.getNode());
19881 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19883 DL, MVT::v8i16, V, V);
19890 case X86ISD::PSHUFD:
19891 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19900 /// PerformShuffleCombine - Performs several different shuffle combines.
19901 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19902 TargetLowering::DAGCombinerInfo &DCI,
19903 const X86Subtarget *Subtarget) {
19905 SDValue N0 = N->getOperand(0);
19906 SDValue N1 = N->getOperand(1);
19907 EVT VT = N->getValueType(0);
19909 // Don't create instructions with illegal types after legalize types has run.
19910 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19911 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19914 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19915 if (Subtarget->hasFp256() && VT.is256BitVector() &&
19916 N->getOpcode() == ISD::VECTOR_SHUFFLE)
19917 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19919 // During Type Legalization, when promoting illegal vector types,
19920 // the backend might introduce new shuffle dag nodes and bitcasts.
19922 // This code performs the following transformation:
19923 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19924 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19926 // We do this only if both the bitcast and the BINOP dag nodes have
19927 // one use. Also, perform this transformation only if the new binary
19928 // operation is legal. This is to avoid introducing dag nodes that
19929 // potentially need to be further expanded (or custom lowered) into a
19930 // less optimal sequence of dag nodes.
19931 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19932 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19933 N0.getOpcode() == ISD::BITCAST) {
19934 SDValue BC0 = N0.getOperand(0);
19935 EVT SVT = BC0.getValueType();
19936 unsigned Opcode = BC0.getOpcode();
19937 unsigned NumElts = VT.getVectorNumElements();
19939 if (BC0.hasOneUse() && SVT.isVector() &&
19940 SVT.getVectorNumElements() * 2 == NumElts &&
19941 TLI.isOperationLegal(Opcode, VT)) {
19942 bool CanFold = false;
19954 unsigned SVTNumElts = SVT.getVectorNumElements();
19955 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19956 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19957 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19958 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19959 CanFold = SVOp->getMaskElt(i) < 0;
19962 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19963 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19964 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19965 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19970 // Only handle 128 wide vector from here on.
19971 if (!VT.is128BitVector())
19974 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19975 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19976 // consecutive, non-overlapping, and in the right order.
19977 SmallVector<SDValue, 16> Elts;
19978 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19979 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19981 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19985 if (isTargetShuffle(N->getOpcode())) {
19987 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19988 if (Shuffle.getNode())
19991 // Try recursively combining arbitrary sequences of x86 shuffle
19992 // instructions into higher-order shuffles. We do this after combining
19993 // specific PSHUF instruction sequences into their minimal form so that we
19994 // can evaluate how many specialized shuffle instructions are involved in
19995 // a particular chain.
19996 SmallVector<int, 1> NonceMask; // Just a placeholder.
19997 NonceMask.push_back(0);
19998 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19999 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20001 return SDValue(); // This routine will use CombineTo to replace N.
20007 /// PerformTruncateCombine - Converts truncate operation to
20008 /// a sequence of vector shuffle operations.
20009 /// It is possible when we truncate 256-bit vector to 128-bit vector
20010 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20011 TargetLowering::DAGCombinerInfo &DCI,
20012 const X86Subtarget *Subtarget) {
20016 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20017 /// specific shuffle of a load can be folded into a single element load.
20018 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20019 /// shuffles have been customed lowered so we need to handle those here.
20020 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20021 TargetLowering::DAGCombinerInfo &DCI) {
20022 if (DCI.isBeforeLegalizeOps())
20025 SDValue InVec = N->getOperand(0);
20026 SDValue EltNo = N->getOperand(1);
20028 if (!isa<ConstantSDNode>(EltNo))
20031 EVT VT = InVec.getValueType();
20033 if (InVec.getOpcode() == ISD::BITCAST) {
20034 // Don't duplicate a load with other uses.
20035 if (!InVec.hasOneUse())
20037 EVT BCVT = InVec.getOperand(0).getValueType();
20038 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
20040 InVec = InVec.getOperand(0);
20043 if (!isTargetShuffle(InVec.getOpcode()))
20046 // Don't duplicate a load with other uses.
20047 if (!InVec.hasOneUse())
20050 SmallVector<int, 16> ShuffleMask;
20052 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
20056 // Select the input vector, guarding against out of range extract vector.
20057 unsigned NumElems = VT.getVectorNumElements();
20058 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20059 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20060 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20061 : InVec.getOperand(1);
20063 // If inputs to shuffle are the same for both ops, then allow 2 uses
20064 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20066 if (LdNode.getOpcode() == ISD::BITCAST) {
20067 // Don't duplicate a load with other uses.
20068 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20071 AllowedUses = 1; // only allow 1 load use if we have a bitcast
20072 LdNode = LdNode.getOperand(0);
20075 if (!ISD::isNormalLoad(LdNode.getNode()))
20078 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20080 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20083 EVT EltVT = N->getValueType(0);
20084 // If there's a bitcast before the shuffle, check if the load type and
20085 // alignment is valid.
20086 unsigned Align = LN0->getAlignment();
20087 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20088 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20089 EltVT.getTypeForEVT(*DAG.getContext()));
20091 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20094 // All checks match so transform back to vector_shuffle so that DAG combiner
20095 // can finish the job
20098 // Create shuffle node taking into account the case that its a unary shuffle
20099 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
20100 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
20101 InVec.getOperand(0), Shuffle,
20103 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
20104 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20108 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20109 /// generation and convert it from being a bunch of shuffles and extracts
20110 /// to a simple store and scalar loads to extract the elements.
20111 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20112 TargetLowering::DAGCombinerInfo &DCI) {
20113 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20114 if (NewOp.getNode())
20117 SDValue InputVector = N->getOperand(0);
20119 // Detect whether we are trying to convert from mmx to i32 and the bitcast
20120 // from mmx to v2i32 has a single usage.
20121 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
20122 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
20123 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
20124 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20125 N->getValueType(0),
20126 InputVector.getNode()->getOperand(0));
20128 // Only operate on vectors of 4 elements, where the alternative shuffling
20129 // gets to be more expensive.
20130 if (InputVector.getValueType() != MVT::v4i32)
20133 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20134 // single use which is a sign-extend or zero-extend, and all elements are
20136 SmallVector<SDNode *, 4> Uses;
20137 unsigned ExtractedElements = 0;
20138 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20139 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20140 if (UI.getUse().getResNo() != InputVector.getResNo())
20143 SDNode *Extract = *UI;
20144 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20147 if (Extract->getValueType(0) != MVT::i32)
20149 if (!Extract->hasOneUse())
20151 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20152 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20154 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20157 // Record which element was extracted.
20158 ExtractedElements |=
20159 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20161 Uses.push_back(Extract);
20164 // If not all the elements were used, this may not be worthwhile.
20165 if (ExtractedElements != 15)
20168 // Ok, we've now decided to do the transformation.
20169 SDLoc dl(InputVector);
20171 // Store the value to a temporary stack slot.
20172 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20173 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20174 MachinePointerInfo(), false, false, 0);
20176 // Replace each use (extract) with a load of the appropriate element.
20177 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20178 UE = Uses.end(); UI != UE; ++UI) {
20179 SDNode *Extract = *UI;
20181 // cOMpute the element's address.
20182 SDValue Idx = Extract->getOperand(1);
20184 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
20185 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
20186 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20187 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20189 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20190 StackPtr, OffsetVal);
20192 // Load the scalar.
20193 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
20194 ScalarAddr, MachinePointerInfo(),
20195 false, false, false, 0);
20197 // Replace the exact with the load.
20198 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
20201 // The replacement was made in place; don't return anything.
20205 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20206 static std::pair<unsigned, bool>
20207 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20208 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20209 if (!VT.isVector())
20210 return std::make_pair(0, false);
20212 bool NeedSplit = false;
20213 switch (VT.getSimpleVT().SimpleTy) {
20214 default: return std::make_pair(0, false);
20218 if (!Subtarget->hasAVX2())
20220 if (!Subtarget->hasAVX())
20221 return std::make_pair(0, false);
20226 if (!Subtarget->hasSSE2())
20227 return std::make_pair(0, false);
20230 // SSE2 has only a small subset of the operations.
20231 bool hasUnsigned = Subtarget->hasSSE41() ||
20232 (Subtarget->hasSSE2() && VT == MVT::v16i8);
20233 bool hasSigned = Subtarget->hasSSE41() ||
20234 (Subtarget->hasSSE2() && VT == MVT::v8i16);
20236 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20239 // Check for x CC y ? x : y.
20240 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20241 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20246 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20249 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20252 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20255 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20257 // Check for x CC y ? y : x -- a min/max with reversed arms.
20258 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20259 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20264 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20267 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20270 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20273 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20277 return std::make_pair(Opc, NeedSplit);
20281 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20282 const X86Subtarget *Subtarget) {
20284 SDValue Cond = N->getOperand(0);
20285 SDValue LHS = N->getOperand(1);
20286 SDValue RHS = N->getOperand(2);
20288 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20289 SDValue CondSrc = Cond->getOperand(0);
20290 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20291 Cond = CondSrc->getOperand(0);
20294 MVT VT = N->getSimpleValueType(0);
20295 MVT EltVT = VT.getVectorElementType();
20296 unsigned NumElems = VT.getVectorNumElements();
20297 // There is no blend with immediate in AVX-512.
20298 if (VT.is512BitVector())
20301 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
20303 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
20306 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20309 // A vselect where all conditions and data are constants can be optimized into
20310 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20311 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20312 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20315 unsigned MaskValue = 0;
20316 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20319 SmallVector<int, 8> ShuffleMask(NumElems, -1);
20320 for (unsigned i = 0; i < NumElems; ++i) {
20321 // Be sure we emit undef where we can.
20322 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20323 ShuffleMask[i] = -1;
20325 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20328 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20331 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20333 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20334 TargetLowering::DAGCombinerInfo &DCI,
20335 const X86Subtarget *Subtarget) {
20337 SDValue Cond = N->getOperand(0);
20338 // Get the LHS/RHS of the select.
20339 SDValue LHS = N->getOperand(1);
20340 SDValue RHS = N->getOperand(2);
20341 EVT VT = LHS.getValueType();
20342 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20344 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20345 // instructions match the semantics of the common C idiom x<y?x:y but not
20346 // x<=y?x:y, because of how they handle negative zero (which can be
20347 // ignored in unsafe-math mode).
20348 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20349 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20350 (Subtarget->hasSSE2() ||
20351 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20352 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20354 unsigned Opcode = 0;
20355 // Check for x CC y ? x : y.
20356 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20357 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20361 // Converting this to a min would handle NaNs incorrectly, and swapping
20362 // the operands would cause it to handle comparisons between positive
20363 // and negative zero incorrectly.
20364 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20365 if (!DAG.getTarget().Options.UnsafeFPMath &&
20366 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20368 std::swap(LHS, RHS);
20370 Opcode = X86ISD::FMIN;
20373 // Converting this to a min would handle comparisons between positive
20374 // and negative zero incorrectly.
20375 if (!DAG.getTarget().Options.UnsafeFPMath &&
20376 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20378 Opcode = X86ISD::FMIN;
20381 // Converting this to a min would handle both negative zeros and NaNs
20382 // incorrectly, but we can swap the operands to fix both.
20383 std::swap(LHS, RHS);
20387 Opcode = X86ISD::FMIN;
20391 // Converting this to a max would handle comparisons between positive
20392 // and negative zero incorrectly.
20393 if (!DAG.getTarget().Options.UnsafeFPMath &&
20394 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20396 Opcode = X86ISD::FMAX;
20399 // Converting this to a max would handle NaNs incorrectly, and swapping
20400 // the operands would cause it to handle comparisons between positive
20401 // and negative zero incorrectly.
20402 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20403 if (!DAG.getTarget().Options.UnsafeFPMath &&
20404 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20406 std::swap(LHS, RHS);
20408 Opcode = X86ISD::FMAX;
20411 // Converting this to a max would handle both negative zeros and NaNs
20412 // incorrectly, but we can swap the operands to fix both.
20413 std::swap(LHS, RHS);
20417 Opcode = X86ISD::FMAX;
20420 // Check for x CC y ? y : x -- a min/max with reversed arms.
20421 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20422 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20426 // Converting this to a min would handle comparisons between positive
20427 // and negative zero incorrectly, and swapping the operands would
20428 // cause it to handle NaNs incorrectly.
20429 if (!DAG.getTarget().Options.UnsafeFPMath &&
20430 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20431 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20433 std::swap(LHS, RHS);
20435 Opcode = X86ISD::FMIN;
20438 // Converting this to a min would handle NaNs incorrectly.
20439 if (!DAG.getTarget().Options.UnsafeFPMath &&
20440 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20442 Opcode = X86ISD::FMIN;
20445 // Converting this to a min would handle both negative zeros and NaNs
20446 // incorrectly, but we can swap the operands to fix both.
20447 std::swap(LHS, RHS);
20451 Opcode = X86ISD::FMIN;
20455 // Converting this to a max would handle NaNs incorrectly.
20456 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20458 Opcode = X86ISD::FMAX;
20461 // Converting this to a max would handle comparisons between positive
20462 // and negative zero incorrectly, and swapping the operands would
20463 // cause it to handle NaNs incorrectly.
20464 if (!DAG.getTarget().Options.UnsafeFPMath &&
20465 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20466 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20468 std::swap(LHS, RHS);
20470 Opcode = X86ISD::FMAX;
20473 // Converting this to a max would handle both negative zeros and NaNs
20474 // incorrectly, but we can swap the operands to fix both.
20475 std::swap(LHS, RHS);
20479 Opcode = X86ISD::FMAX;
20485 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20488 EVT CondVT = Cond.getValueType();
20489 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20490 CondVT.getVectorElementType() == MVT::i1) {
20491 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20492 // lowering on KNL. In this case we convert it to
20493 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20494 // The same situation for all 128 and 256-bit vectors of i8 and i16.
20495 // Since SKX these selects have a proper lowering.
20496 EVT OpVT = LHS.getValueType();
20497 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20498 (OpVT.getVectorElementType() == MVT::i8 ||
20499 OpVT.getVectorElementType() == MVT::i16) &&
20500 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20501 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20502 DCI.AddToWorklist(Cond.getNode());
20503 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20506 // If this is a select between two integer constants, try to do some
20508 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20509 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20510 // Don't do this for crazy integer types.
20511 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20512 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20513 // so that TrueC (the true value) is larger than FalseC.
20514 bool NeedsCondInvert = false;
20516 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20517 // Efficiently invertible.
20518 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
20519 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
20520 isa<ConstantSDNode>(Cond.getOperand(1))))) {
20521 NeedsCondInvert = true;
20522 std::swap(TrueC, FalseC);
20525 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
20526 if (FalseC->getAPIntValue() == 0 &&
20527 TrueC->getAPIntValue().isPowerOf2()) {
20528 if (NeedsCondInvert) // Invert the condition if needed.
20529 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20530 DAG.getConstant(1, Cond.getValueType()));
20532 // Zero extend the condition if needed.
20533 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20535 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20536 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20537 DAG.getConstant(ShAmt, MVT::i8));
20540 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20541 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20542 if (NeedsCondInvert) // Invert the condition if needed.
20543 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20544 DAG.getConstant(1, Cond.getValueType()));
20546 // Zero extend the condition if needed.
20547 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20548 FalseC->getValueType(0), Cond);
20549 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20550 SDValue(FalseC, 0));
20553 // Optimize cases that will turn into an LEA instruction. This requires
20554 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20555 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20556 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20557 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20559 bool isFastMultiplier = false;
20561 switch ((unsigned char)Diff) {
20563 case 1: // result = add base, cond
20564 case 2: // result = lea base( , cond*2)
20565 case 3: // result = lea base(cond, cond*2)
20566 case 4: // result = lea base( , cond*4)
20567 case 5: // result = lea base(cond, cond*4)
20568 case 8: // result = lea base( , cond*8)
20569 case 9: // result = lea base(cond, cond*8)
20570 isFastMultiplier = true;
20575 if (isFastMultiplier) {
20576 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20577 if (NeedsCondInvert) // Invert the condition if needed.
20578 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20579 DAG.getConstant(1, Cond.getValueType()));
20581 // Zero extend the condition if needed.
20582 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20584 // Scale the condition by the difference.
20586 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20587 DAG.getConstant(Diff, Cond.getValueType()));
20589 // Add the base if non-zero.
20590 if (FalseC->getAPIntValue() != 0)
20591 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20592 SDValue(FalseC, 0));
20599 // Canonicalize max and min:
20600 // (x > y) ? x : y -> (x >= y) ? x : y
20601 // (x < y) ? x : y -> (x <= y) ? x : y
20602 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20603 // the need for an extra compare
20604 // against zero. e.g.
20605 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20607 // testl %edi, %edi
20609 // cmovgl %edi, %eax
20613 // cmovsl %eax, %edi
20614 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20615 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20616 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20617 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20622 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20623 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20624 Cond.getOperand(0), Cond.getOperand(1), NewCC);
20625 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20630 // Early exit check
20631 if (!TLI.isTypeLegal(VT))
20634 // Match VSELECTs into subs with unsigned saturation.
20635 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20636 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20637 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20638 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20639 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20641 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20642 // left side invert the predicate to simplify logic below.
20644 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20646 CC = ISD::getSetCCInverse(CC, true);
20647 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20651 if (Other.getNode() && Other->getNumOperands() == 2 &&
20652 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20653 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20654 SDValue CondRHS = Cond->getOperand(1);
20656 // Look for a general sub with unsigned saturation first.
20657 // x >= y ? x-y : 0 --> subus x, y
20658 // x > y ? x-y : 0 --> subus x, y
20659 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20660 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20661 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20663 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20664 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20665 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20666 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20667 // If the RHS is a constant we have to reverse the const
20668 // canonicalization.
20669 // x > C-1 ? x+-C : 0 --> subus x, C
20670 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20671 CondRHSConst->getAPIntValue() ==
20672 (-OpRHSConst->getAPIntValue() - 1))
20673 return DAG.getNode(
20674 X86ISD::SUBUS, DL, VT, OpLHS,
20675 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20677 // Another special case: If C was a sign bit, the sub has been
20678 // canonicalized into a xor.
20679 // FIXME: Would it be better to use computeKnownBits to determine
20680 // whether it's safe to decanonicalize the xor?
20681 // x s< 0 ? x^C : 0 --> subus x, C
20682 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20683 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20684 OpRHSConst->getAPIntValue().isSignBit())
20685 // Note that we have to rebuild the RHS constant here to ensure we
20686 // don't rely on particular values of undef lanes.
20687 return DAG.getNode(
20688 X86ISD::SUBUS, DL, VT, OpLHS,
20689 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20694 // Try to match a min/max vector operation.
20695 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20696 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20697 unsigned Opc = ret.first;
20698 bool NeedSplit = ret.second;
20700 if (Opc && NeedSplit) {
20701 unsigned NumElems = VT.getVectorNumElements();
20702 // Extract the LHS vectors
20703 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20704 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20706 // Extract the RHS vectors
20707 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20708 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20710 // Create min/max for each subvector
20711 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20712 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20714 // Merge the result
20715 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20717 return DAG.getNode(Opc, DL, VT, LHS, RHS);
20720 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20721 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20722 // Check if SETCC has already been promoted
20723 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20724 // Check that condition value type matches vselect operand type
20727 assert(Cond.getValueType().isVector() &&
20728 "vector select expects a vector selector!");
20730 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20731 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20733 if (!TValIsAllOnes && !FValIsAllZeros) {
20734 // Try invert the condition if true value is not all 1s and false value
20736 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20737 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20739 if (TValIsAllZeros || FValIsAllOnes) {
20740 SDValue CC = Cond.getOperand(2);
20741 ISD::CondCode NewCC =
20742 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20743 Cond.getOperand(0).getValueType().isInteger());
20744 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20745 std::swap(LHS, RHS);
20746 TValIsAllOnes = FValIsAllOnes;
20747 FValIsAllZeros = TValIsAllZeros;
20751 if (TValIsAllOnes || FValIsAllZeros) {
20754 if (TValIsAllOnes && FValIsAllZeros)
20756 else if (TValIsAllOnes)
20757 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20758 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20759 else if (FValIsAllZeros)
20760 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20761 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20763 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20767 // Try to fold this VSELECT into a MOVSS/MOVSD
20768 if (N->getOpcode() == ISD::VSELECT &&
20769 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20770 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20771 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20772 bool CanFold = false;
20773 unsigned NumElems = Cond.getNumOperands();
20777 if (isZero(Cond.getOperand(0))) {
20780 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20781 // fold (vselect <0,-1> -> (movsd A, B)
20782 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20783 CanFold = isAllOnes(Cond.getOperand(i));
20784 } else if (isAllOnes(Cond.getOperand(0))) {
20788 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20789 // fold (vselect <-1,0> -> (movsd B, A)
20790 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20791 CanFold = isZero(Cond.getOperand(i));
20795 if (VT == MVT::v4i32 || VT == MVT::v4f32)
20796 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20797 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20800 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20801 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20802 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20803 // (v2i64 (bitcast B)))))
20805 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20806 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20807 // (v2f64 (bitcast B)))))
20809 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20810 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20811 // (v2i64 (bitcast A)))))
20813 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20814 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20815 // (v2f64 (bitcast A)))))
20817 CanFold = (isZero(Cond.getOperand(0)) &&
20818 isZero(Cond.getOperand(1)) &&
20819 isAllOnes(Cond.getOperand(2)) &&
20820 isAllOnes(Cond.getOperand(3)));
20822 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20823 isAllOnes(Cond.getOperand(1)) &&
20824 isZero(Cond.getOperand(2)) &&
20825 isZero(Cond.getOperand(3))) {
20827 std::swap(LHS, RHS);
20831 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20832 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20833 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20834 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20836 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20842 // If we know that this node is legal then we know that it is going to be
20843 // matched by one of the SSE/AVX BLEND instructions. These instructions only
20844 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20845 // to simplify previous instructions.
20846 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20847 !DCI.isBeforeLegalize() &&
20848 // We explicitly check against v8i16 and v16i16 because, although
20849 // they're marked as Custom, they might only be legal when Cond is a
20850 // build_vector of constants. This will be taken care in a later
20852 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20853 VT != MVT::v8i16)) {
20854 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20856 // Don't optimize vector selects that map to mask-registers.
20860 // Check all uses of that condition operand to check whether it will be
20861 // consumed by non-BLEND instructions, which may depend on all bits are set
20863 for (SDNode::use_iterator I = Cond->use_begin(),
20864 E = Cond->use_end(); I != E; ++I)
20865 if (I->getOpcode() != ISD::VSELECT)
20866 // TODO: Add other opcodes eventually lowered into BLEND.
20869 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20870 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20872 APInt KnownZero, KnownOne;
20873 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20874 DCI.isBeforeLegalizeOps());
20875 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20876 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20877 DCI.CommitTargetLoweringOpt(TLO);
20880 // We should generate an X86ISD::BLENDI from a vselect if its argument
20881 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20882 // constants. This specific pattern gets generated when we split a
20883 // selector for a 512 bit vector in a machine without AVX512 (but with
20884 // 256-bit vectors), during legalization:
20886 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20888 // Iff we find this pattern and the build_vectors are built from
20889 // constants, we translate the vselect into a shuffle_vector that we
20890 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20891 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20892 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20893 if (Shuffle.getNode())
20900 // Check whether a boolean test is testing a boolean value generated by
20901 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20904 // Simplify the following patterns:
20905 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20906 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20907 // to (Op EFLAGS Cond)
20909 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20910 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20911 // to (Op EFLAGS !Cond)
20913 // where Op could be BRCOND or CMOV.
20915 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20916 // Quit if not CMP and SUB with its value result used.
20917 if (Cmp.getOpcode() != X86ISD::CMP &&
20918 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20921 // Quit if not used as a boolean value.
20922 if (CC != X86::COND_E && CC != X86::COND_NE)
20925 // Check CMP operands. One of them should be 0 or 1 and the other should be
20926 // an SetCC or extended from it.
20927 SDValue Op1 = Cmp.getOperand(0);
20928 SDValue Op2 = Cmp.getOperand(1);
20931 const ConstantSDNode* C = nullptr;
20932 bool needOppositeCond = (CC == X86::COND_E);
20933 bool checkAgainstTrue = false; // Is it a comparison against 1?
20935 if ((C = dyn_cast<ConstantSDNode>(Op1)))
20937 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20939 else // Quit if all operands are not constants.
20942 if (C->getZExtValue() == 1) {
20943 needOppositeCond = !needOppositeCond;
20944 checkAgainstTrue = true;
20945 } else if (C->getZExtValue() != 0)
20946 // Quit if the constant is neither 0 or 1.
20949 bool truncatedToBoolWithAnd = false;
20950 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20951 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20952 SetCC.getOpcode() == ISD::TRUNCATE ||
20953 SetCC.getOpcode() == ISD::AND) {
20954 if (SetCC.getOpcode() == ISD::AND) {
20956 ConstantSDNode *CS;
20957 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20958 CS->getZExtValue() == 1)
20960 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20961 CS->getZExtValue() == 1)
20965 SetCC = SetCC.getOperand(OpIdx);
20966 truncatedToBoolWithAnd = true;
20968 SetCC = SetCC.getOperand(0);
20971 switch (SetCC.getOpcode()) {
20972 case X86ISD::SETCC_CARRY:
20973 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20974 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20975 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20976 // truncated to i1 using 'and'.
20977 if (checkAgainstTrue && !truncatedToBoolWithAnd)
20979 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20980 "Invalid use of SETCC_CARRY!");
20982 case X86ISD::SETCC:
20983 // Set the condition code or opposite one if necessary.
20984 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20985 if (needOppositeCond)
20986 CC = X86::GetOppositeBranchCondition(CC);
20987 return SetCC.getOperand(1);
20988 case X86ISD::CMOV: {
20989 // Check whether false/true value has canonical one, i.e. 0 or 1.
20990 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20991 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20992 // Quit if true value is not a constant.
20995 // Quit if false value is not a constant.
20997 SDValue Op = SetCC.getOperand(0);
20998 // Skip 'zext' or 'trunc' node.
20999 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21000 Op.getOpcode() == ISD::TRUNCATE)
21001 Op = Op.getOperand(0);
21002 // A special case for rdrand/rdseed, where 0 is set if false cond is
21004 if ((Op.getOpcode() != X86ISD::RDRAND &&
21005 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21008 // Quit if false value is not the constant 0 or 1.
21009 bool FValIsFalse = true;
21010 if (FVal && FVal->getZExtValue() != 0) {
21011 if (FVal->getZExtValue() != 1)
21013 // If FVal is 1, opposite cond is needed.
21014 needOppositeCond = !needOppositeCond;
21015 FValIsFalse = false;
21017 // Quit if TVal is not the constant opposite of FVal.
21018 if (FValIsFalse && TVal->getZExtValue() != 1)
21020 if (!FValIsFalse && TVal->getZExtValue() != 0)
21022 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21023 if (needOppositeCond)
21024 CC = X86::GetOppositeBranchCondition(CC);
21025 return SetCC.getOperand(3);
21032 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21033 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21034 TargetLowering::DAGCombinerInfo &DCI,
21035 const X86Subtarget *Subtarget) {
21038 // If the flag operand isn't dead, don't touch this CMOV.
21039 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21042 SDValue FalseOp = N->getOperand(0);
21043 SDValue TrueOp = N->getOperand(1);
21044 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21045 SDValue Cond = N->getOperand(3);
21047 if (CC == X86::COND_E || CC == X86::COND_NE) {
21048 switch (Cond.getOpcode()) {
21052 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21053 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21054 return (CC == X86::COND_E) ? FalseOp : TrueOp;
21060 Flags = checkBoolTestSetCCCombine(Cond, CC);
21061 if (Flags.getNode() &&
21062 // Extra check as FCMOV only supports a subset of X86 cond.
21063 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21064 SDValue Ops[] = { FalseOp, TrueOp,
21065 DAG.getConstant(CC, MVT::i8), Flags };
21066 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21069 // If this is a select between two integer constants, try to do some
21070 // optimizations. Note that the operands are ordered the opposite of SELECT
21072 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21073 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21074 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21075 // larger than FalseC (the false value).
21076 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21077 CC = X86::GetOppositeBranchCondition(CC);
21078 std::swap(TrueC, FalseC);
21079 std::swap(TrueOp, FalseOp);
21082 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
21083 // This is efficient for any integer data type (including i8/i16) and
21085 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21086 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21087 DAG.getConstant(CC, MVT::i8), Cond);
21089 // Zero extend the condition if needed.
21090 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21092 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21093 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21094 DAG.getConstant(ShAmt, MVT::i8));
21095 if (N->getNumValues() == 2) // Dead flag value?
21096 return DCI.CombineTo(N, Cond, SDValue());
21100 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
21101 // for any integer data type, including i8/i16.
21102 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21103 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21104 DAG.getConstant(CC, MVT::i8), Cond);
21106 // Zero extend the condition if needed.
21107 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21108 FalseC->getValueType(0), Cond);
21109 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21110 SDValue(FalseC, 0));
21112 if (N->getNumValues() == 2) // Dead flag value?
21113 return DCI.CombineTo(N, Cond, SDValue());
21117 // Optimize cases that will turn into an LEA instruction. This requires
21118 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21119 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21120 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21121 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21123 bool isFastMultiplier = false;
21125 switch ((unsigned char)Diff) {
21127 case 1: // result = add base, cond
21128 case 2: // result = lea base( , cond*2)
21129 case 3: // result = lea base(cond, cond*2)
21130 case 4: // result = lea base( , cond*4)
21131 case 5: // result = lea base(cond, cond*4)
21132 case 8: // result = lea base( , cond*8)
21133 case 9: // result = lea base(cond, cond*8)
21134 isFastMultiplier = true;
21139 if (isFastMultiplier) {
21140 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21141 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21142 DAG.getConstant(CC, MVT::i8), Cond);
21143 // Zero extend the condition if needed.
21144 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21146 // Scale the condition by the difference.
21148 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21149 DAG.getConstant(Diff, Cond.getValueType()));
21151 // Add the base if non-zero.
21152 if (FalseC->getAPIntValue() != 0)
21153 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21154 SDValue(FalseC, 0));
21155 if (N->getNumValues() == 2) // Dead flag value?
21156 return DCI.CombineTo(N, Cond, SDValue());
21163 // Handle these cases:
21164 // (select (x != c), e, c) -> select (x != c), e, x),
21165 // (select (x == c), c, e) -> select (x == c), x, e)
21166 // where the c is an integer constant, and the "select" is the combination
21167 // of CMOV and CMP.
21169 // The rationale for this change is that the conditional-move from a constant
21170 // needs two instructions, however, conditional-move from a register needs
21171 // only one instruction.
21173 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21174 // some instruction-combining opportunities. This opt needs to be
21175 // postponed as late as possible.
21177 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21178 // the DCI.xxxx conditions are provided to postpone the optimization as
21179 // late as possible.
21181 ConstantSDNode *CmpAgainst = nullptr;
21182 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21183 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21184 !isa<ConstantSDNode>(Cond.getOperand(0))) {
21186 if (CC == X86::COND_NE &&
21187 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21188 CC = X86::GetOppositeBranchCondition(CC);
21189 std::swap(TrueOp, FalseOp);
21192 if (CC == X86::COND_E &&
21193 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21194 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21195 DAG.getConstant(CC, MVT::i8), Cond };
21196 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21204 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21205 const X86Subtarget *Subtarget) {
21206 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21208 default: return SDValue();
21209 // SSE/AVX/AVX2 blend intrinsics.
21210 case Intrinsic::x86_avx2_pblendvb:
21211 case Intrinsic::x86_avx2_pblendw:
21212 case Intrinsic::x86_avx2_pblendd_128:
21213 case Intrinsic::x86_avx2_pblendd_256:
21214 // Don't try to simplify this intrinsic if we don't have AVX2.
21215 if (!Subtarget->hasAVX2())
21218 case Intrinsic::x86_avx_blend_pd_256:
21219 case Intrinsic::x86_avx_blend_ps_256:
21220 case Intrinsic::x86_avx_blendv_pd_256:
21221 case Intrinsic::x86_avx_blendv_ps_256:
21222 // Don't try to simplify this intrinsic if we don't have AVX.
21223 if (!Subtarget->hasAVX())
21226 case Intrinsic::x86_sse41_pblendw:
21227 case Intrinsic::x86_sse41_blendpd:
21228 case Intrinsic::x86_sse41_blendps:
21229 case Intrinsic::x86_sse41_blendvps:
21230 case Intrinsic::x86_sse41_blendvpd:
21231 case Intrinsic::x86_sse41_pblendvb: {
21232 SDValue Op0 = N->getOperand(1);
21233 SDValue Op1 = N->getOperand(2);
21234 SDValue Mask = N->getOperand(3);
21236 // Don't try to simplify this intrinsic if we don't have SSE4.1.
21237 if (!Subtarget->hasSSE41())
21240 // fold (blend A, A, Mask) -> A
21243 // fold (blend A, B, allZeros) -> A
21244 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21246 // fold (blend A, B, allOnes) -> B
21247 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21250 // Simplify the case where the mask is a constant i32 value.
21251 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21252 if (C->isNullValue())
21254 if (C->isAllOnesValue())
21261 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21262 case Intrinsic::x86_sse2_psrai_w:
21263 case Intrinsic::x86_sse2_psrai_d:
21264 case Intrinsic::x86_avx2_psrai_w:
21265 case Intrinsic::x86_avx2_psrai_d:
21266 case Intrinsic::x86_sse2_psra_w:
21267 case Intrinsic::x86_sse2_psra_d:
21268 case Intrinsic::x86_avx2_psra_w:
21269 case Intrinsic::x86_avx2_psra_d: {
21270 SDValue Op0 = N->getOperand(1);
21271 SDValue Op1 = N->getOperand(2);
21272 EVT VT = Op0.getValueType();
21273 assert(VT.isVector() && "Expected a vector type!");
21275 if (isa<BuildVectorSDNode>(Op1))
21276 Op1 = Op1.getOperand(0);
21278 if (!isa<ConstantSDNode>(Op1))
21281 EVT SVT = VT.getVectorElementType();
21282 unsigned SVTBits = SVT.getSizeInBits();
21284 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21285 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21286 uint64_t ShAmt = C.getZExtValue();
21288 // Don't try to convert this shift into a ISD::SRA if the shift
21289 // count is bigger than or equal to the element size.
21290 if (ShAmt >= SVTBits)
21293 // Trivial case: if the shift count is zero, then fold this
21294 // into the first operand.
21298 // Replace this packed shift intrinsic with a target independent
21300 SDValue Splat = DAG.getConstant(C, VT);
21301 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21306 /// PerformMulCombine - Optimize a single multiply with constant into two
21307 /// in order to implement it with two cheaper instructions, e.g.
21308 /// LEA + SHL, LEA + LEA.
21309 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21310 TargetLowering::DAGCombinerInfo &DCI) {
21311 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21314 EVT VT = N->getValueType(0);
21315 if (VT != MVT::i64)
21318 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21321 uint64_t MulAmt = C->getZExtValue();
21322 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21325 uint64_t MulAmt1 = 0;
21326 uint64_t MulAmt2 = 0;
21327 if ((MulAmt % 9) == 0) {
21329 MulAmt2 = MulAmt / 9;
21330 } else if ((MulAmt % 5) == 0) {
21332 MulAmt2 = MulAmt / 5;
21333 } else if ((MulAmt % 3) == 0) {
21335 MulAmt2 = MulAmt / 3;
21338 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21341 if (isPowerOf2_64(MulAmt2) &&
21342 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21343 // If second multiplifer is pow2, issue it first. We want the multiply by
21344 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21346 std::swap(MulAmt1, MulAmt2);
21349 if (isPowerOf2_64(MulAmt1))
21350 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21351 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21353 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21354 DAG.getConstant(MulAmt1, VT));
21356 if (isPowerOf2_64(MulAmt2))
21357 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21358 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21360 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21361 DAG.getConstant(MulAmt2, VT));
21363 // Do not add new nodes to DAG combiner worklist.
21364 DCI.CombineTo(N, NewMul, false);
21369 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21370 SDValue N0 = N->getOperand(0);
21371 SDValue N1 = N->getOperand(1);
21372 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21373 EVT VT = N0.getValueType();
21375 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21376 // since the result of setcc_c is all zero's or all ones.
21377 if (VT.isInteger() && !VT.isVector() &&
21378 N1C && N0.getOpcode() == ISD::AND &&
21379 N0.getOperand(1).getOpcode() == ISD::Constant) {
21380 SDValue N00 = N0.getOperand(0);
21381 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21382 ((N00.getOpcode() == ISD::ANY_EXTEND ||
21383 N00.getOpcode() == ISD::ZERO_EXTEND) &&
21384 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21385 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21386 APInt ShAmt = N1C->getAPIntValue();
21387 Mask = Mask.shl(ShAmt);
21389 return DAG.getNode(ISD::AND, SDLoc(N), VT,
21390 N00, DAG.getConstant(Mask, VT));
21394 // Hardware support for vector shifts is sparse which makes us scalarize the
21395 // vector operations in many cases. Also, on sandybridge ADD is faster than
21397 // (shl V, 1) -> add V,V
21398 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21399 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21400 assert(N0.getValueType().isVector() && "Invalid vector shift type");
21401 // We shift all of the values by one. In many cases we do not have
21402 // hardware support for this operation. This is better expressed as an ADD
21404 if (N1SplatC->getZExtValue() == 1)
21405 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21411 /// \brief Returns a vector of 0s if the node in input is a vector logical
21412 /// shift by a constant amount which is known to be bigger than or equal
21413 /// to the vector element size in bits.
21414 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21415 const X86Subtarget *Subtarget) {
21416 EVT VT = N->getValueType(0);
21418 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21419 (!Subtarget->hasInt256() ||
21420 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21423 SDValue Amt = N->getOperand(1);
21425 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21426 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21427 APInt ShiftAmt = AmtSplat->getAPIntValue();
21428 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21430 // SSE2/AVX2 logical shifts always return a vector of 0s
21431 // if the shift amount is bigger than or equal to
21432 // the element size. The constant shift amount will be
21433 // encoded as a 8-bit immediate.
21434 if (ShiftAmt.trunc(8).uge(MaxAmount))
21435 return getZeroVector(VT, Subtarget, DAG, DL);
21441 /// PerformShiftCombine - Combine shifts.
21442 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21443 TargetLowering::DAGCombinerInfo &DCI,
21444 const X86Subtarget *Subtarget) {
21445 if (N->getOpcode() == ISD::SHL) {
21446 SDValue V = PerformSHLCombine(N, DAG);
21447 if (V.getNode()) return V;
21450 if (N->getOpcode() != ISD::SRA) {
21451 // Try to fold this logical shift into a zero vector.
21452 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21453 if (V.getNode()) return V;
21459 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
21460 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21461 // and friends. Likewise for OR -> CMPNEQSS.
21462 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21463 TargetLowering::DAGCombinerInfo &DCI,
21464 const X86Subtarget *Subtarget) {
21467 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21468 // we're requiring SSE2 for both.
21469 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21470 SDValue N0 = N->getOperand(0);
21471 SDValue N1 = N->getOperand(1);
21472 SDValue CMP0 = N0->getOperand(1);
21473 SDValue CMP1 = N1->getOperand(1);
21476 // The SETCCs should both refer to the same CMP.
21477 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21480 SDValue CMP00 = CMP0->getOperand(0);
21481 SDValue CMP01 = CMP0->getOperand(1);
21482 EVT VT = CMP00.getValueType();
21484 if (VT == MVT::f32 || VT == MVT::f64) {
21485 bool ExpectingFlags = false;
21486 // Check for any users that want flags:
21487 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21488 !ExpectingFlags && UI != UE; ++UI)
21489 switch (UI->getOpcode()) {
21494 ExpectingFlags = true;
21496 case ISD::CopyToReg:
21497 case ISD::SIGN_EXTEND:
21498 case ISD::ZERO_EXTEND:
21499 case ISD::ANY_EXTEND:
21503 if (!ExpectingFlags) {
21504 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21505 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21507 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21508 X86::CondCode tmp = cc0;
21513 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
21514 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21515 // FIXME: need symbolic constants for these magic numbers.
21516 // See X86ATTInstPrinter.cpp:printSSECC().
21517 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21518 if (Subtarget->hasAVX512()) {
21519 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21520 CMP01, DAG.getConstant(x86cc, MVT::i8));
21521 if (N->getValueType(0) != MVT::i1)
21522 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21526 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21527 CMP00.getValueType(), CMP00, CMP01,
21528 DAG.getConstant(x86cc, MVT::i8));
21530 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21531 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21533 if (is64BitFP && !Subtarget->is64Bit()) {
21534 // On a 32-bit target, we cannot bitcast the 64-bit float to a
21535 // 64-bit integer, since that's not a legal type. Since
21536 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21537 // bits, but can do this little dance to extract the lowest 32 bits
21538 // and work with those going forward.
21539 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21541 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21543 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21544 Vector32, DAG.getIntPtrConstant(0));
21548 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21549 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21550 DAG.getConstant(1, IntVT));
21551 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21552 return OneBitOfTruth;
21560 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21561 /// so it can be folded inside ANDNP.
21562 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21563 EVT VT = N->getValueType(0);
21565 // Match direct AllOnes for 128 and 256-bit vectors
21566 if (ISD::isBuildVectorAllOnes(N))
21569 // Look through a bit convert.
21570 if (N->getOpcode() == ISD::BITCAST)
21571 N = N->getOperand(0).getNode();
21573 // Sometimes the operand may come from a insert_subvector building a 256-bit
21575 if (VT.is256BitVector() &&
21576 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21577 SDValue V1 = N->getOperand(0);
21578 SDValue V2 = N->getOperand(1);
21580 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21581 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21582 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21583 ISD::isBuildVectorAllOnes(V2.getNode()))
21590 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21591 // register. In most cases we actually compare or select YMM-sized registers
21592 // and mixing the two types creates horrible code. This method optimizes
21593 // some of the transition sequences.
21594 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21595 TargetLowering::DAGCombinerInfo &DCI,
21596 const X86Subtarget *Subtarget) {
21597 EVT VT = N->getValueType(0);
21598 if (!VT.is256BitVector())
21601 assert((N->getOpcode() == ISD::ANY_EXTEND ||
21602 N->getOpcode() == ISD::ZERO_EXTEND ||
21603 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21605 SDValue Narrow = N->getOperand(0);
21606 EVT NarrowVT = Narrow->getValueType(0);
21607 if (!NarrowVT.is128BitVector())
21610 if (Narrow->getOpcode() != ISD::XOR &&
21611 Narrow->getOpcode() != ISD::AND &&
21612 Narrow->getOpcode() != ISD::OR)
21615 SDValue N0 = Narrow->getOperand(0);
21616 SDValue N1 = Narrow->getOperand(1);
21619 // The Left side has to be a trunc.
21620 if (N0.getOpcode() != ISD::TRUNCATE)
21623 // The type of the truncated inputs.
21624 EVT WideVT = N0->getOperand(0)->getValueType(0);
21628 // The right side has to be a 'trunc' or a constant vector.
21629 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21630 ConstantSDNode *RHSConstSplat = nullptr;
21631 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21632 RHSConstSplat = RHSBV->getConstantSplatNode();
21633 if (!RHSTrunc && !RHSConstSplat)
21636 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21638 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21641 // Set N0 and N1 to hold the inputs to the new wide operation.
21642 N0 = N0->getOperand(0);
21643 if (RHSConstSplat) {
21644 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21645 SDValue(RHSConstSplat, 0));
21646 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21647 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21648 } else if (RHSTrunc) {
21649 N1 = N1->getOperand(0);
21652 // Generate the wide operation.
21653 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21654 unsigned Opcode = N->getOpcode();
21656 case ISD::ANY_EXTEND:
21658 case ISD::ZERO_EXTEND: {
21659 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21660 APInt Mask = APInt::getAllOnesValue(InBits);
21661 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21662 return DAG.getNode(ISD::AND, DL, VT,
21663 Op, DAG.getConstant(Mask, VT));
21665 case ISD::SIGN_EXTEND:
21666 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21667 Op, DAG.getValueType(NarrowVT));
21669 llvm_unreachable("Unexpected opcode");
21673 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21674 TargetLowering::DAGCombinerInfo &DCI,
21675 const X86Subtarget *Subtarget) {
21676 EVT VT = N->getValueType(0);
21677 if (DCI.isBeforeLegalizeOps())
21680 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21684 // Create BEXTR instructions
21685 // BEXTR is ((X >> imm) & (2**size-1))
21686 if (VT == MVT::i32 || VT == MVT::i64) {
21687 SDValue N0 = N->getOperand(0);
21688 SDValue N1 = N->getOperand(1);
21691 // Check for BEXTR.
21692 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21693 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21694 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21695 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21696 if (MaskNode && ShiftNode) {
21697 uint64_t Mask = MaskNode->getZExtValue();
21698 uint64_t Shift = ShiftNode->getZExtValue();
21699 if (isMask_64(Mask)) {
21700 uint64_t MaskSize = CountPopulation_64(Mask);
21701 if (Shift + MaskSize <= VT.getSizeInBits())
21702 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21703 DAG.getConstant(Shift | (MaskSize << 8), VT));
21711 // Want to form ANDNP nodes:
21712 // 1) In the hopes of then easily combining them with OR and AND nodes
21713 // to form PBLEND/PSIGN.
21714 // 2) To match ANDN packed intrinsics
21715 if (VT != MVT::v2i64 && VT != MVT::v4i64)
21718 SDValue N0 = N->getOperand(0);
21719 SDValue N1 = N->getOperand(1);
21722 // Check LHS for vnot
21723 if (N0.getOpcode() == ISD::XOR &&
21724 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21725 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21726 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21728 // Check RHS for vnot
21729 if (N1.getOpcode() == ISD::XOR &&
21730 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21731 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21732 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21737 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21738 TargetLowering::DAGCombinerInfo &DCI,
21739 const X86Subtarget *Subtarget) {
21740 if (DCI.isBeforeLegalizeOps())
21743 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21747 SDValue N0 = N->getOperand(0);
21748 SDValue N1 = N->getOperand(1);
21749 EVT VT = N->getValueType(0);
21751 // look for psign/blend
21752 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21753 if (!Subtarget->hasSSSE3() ||
21754 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21757 // Canonicalize pandn to RHS
21758 if (N0.getOpcode() == X86ISD::ANDNP)
21760 // or (and (m, y), (pandn m, x))
21761 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21762 SDValue Mask = N1.getOperand(0);
21763 SDValue X = N1.getOperand(1);
21765 if (N0.getOperand(0) == Mask)
21766 Y = N0.getOperand(1);
21767 if (N0.getOperand(1) == Mask)
21768 Y = N0.getOperand(0);
21770 // Check to see if the mask appeared in both the AND and ANDNP and
21774 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21775 // Look through mask bitcast.
21776 if (Mask.getOpcode() == ISD::BITCAST)
21777 Mask = Mask.getOperand(0);
21778 if (X.getOpcode() == ISD::BITCAST)
21779 X = X.getOperand(0);
21780 if (Y.getOpcode() == ISD::BITCAST)
21781 Y = Y.getOperand(0);
21783 EVT MaskVT = Mask.getValueType();
21785 // Validate that the Mask operand is a vector sra node.
21786 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21787 // there is no psrai.b
21788 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21789 unsigned SraAmt = ~0;
21790 if (Mask.getOpcode() == ISD::SRA) {
21791 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21792 if (auto *AmtConst = AmtBV->getConstantSplatNode())
21793 SraAmt = AmtConst->getZExtValue();
21794 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21795 SDValue SraC = Mask.getOperand(1);
21796 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
21798 if ((SraAmt + 1) != EltBits)
21803 // Now we know we at least have a plendvb with the mask val. See if
21804 // we can form a psignb/w/d.
21805 // psign = x.type == y.type == mask.type && y = sub(0, x);
21806 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21807 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21808 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21809 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21810 "Unsupported VT for PSIGN");
21811 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21812 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21814 // PBLENDVB only available on SSE 4.1
21815 if (!Subtarget->hasSSE41())
21818 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21820 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21821 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21822 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21823 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21824 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21828 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21831 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21832 MachineFunction &MF = DAG.getMachineFunction();
21833 bool OptForSize = MF.getFunction()->getAttributes().
21834 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21836 // SHLD/SHRD instructions have lower register pressure, but on some
21837 // platforms they have higher latency than the equivalent
21838 // series of shifts/or that would otherwise be generated.
21839 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21840 // have higher latencies and we are not optimizing for size.
21841 if (!OptForSize && Subtarget->isSHLDSlow())
21844 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21846 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21848 if (!N0.hasOneUse() || !N1.hasOneUse())
21851 SDValue ShAmt0 = N0.getOperand(1);
21852 if (ShAmt0.getValueType() != MVT::i8)
21854 SDValue ShAmt1 = N1.getOperand(1);
21855 if (ShAmt1.getValueType() != MVT::i8)
21857 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21858 ShAmt0 = ShAmt0.getOperand(0);
21859 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21860 ShAmt1 = ShAmt1.getOperand(0);
21863 unsigned Opc = X86ISD::SHLD;
21864 SDValue Op0 = N0.getOperand(0);
21865 SDValue Op1 = N1.getOperand(0);
21866 if (ShAmt0.getOpcode() == ISD::SUB) {
21867 Opc = X86ISD::SHRD;
21868 std::swap(Op0, Op1);
21869 std::swap(ShAmt0, ShAmt1);
21872 unsigned Bits = VT.getSizeInBits();
21873 if (ShAmt1.getOpcode() == ISD::SUB) {
21874 SDValue Sum = ShAmt1.getOperand(0);
21875 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21876 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21877 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21878 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21879 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21880 return DAG.getNode(Opc, DL, VT,
21882 DAG.getNode(ISD::TRUNCATE, DL,
21885 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21886 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21888 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21889 return DAG.getNode(Opc, DL, VT,
21890 N0.getOperand(0), N1.getOperand(0),
21891 DAG.getNode(ISD::TRUNCATE, DL,
21898 // Generate NEG and CMOV for integer abs.
21899 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21900 EVT VT = N->getValueType(0);
21902 // Since X86 does not have CMOV for 8-bit integer, we don't convert
21903 // 8-bit integer abs to NEG and CMOV.
21904 if (VT.isInteger() && VT.getSizeInBits() == 8)
21907 SDValue N0 = N->getOperand(0);
21908 SDValue N1 = N->getOperand(1);
21911 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21912 // and change it to SUB and CMOV.
21913 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21914 N0.getOpcode() == ISD::ADD &&
21915 N0.getOperand(1) == N1 &&
21916 N1.getOpcode() == ISD::SRA &&
21917 N1.getOperand(0) == N0.getOperand(0))
21918 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21919 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21920 // Generate SUB & CMOV.
21921 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21922 DAG.getConstant(0, VT), N0.getOperand(0));
21924 SDValue Ops[] = { N0.getOperand(0), Neg,
21925 DAG.getConstant(X86::COND_GE, MVT::i8),
21926 SDValue(Neg.getNode(), 1) };
21927 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21932 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21933 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21934 TargetLowering::DAGCombinerInfo &DCI,
21935 const X86Subtarget *Subtarget) {
21936 if (DCI.isBeforeLegalizeOps())
21939 if (Subtarget->hasCMov()) {
21940 SDValue RV = performIntegerAbsCombine(N, DAG);
21948 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21949 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21950 TargetLowering::DAGCombinerInfo &DCI,
21951 const X86Subtarget *Subtarget) {
21952 LoadSDNode *Ld = cast<LoadSDNode>(N);
21953 EVT RegVT = Ld->getValueType(0);
21954 EVT MemVT = Ld->getMemoryVT();
21956 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21958 // On Sandybridge unaligned 256bit loads are inefficient.
21959 ISD::LoadExtType Ext = Ld->getExtensionType();
21960 unsigned Alignment = Ld->getAlignment();
21961 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21962 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21963 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21964 unsigned NumElems = RegVT.getVectorNumElements();
21968 SDValue Ptr = Ld->getBasePtr();
21969 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21971 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21973 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21974 Ld->getPointerInfo(), Ld->isVolatile(),
21975 Ld->isNonTemporal(), Ld->isInvariant(),
21977 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21978 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21979 Ld->getPointerInfo(), Ld->isVolatile(),
21980 Ld->isNonTemporal(), Ld->isInvariant(),
21981 std::min(16U, Alignment));
21982 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21984 Load2.getValue(1));
21986 SDValue NewVec = DAG.getUNDEF(RegVT);
21987 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21988 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21989 return DCI.CombineTo(N, NewVec, TF, true);
21995 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21996 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21997 const X86Subtarget *Subtarget) {
21998 StoreSDNode *St = cast<StoreSDNode>(N);
21999 EVT VT = St->getValue().getValueType();
22000 EVT StVT = St->getMemoryVT();
22002 SDValue StoredVal = St->getOperand(1);
22003 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22005 // If we are saving a concatenation of two XMM registers, perform two stores.
22006 // On Sandy Bridge, 256-bit memory operations are executed by two
22007 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
22008 // memory operation.
22009 unsigned Alignment = St->getAlignment();
22010 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22011 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
22012 StVT == VT && !IsAligned) {
22013 unsigned NumElems = VT.getVectorNumElements();
22017 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22018 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22020 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22021 SDValue Ptr0 = St->getBasePtr();
22022 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22024 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22025 St->getPointerInfo(), St->isVolatile(),
22026 St->isNonTemporal(), Alignment);
22027 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22028 St->getPointerInfo(), St->isVolatile(),
22029 St->isNonTemporal(),
22030 std::min(16U, Alignment));
22031 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22034 // Optimize trunc store (of multiple scalars) to shuffle and store.
22035 // First, pack all of the elements in one place. Next, store to memory
22036 // in fewer chunks.
22037 if (St->isTruncatingStore() && VT.isVector()) {
22038 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22039 unsigned NumElems = VT.getVectorNumElements();
22040 assert(StVT != VT && "Cannot truncate to the same type");
22041 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22042 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22044 // From, To sizes and ElemCount must be pow of two
22045 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22046 // We are going to use the original vector elt for storing.
22047 // Accumulated smaller vector elements must be a multiple of the store size.
22048 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22050 unsigned SizeRatio = FromSz / ToSz;
22052 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22054 // Create a type on which we perform the shuffle
22055 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22056 StVT.getScalarType(), NumElems*SizeRatio);
22058 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22060 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22061 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22062 for (unsigned i = 0; i != NumElems; ++i)
22063 ShuffleVec[i] = i * SizeRatio;
22065 // Can't shuffle using an illegal type.
22066 if (!TLI.isTypeLegal(WideVecVT))
22069 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22070 DAG.getUNDEF(WideVecVT),
22072 // At this point all of the data is stored at the bottom of the
22073 // register. We now need to save it to mem.
22075 // Find the largest store unit
22076 MVT StoreType = MVT::i8;
22077 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
22078 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
22079 MVT Tp = (MVT::SimpleValueType)tp;
22080 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22084 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22085 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22086 (64 <= NumElems * ToSz))
22087 StoreType = MVT::f64;
22089 // Bitcast the original vector into a vector of store-size units
22090 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22091 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22092 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22093 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22094 SmallVector<SDValue, 8> Chains;
22095 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22096 TLI.getPointerTy());
22097 SDValue Ptr = St->getBasePtr();
22099 // Perform one or more big stores into memory.
22100 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22101 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22102 StoreType, ShuffWide,
22103 DAG.getIntPtrConstant(i));
22104 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22105 St->getPointerInfo(), St->isVolatile(),
22106 St->isNonTemporal(), St->getAlignment());
22107 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22108 Chains.push_back(Ch);
22111 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22114 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
22115 // the FP state in cases where an emms may be missing.
22116 // A preferable solution to the general problem is to figure out the right
22117 // places to insert EMMS. This qualifies as a quick hack.
22119 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22120 if (VT.getSizeInBits() != 64)
22123 const Function *F = DAG.getMachineFunction().getFunction();
22124 bool NoImplicitFloatOps = F->getAttributes().
22125 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
22126 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22127 && Subtarget->hasSSE2();
22128 if ((VT.isVector() ||
22129 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22130 isa<LoadSDNode>(St->getValue()) &&
22131 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22132 St->getChain().hasOneUse() && !St->isVolatile()) {
22133 SDNode* LdVal = St->getValue().getNode();
22134 LoadSDNode *Ld = nullptr;
22135 int TokenFactorIndex = -1;
22136 SmallVector<SDValue, 8> Ops;
22137 SDNode* ChainVal = St->getChain().getNode();
22138 // Must be a store of a load. We currently handle two cases: the load
22139 // is a direct child, and it's under an intervening TokenFactor. It is
22140 // possible to dig deeper under nested TokenFactors.
22141 if (ChainVal == LdVal)
22142 Ld = cast<LoadSDNode>(St->getChain());
22143 else if (St->getValue().hasOneUse() &&
22144 ChainVal->getOpcode() == ISD::TokenFactor) {
22145 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22146 if (ChainVal->getOperand(i).getNode() == LdVal) {
22147 TokenFactorIndex = i;
22148 Ld = cast<LoadSDNode>(St->getValue());
22150 Ops.push_back(ChainVal->getOperand(i));
22154 if (!Ld || !ISD::isNormalLoad(Ld))
22157 // If this is not the MMX case, i.e. we are just turning i64 load/store
22158 // into f64 load/store, avoid the transformation if there are multiple
22159 // uses of the loaded value.
22160 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22165 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22166 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22168 if (Subtarget->is64Bit() || F64IsLegal) {
22169 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22170 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22171 Ld->getPointerInfo(), Ld->isVolatile(),
22172 Ld->isNonTemporal(), Ld->isInvariant(),
22173 Ld->getAlignment());
22174 SDValue NewChain = NewLd.getValue(1);
22175 if (TokenFactorIndex != -1) {
22176 Ops.push_back(NewChain);
22177 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22179 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22180 St->getPointerInfo(),
22181 St->isVolatile(), St->isNonTemporal(),
22182 St->getAlignment());
22185 // Otherwise, lower to two pairs of 32-bit loads / stores.
22186 SDValue LoAddr = Ld->getBasePtr();
22187 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22188 DAG.getConstant(4, MVT::i32));
22190 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22191 Ld->getPointerInfo(),
22192 Ld->isVolatile(), Ld->isNonTemporal(),
22193 Ld->isInvariant(), Ld->getAlignment());
22194 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22195 Ld->getPointerInfo().getWithOffset(4),
22196 Ld->isVolatile(), Ld->isNonTemporal(),
22198 MinAlign(Ld->getAlignment(), 4));
22200 SDValue NewChain = LoLd.getValue(1);
22201 if (TokenFactorIndex != -1) {
22202 Ops.push_back(LoLd);
22203 Ops.push_back(HiLd);
22204 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22207 LoAddr = St->getBasePtr();
22208 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22209 DAG.getConstant(4, MVT::i32));
22211 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22212 St->getPointerInfo(),
22213 St->isVolatile(), St->isNonTemporal(),
22214 St->getAlignment());
22215 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22216 St->getPointerInfo().getWithOffset(4),
22218 St->isNonTemporal(),
22219 MinAlign(St->getAlignment(), 4));
22220 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22225 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
22226 /// and return the operands for the horizontal operation in LHS and RHS. A
22227 /// horizontal operation performs the binary operation on successive elements
22228 /// of its first operand, then on successive elements of its second operand,
22229 /// returning the resulting values in a vector. For example, if
22230 /// A = < float a0, float a1, float a2, float a3 >
22232 /// B = < float b0, float b1, float b2, float b3 >
22233 /// then the result of doing a horizontal operation on A and B is
22234 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22235 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22236 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22237 /// set to A, RHS to B, and the routine returns 'true'.
22238 /// Note that the binary operation should have the property that if one of the
22239 /// operands is UNDEF then the result is UNDEF.
22240 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22241 // Look for the following pattern: if
22242 // A = < float a0, float a1, float a2, float a3 >
22243 // B = < float b0, float b1, float b2, float b3 >
22245 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22246 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22247 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22248 // which is A horizontal-op B.
22250 // At least one of the operands should be a vector shuffle.
22251 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22252 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22255 MVT VT = LHS.getSimpleValueType();
22257 assert((VT.is128BitVector() || VT.is256BitVector()) &&
22258 "Unsupported vector type for horizontal add/sub");
22260 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22261 // operate independently on 128-bit lanes.
22262 unsigned NumElts = VT.getVectorNumElements();
22263 unsigned NumLanes = VT.getSizeInBits()/128;
22264 unsigned NumLaneElts = NumElts / NumLanes;
22265 assert((NumLaneElts % 2 == 0) &&
22266 "Vector type should have an even number of elements in each lane");
22267 unsigned HalfLaneElts = NumLaneElts/2;
22269 // View LHS in the form
22270 // LHS = VECTOR_SHUFFLE A, B, LMask
22271 // If LHS is not a shuffle then pretend it is the shuffle
22272 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22273 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22276 SmallVector<int, 16> LMask(NumElts);
22277 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22278 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22279 A = LHS.getOperand(0);
22280 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22281 B = LHS.getOperand(1);
22282 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22283 std::copy(Mask.begin(), Mask.end(), LMask.begin());
22285 if (LHS.getOpcode() != ISD::UNDEF)
22287 for (unsigned i = 0; i != NumElts; ++i)
22291 // Likewise, view RHS in the form
22292 // RHS = VECTOR_SHUFFLE C, D, RMask
22294 SmallVector<int, 16> RMask(NumElts);
22295 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22296 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22297 C = RHS.getOperand(0);
22298 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22299 D = RHS.getOperand(1);
22300 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22301 std::copy(Mask.begin(), Mask.end(), RMask.begin());
22303 if (RHS.getOpcode() != ISD::UNDEF)
22305 for (unsigned i = 0; i != NumElts; ++i)
22309 // Check that the shuffles are both shuffling the same vectors.
22310 if (!(A == C && B == D) && !(A == D && B == C))
22313 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22314 if (!A.getNode() && !B.getNode())
22317 // If A and B occur in reverse order in RHS, then "swap" them (which means
22318 // rewriting the mask).
22320 CommuteVectorShuffleMask(RMask, NumElts);
22322 // At this point LHS and RHS are equivalent to
22323 // LHS = VECTOR_SHUFFLE A, B, LMask
22324 // RHS = VECTOR_SHUFFLE A, B, RMask
22325 // Check that the masks correspond to performing a horizontal operation.
22326 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22327 for (unsigned i = 0; i != NumLaneElts; ++i) {
22328 int LIdx = LMask[i+l], RIdx = RMask[i+l];
22330 // Ignore any UNDEF components.
22331 if (LIdx < 0 || RIdx < 0 ||
22332 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22333 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22336 // Check that successive elements are being operated on. If not, this is
22337 // not a horizontal operation.
22338 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22339 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22340 if (!(LIdx == Index && RIdx == Index + 1) &&
22341 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22346 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22347 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22351 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22352 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22353 const X86Subtarget *Subtarget) {
22354 EVT VT = N->getValueType(0);
22355 SDValue LHS = N->getOperand(0);
22356 SDValue RHS = N->getOperand(1);
22358 // Try to synthesize horizontal adds from adds of shuffles.
22359 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22360 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22361 isHorizontalBinOp(LHS, RHS, true))
22362 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22366 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22367 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22368 const X86Subtarget *Subtarget) {
22369 EVT VT = N->getValueType(0);
22370 SDValue LHS = N->getOperand(0);
22371 SDValue RHS = N->getOperand(1);
22373 // Try to synthesize horizontal subs from subs of shuffles.
22374 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22375 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22376 isHorizontalBinOp(LHS, RHS, false))
22377 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22381 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22382 /// X86ISD::FXOR nodes.
22383 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22384 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22385 // F[X]OR(0.0, x) -> x
22386 // F[X]OR(x, 0.0) -> x
22387 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22388 if (C->getValueAPF().isPosZero())
22389 return N->getOperand(1);
22390 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22391 if (C->getValueAPF().isPosZero())
22392 return N->getOperand(0);
22396 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22397 /// X86ISD::FMAX nodes.
22398 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22399 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22401 // Only perform optimizations if UnsafeMath is used.
22402 if (!DAG.getTarget().Options.UnsafeFPMath)
22405 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22406 // into FMINC and FMAXC, which are Commutative operations.
22407 unsigned NewOp = 0;
22408 switch (N->getOpcode()) {
22409 default: llvm_unreachable("unknown opcode");
22410 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
22411 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
22414 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22415 N->getOperand(0), N->getOperand(1));
22418 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22419 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22420 // FAND(0.0, x) -> 0.0
22421 // FAND(x, 0.0) -> 0.0
22422 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22423 if (C->getValueAPF().isPosZero())
22424 return N->getOperand(0);
22425 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22426 if (C->getValueAPF().isPosZero())
22427 return N->getOperand(1);
22431 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22432 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22433 // FANDN(x, 0.0) -> 0.0
22434 // FANDN(0.0, x) -> x
22435 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22436 if (C->getValueAPF().isPosZero())
22437 return N->getOperand(1);
22438 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22439 if (C->getValueAPF().isPosZero())
22440 return N->getOperand(1);
22444 static SDValue PerformBTCombine(SDNode *N,
22446 TargetLowering::DAGCombinerInfo &DCI) {
22447 // BT ignores high bits in the bit index operand.
22448 SDValue Op1 = N->getOperand(1);
22449 if (Op1.hasOneUse()) {
22450 unsigned BitWidth = Op1.getValueSizeInBits();
22451 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22452 APInt KnownZero, KnownOne;
22453 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22454 !DCI.isBeforeLegalizeOps());
22455 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22456 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22457 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22458 DCI.CommitTargetLoweringOpt(TLO);
22463 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22464 SDValue Op = N->getOperand(0);
22465 if (Op.getOpcode() == ISD::BITCAST)
22466 Op = Op.getOperand(0);
22467 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22468 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22469 VT.getVectorElementType().getSizeInBits() ==
22470 OpVT.getVectorElementType().getSizeInBits()) {
22471 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22476 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22477 const X86Subtarget *Subtarget) {
22478 EVT VT = N->getValueType(0);
22479 if (!VT.isVector())
22482 SDValue N0 = N->getOperand(0);
22483 SDValue N1 = N->getOperand(1);
22484 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22487 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22488 // both SSE and AVX2 since there is no sign-extended shift right
22489 // operation on a vector with 64-bit elements.
22490 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22491 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22492 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22493 N0.getOpcode() == ISD::SIGN_EXTEND)) {
22494 SDValue N00 = N0.getOperand(0);
22496 // EXTLOAD has a better solution on AVX2,
22497 // it may be replaced with X86ISD::VSEXT node.
22498 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22499 if (!ISD::isNormalLoad(N00.getNode()))
22502 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22503 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22505 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22511 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22512 TargetLowering::DAGCombinerInfo &DCI,
22513 const X86Subtarget *Subtarget) {
22514 if (!DCI.isBeforeLegalizeOps())
22517 if (!Subtarget->hasFp256())
22520 EVT VT = N->getValueType(0);
22521 if (VT.isVector() && VT.getSizeInBits() == 256) {
22522 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22530 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22531 const X86Subtarget* Subtarget) {
22533 EVT VT = N->getValueType(0);
22535 // Let legalize expand this if it isn't a legal type yet.
22536 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22539 EVT ScalarVT = VT.getScalarType();
22540 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22541 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22544 SDValue A = N->getOperand(0);
22545 SDValue B = N->getOperand(1);
22546 SDValue C = N->getOperand(2);
22548 bool NegA = (A.getOpcode() == ISD::FNEG);
22549 bool NegB = (B.getOpcode() == ISD::FNEG);
22550 bool NegC = (C.getOpcode() == ISD::FNEG);
22552 // Negative multiplication when NegA xor NegB
22553 bool NegMul = (NegA != NegB);
22555 A = A.getOperand(0);
22557 B = B.getOperand(0);
22559 C = C.getOperand(0);
22563 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22565 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22567 return DAG.getNode(Opcode, dl, VT, A, B, C);
22570 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22571 TargetLowering::DAGCombinerInfo &DCI,
22572 const X86Subtarget *Subtarget) {
22573 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
22574 // (and (i32 x86isd::setcc_carry), 1)
22575 // This eliminates the zext. This transformation is necessary because
22576 // ISD::SETCC is always legalized to i8.
22578 SDValue N0 = N->getOperand(0);
22579 EVT VT = N->getValueType(0);
22581 if (N0.getOpcode() == ISD::AND &&
22583 N0.getOperand(0).hasOneUse()) {
22584 SDValue N00 = N0.getOperand(0);
22585 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22586 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22587 if (!C || C->getZExtValue() != 1)
22589 return DAG.getNode(ISD::AND, dl, VT,
22590 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22591 N00.getOperand(0), N00.getOperand(1)),
22592 DAG.getConstant(1, VT));
22596 if (N0.getOpcode() == ISD::TRUNCATE &&
22598 N0.getOperand(0).hasOneUse()) {
22599 SDValue N00 = N0.getOperand(0);
22600 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22601 return DAG.getNode(ISD::AND, dl, VT,
22602 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22603 N00.getOperand(0), N00.getOperand(1)),
22604 DAG.getConstant(1, VT));
22607 if (VT.is256BitVector()) {
22608 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22616 // Optimize x == -y --> x+y == 0
22617 // x != -y --> x+y != 0
22618 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22619 const X86Subtarget* Subtarget) {
22620 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22621 SDValue LHS = N->getOperand(0);
22622 SDValue RHS = N->getOperand(1);
22623 EVT VT = N->getValueType(0);
22626 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22627 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22628 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22629 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22630 LHS.getValueType(), RHS, LHS.getOperand(1));
22631 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22632 addV, DAG.getConstant(0, addV.getValueType()), CC);
22634 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22635 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22636 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22637 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22638 RHS.getValueType(), LHS, RHS.getOperand(1));
22639 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22640 addV, DAG.getConstant(0, addV.getValueType()), CC);
22643 if (VT.getScalarType() == MVT::i1) {
22644 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22645 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22646 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22647 if (!IsSEXT0 && !IsVZero0)
22649 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22650 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22651 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22653 if (!IsSEXT1 && !IsVZero1)
22656 if (IsSEXT0 && IsVZero1) {
22657 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22658 if (CC == ISD::SETEQ)
22659 return DAG.getNOT(DL, LHS.getOperand(0), VT);
22660 return LHS.getOperand(0);
22662 if (IsSEXT1 && IsVZero0) {
22663 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22664 if (CC == ISD::SETEQ)
22665 return DAG.getNOT(DL, RHS.getOperand(0), VT);
22666 return RHS.getOperand(0);
22673 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22674 const X86Subtarget *Subtarget) {
22676 MVT VT = N->getOperand(1)->getSimpleValueType(0);
22677 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22678 "X86insertps is only defined for v4x32");
22680 SDValue Ld = N->getOperand(1);
22681 if (MayFoldLoad(Ld)) {
22682 // Extract the countS bits from the immediate so we can get the proper
22683 // address when narrowing the vector load to a specific element.
22684 // When the second source op is a memory address, interps doesn't use
22685 // countS and just gets an f32 from that address.
22686 unsigned DestIndex =
22687 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22688 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22692 // Create this as a scalar to vector to match the instruction pattern.
22693 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22694 // countS bits are ignored when loading from memory on insertps, which
22695 // means we don't need to explicitly set them to 0.
22696 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22697 LoadScalarToVector, N->getOperand(2));
22700 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22701 // as "sbb reg,reg", since it can be extended without zext and produces
22702 // an all-ones bit which is more useful than 0/1 in some cases.
22703 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22706 return DAG.getNode(ISD::AND, DL, VT,
22707 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22708 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22709 DAG.getConstant(1, VT));
22710 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22711 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22712 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22713 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22716 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22717 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22718 TargetLowering::DAGCombinerInfo &DCI,
22719 const X86Subtarget *Subtarget) {
22721 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22722 SDValue EFLAGS = N->getOperand(1);
22724 if (CC == X86::COND_A) {
22725 // Try to convert COND_A into COND_B in an attempt to facilitate
22726 // materializing "setb reg".
22728 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22729 // cannot take an immediate as its first operand.
22731 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22732 EFLAGS.getValueType().isInteger() &&
22733 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22734 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22735 EFLAGS.getNode()->getVTList(),
22736 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22737 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22738 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22742 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22743 // a zext and produces an all-ones bit which is more useful than 0/1 in some
22745 if (CC == X86::COND_B)
22746 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22750 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22751 if (Flags.getNode()) {
22752 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22753 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22759 // Optimize branch condition evaluation.
22761 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22762 TargetLowering::DAGCombinerInfo &DCI,
22763 const X86Subtarget *Subtarget) {
22765 SDValue Chain = N->getOperand(0);
22766 SDValue Dest = N->getOperand(1);
22767 SDValue EFLAGS = N->getOperand(3);
22768 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22772 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22773 if (Flags.getNode()) {
22774 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22775 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22782 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22783 SelectionDAG &DAG) {
22784 // Take advantage of vector comparisons producing 0 or -1 in each lane to
22785 // optimize away operation when it's from a constant.
22787 // The general transformation is:
22788 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22789 // AND(VECTOR_CMP(x,y), constant2)
22790 // constant2 = UNARYOP(constant)
22792 // Early exit if this isn't a vector operation, the operand of the
22793 // unary operation isn't a bitwise AND, or if the sizes of the operations
22794 // aren't the same.
22795 EVT VT = N->getValueType(0);
22796 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22797 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22798 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22801 // Now check that the other operand of the AND is a constant. We could
22802 // make the transformation for non-constant splats as well, but it's unclear
22803 // that would be a benefit as it would not eliminate any operations, just
22804 // perform one more step in scalar code before moving to the vector unit.
22805 if (BuildVectorSDNode *BV =
22806 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22807 // Bail out if the vector isn't a constant.
22808 if (!BV->isConstant())
22811 // Everything checks out. Build up the new and improved node.
22813 EVT IntVT = BV->getValueType(0);
22814 // Create a new constant of the appropriate type for the transformed
22816 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22817 // The AND node needs bitcasts to/from an integer vector type around it.
22818 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22819 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22820 N->getOperand(0)->getOperand(0), MaskConst);
22821 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22828 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22829 const X86TargetLowering *XTLI) {
22830 // First try to optimize away the conversion entirely when it's
22831 // conditionally from a constant. Vectors only.
22832 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22833 if (Res != SDValue())
22836 // Now move on to more general possibilities.
22837 SDValue Op0 = N->getOperand(0);
22838 EVT InVT = Op0->getValueType(0);
22840 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22841 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22843 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22844 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22845 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22848 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22849 // a 32-bit target where SSE doesn't support i64->FP operations.
22850 if (Op0.getOpcode() == ISD::LOAD) {
22851 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22852 EVT VT = Ld->getValueType(0);
22853 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22854 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22855 !XTLI->getSubtarget()->is64Bit() &&
22857 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22858 Ld->getChain(), Op0, DAG);
22859 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22866 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22867 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22868 X86TargetLowering::DAGCombinerInfo &DCI) {
22869 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22870 // the result is either zero or one (depending on the input carry bit).
22871 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22872 if (X86::isZeroNode(N->getOperand(0)) &&
22873 X86::isZeroNode(N->getOperand(1)) &&
22874 // We don't have a good way to replace an EFLAGS use, so only do this when
22876 SDValue(N, 1).use_empty()) {
22878 EVT VT = N->getValueType(0);
22879 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22880 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22881 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22882 DAG.getConstant(X86::COND_B,MVT::i8),
22884 DAG.getConstant(1, VT));
22885 return DCI.CombineTo(N, Res1, CarryOut);
22891 // fold (add Y, (sete X, 0)) -> adc 0, Y
22892 // (add Y, (setne X, 0)) -> sbb -1, Y
22893 // (sub (sete X, 0), Y) -> sbb 0, Y
22894 // (sub (setne X, 0), Y) -> adc -1, Y
22895 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22898 // Look through ZExts.
22899 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22900 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22903 SDValue SetCC = Ext.getOperand(0);
22904 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22907 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22908 if (CC != X86::COND_E && CC != X86::COND_NE)
22911 SDValue Cmp = SetCC.getOperand(1);
22912 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22913 !X86::isZeroNode(Cmp.getOperand(1)) ||
22914 !Cmp.getOperand(0).getValueType().isInteger())
22917 SDValue CmpOp0 = Cmp.getOperand(0);
22918 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22919 DAG.getConstant(1, CmpOp0.getValueType()));
22921 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22922 if (CC == X86::COND_NE)
22923 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22924 DL, OtherVal.getValueType(), OtherVal,
22925 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22926 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22927 DL, OtherVal.getValueType(), OtherVal,
22928 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22931 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22932 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22933 const X86Subtarget *Subtarget) {
22934 EVT VT = N->getValueType(0);
22935 SDValue Op0 = N->getOperand(0);
22936 SDValue Op1 = N->getOperand(1);
22938 // Try to synthesize horizontal adds from adds of shuffles.
22939 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22940 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22941 isHorizontalBinOp(Op0, Op1, true))
22942 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22944 return OptimizeConditionalInDecrement(N, DAG);
22947 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22948 const X86Subtarget *Subtarget) {
22949 SDValue Op0 = N->getOperand(0);
22950 SDValue Op1 = N->getOperand(1);
22952 // X86 can't encode an immediate LHS of a sub. See if we can push the
22953 // negation into a preceding instruction.
22954 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22955 // If the RHS of the sub is a XOR with one use and a constant, invert the
22956 // immediate. Then add one to the LHS of the sub so we can turn
22957 // X-Y -> X+~Y+1, saving one register.
22958 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22959 isa<ConstantSDNode>(Op1.getOperand(1))) {
22960 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22961 EVT VT = Op0.getValueType();
22962 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22964 DAG.getConstant(~XorC, VT));
22965 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22966 DAG.getConstant(C->getAPIntValue()+1, VT));
22970 // Try to synthesize horizontal adds from adds of shuffles.
22971 EVT VT = N->getValueType(0);
22972 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22973 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22974 isHorizontalBinOp(Op0, Op1, true))
22975 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22977 return OptimizeConditionalInDecrement(N, DAG);
22980 /// performVZEXTCombine - Performs build vector combines
22981 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22982 TargetLowering::DAGCombinerInfo &DCI,
22983 const X86Subtarget *Subtarget) {
22984 // (vzext (bitcast (vzext (x)) -> (vzext x)
22985 SDValue In = N->getOperand(0);
22986 while (In.getOpcode() == ISD::BITCAST)
22987 In = In.getOperand(0);
22989 if (In.getOpcode() != X86ISD::VZEXT)
22992 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22996 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22997 DAGCombinerInfo &DCI) const {
22998 SelectionDAG &DAG = DCI.DAG;
22999 switch (N->getOpcode()) {
23001 case ISD::EXTRACT_VECTOR_ELT:
23002 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23004 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23005 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23006 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
23007 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
23008 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
23009 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
23012 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
23013 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
23014 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
23015 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
23016 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
23017 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
23018 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
23019 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
23020 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
23022 case X86ISD::FOR: return PerformFORCombine(N, DAG);
23024 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
23025 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
23026 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
23027 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
23028 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
23029 case ISD::ANY_EXTEND:
23030 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
23031 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
23032 case ISD::SIGN_EXTEND_INREG:
23033 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23034 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23035 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
23036 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23037 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23038 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
23039 case X86ISD::SHUFP: // Handle all target specific shuffles
23040 case X86ISD::PALIGNR:
23041 case X86ISD::UNPCKH:
23042 case X86ISD::UNPCKL:
23043 case X86ISD::MOVHLPS:
23044 case X86ISD::MOVLHPS:
23045 case X86ISD::PSHUFB:
23046 case X86ISD::PSHUFD:
23047 case X86ISD::PSHUFHW:
23048 case X86ISD::PSHUFLW:
23049 case X86ISD::MOVSS:
23050 case X86ISD::MOVSD:
23051 case X86ISD::VPERMILP:
23052 case X86ISD::VPERM2X128:
23053 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23054 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
23055 case ISD::INTRINSIC_WO_CHAIN:
23056 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23057 case X86ISD::INSERTPS:
23058 return PerformINSERTPSCombine(N, DAG, Subtarget);
23059 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23065 /// isTypeDesirableForOp - Return true if the target has native support for
23066 /// the specified value type and it is 'desirable' to use the type for the
23067 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23068 /// instruction encodings are longer and some i16 instructions are slow.
23069 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23070 if (!isTypeLegal(VT))
23072 if (VT != MVT::i16)
23079 case ISD::SIGN_EXTEND:
23080 case ISD::ZERO_EXTEND:
23081 case ISD::ANY_EXTEND:
23094 /// IsDesirableToPromoteOp - This method query the target whether it is
23095 /// beneficial for dag combiner to promote the specified node. If true, it
23096 /// should return the desired promotion type by reference.
23097 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23098 EVT VT = Op.getValueType();
23099 if (VT != MVT::i16)
23102 bool Promote = false;
23103 bool Commute = false;
23104 switch (Op.getOpcode()) {
23107 LoadSDNode *LD = cast<LoadSDNode>(Op);
23108 // If the non-extending load has a single use and it's not live out, then it
23109 // might be folded.
23110 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23111 Op.hasOneUse()*/) {
23112 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23113 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23114 // The only case where we'd want to promote LOAD (rather then it being
23115 // promoted as an operand is when it's only use is liveout.
23116 if (UI->getOpcode() != ISD::CopyToReg)
23123 case ISD::SIGN_EXTEND:
23124 case ISD::ZERO_EXTEND:
23125 case ISD::ANY_EXTEND:
23130 SDValue N0 = Op.getOperand(0);
23131 // Look out for (store (shl (load), x)).
23132 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23145 SDValue N0 = Op.getOperand(0);
23146 SDValue N1 = Op.getOperand(1);
23147 if (!Commute && MayFoldLoad(N1))
23149 // Avoid disabling potential load folding opportunities.
23150 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23152 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23162 //===----------------------------------------------------------------------===//
23163 // X86 Inline Assembly Support
23164 //===----------------------------------------------------------------------===//
23167 // Helper to match a string separated by whitespace.
23168 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
23169 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
23171 for (unsigned i = 0, e = args.size(); i != e; ++i) {
23172 StringRef piece(*args[i]);
23173 if (!s.startswith(piece)) // Check if the piece matches.
23176 s = s.substr(piece.size());
23177 StringRef::size_type pos = s.find_first_not_of(" \t");
23178 if (pos == 0) // We matched a prefix.
23186 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
23189 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23191 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23192 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23193 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23194 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23196 if (AsmPieces.size() == 3)
23198 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23205 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23206 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23208 std::string AsmStr = IA->getAsmString();
23210 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23211 if (!Ty || Ty->getBitWidth() % 16 != 0)
23214 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23215 SmallVector<StringRef, 4> AsmPieces;
23216 SplitString(AsmStr, AsmPieces, ";\n");
23218 switch (AsmPieces.size()) {
23219 default: return false;
23221 // FIXME: this should verify that we are targeting a 486 or better. If not,
23222 // we will turn this bswap into something that will be lowered to logical
23223 // ops instead of emitting the bswap asm. For now, we don't support 486 or
23224 // lower so don't worry about this.
23226 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
23227 matchAsm(AsmPieces[0], "bswapl", "$0") ||
23228 matchAsm(AsmPieces[0], "bswapq", "$0") ||
23229 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
23230 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
23231 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
23232 // No need to check constraints, nothing other than the equivalent of
23233 // "=r,0" would be valid here.
23234 return IntrinsicLowering::LowerToByteSwap(CI);
23237 // rorw $$8, ${0:w} --> llvm.bswap.i16
23238 if (CI->getType()->isIntegerTy(16) &&
23239 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23240 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
23241 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
23243 const std::string &ConstraintsStr = IA->getConstraintString();
23244 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23245 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23246 if (clobbersFlagRegisters(AsmPieces))
23247 return IntrinsicLowering::LowerToByteSwap(CI);
23251 if (CI->getType()->isIntegerTy(32) &&
23252 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23253 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
23254 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
23255 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
23257 const std::string &ConstraintsStr = IA->getConstraintString();
23258 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23259 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23260 if (clobbersFlagRegisters(AsmPieces))
23261 return IntrinsicLowering::LowerToByteSwap(CI);
23264 if (CI->getType()->isIntegerTy(64)) {
23265 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23266 if (Constraints.size() >= 2 &&
23267 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23268 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23269 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
23270 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
23271 matchAsm(AsmPieces[1], "bswap", "%edx") &&
23272 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
23273 return IntrinsicLowering::LowerToByteSwap(CI);
23281 /// getConstraintType - Given a constraint letter, return the type of
23282 /// constraint it is for this target.
23283 X86TargetLowering::ConstraintType
23284 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23285 if (Constraint.size() == 1) {
23286 switch (Constraint[0]) {
23297 return C_RegisterClass;
23321 return TargetLowering::getConstraintType(Constraint);
23324 /// Examine constraint type and operand type and determine a weight value.
23325 /// This object must already have been set up with the operand type
23326 /// and the current alternative constraint selected.
23327 TargetLowering::ConstraintWeight
23328 X86TargetLowering::getSingleConstraintMatchWeight(
23329 AsmOperandInfo &info, const char *constraint) const {
23330 ConstraintWeight weight = CW_Invalid;
23331 Value *CallOperandVal = info.CallOperandVal;
23332 // If we don't have a value, we can't do a match,
23333 // but allow it at the lowest weight.
23334 if (!CallOperandVal)
23336 Type *type = CallOperandVal->getType();
23337 // Look at the constraint type.
23338 switch (*constraint) {
23340 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23351 if (CallOperandVal->getType()->isIntegerTy())
23352 weight = CW_SpecificReg;
23357 if (type->isFloatingPointTy())
23358 weight = CW_SpecificReg;
23361 if (type->isX86_MMXTy() && Subtarget->hasMMX())
23362 weight = CW_SpecificReg;
23366 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23367 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23368 weight = CW_Register;
23371 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23372 if (C->getZExtValue() <= 31)
23373 weight = CW_Constant;
23377 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23378 if (C->getZExtValue() <= 63)
23379 weight = CW_Constant;
23383 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23384 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23385 weight = CW_Constant;
23389 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23390 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23391 weight = CW_Constant;
23395 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23396 if (C->getZExtValue() <= 3)
23397 weight = CW_Constant;
23401 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23402 if (C->getZExtValue() <= 0xff)
23403 weight = CW_Constant;
23408 if (dyn_cast<ConstantFP>(CallOperandVal)) {
23409 weight = CW_Constant;
23413 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23414 if ((C->getSExtValue() >= -0x80000000LL) &&
23415 (C->getSExtValue() <= 0x7fffffffLL))
23416 weight = CW_Constant;
23420 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23421 if (C->getZExtValue() <= 0xffffffff)
23422 weight = CW_Constant;
23429 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23430 /// with another that has more specific requirements based on the type of the
23431 /// corresponding operand.
23432 const char *X86TargetLowering::
23433 LowerXConstraint(EVT ConstraintVT) const {
23434 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23435 // 'f' like normal targets.
23436 if (ConstraintVT.isFloatingPoint()) {
23437 if (Subtarget->hasSSE2())
23439 if (Subtarget->hasSSE1())
23443 return TargetLowering::LowerXConstraint(ConstraintVT);
23446 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23447 /// vector. If it is invalid, don't add anything to Ops.
23448 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23449 std::string &Constraint,
23450 std::vector<SDValue>&Ops,
23451 SelectionDAG &DAG) const {
23454 // Only support length 1 constraints for now.
23455 if (Constraint.length() > 1) return;
23457 char ConstraintLetter = Constraint[0];
23458 switch (ConstraintLetter) {
23461 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23462 if (C->getZExtValue() <= 31) {
23463 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23469 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23470 if (C->getZExtValue() <= 63) {
23471 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23477 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23478 if (isInt<8>(C->getSExtValue())) {
23479 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23485 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23486 if (C->getZExtValue() <= 255) {
23487 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23493 // 32-bit signed value
23494 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23495 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23496 C->getSExtValue())) {
23497 // Widen to 64 bits here to get it sign extended.
23498 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23501 // FIXME gcc accepts some relocatable values here too, but only in certain
23502 // memory models; it's complicated.
23507 // 32-bit unsigned value
23508 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23509 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23510 C->getZExtValue())) {
23511 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23515 // FIXME gcc accepts some relocatable values here too, but only in certain
23516 // memory models; it's complicated.
23520 // Literal immediates are always ok.
23521 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23522 // Widen to 64 bits here to get it sign extended.
23523 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23527 // In any sort of PIC mode addresses need to be computed at runtime by
23528 // adding in a register or some sort of table lookup. These can't
23529 // be used as immediates.
23530 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23533 // If we are in non-pic codegen mode, we allow the address of a global (with
23534 // an optional displacement) to be used with 'i'.
23535 GlobalAddressSDNode *GA = nullptr;
23536 int64_t Offset = 0;
23538 // Match either (GA), (GA+C), (GA+C1+C2), etc.
23540 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23541 Offset += GA->getOffset();
23543 } else if (Op.getOpcode() == ISD::ADD) {
23544 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23545 Offset += C->getZExtValue();
23546 Op = Op.getOperand(0);
23549 } else if (Op.getOpcode() == ISD::SUB) {
23550 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23551 Offset += -C->getZExtValue();
23552 Op = Op.getOperand(0);
23557 // Otherwise, this isn't something we can handle, reject it.
23561 const GlobalValue *GV = GA->getGlobal();
23562 // If we require an extra load to get this address, as in PIC mode, we
23563 // can't accept it.
23564 if (isGlobalStubReference(
23565 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23568 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23569 GA->getValueType(0), Offset);
23574 if (Result.getNode()) {
23575 Ops.push_back(Result);
23578 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23581 std::pair<unsigned, const TargetRegisterClass*>
23582 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23584 // First, see if this is a constraint that directly corresponds to an LLVM
23586 if (Constraint.size() == 1) {
23587 // GCC Constraint Letters
23588 switch (Constraint[0]) {
23590 // TODO: Slight differences here in allocation order and leaving
23591 // RIP in the class. Do they matter any more here than they do
23592 // in the normal allocation?
23593 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23594 if (Subtarget->is64Bit()) {
23595 if (VT == MVT::i32 || VT == MVT::f32)
23596 return std::make_pair(0U, &X86::GR32RegClass);
23597 if (VT == MVT::i16)
23598 return std::make_pair(0U, &X86::GR16RegClass);
23599 if (VT == MVT::i8 || VT == MVT::i1)
23600 return std::make_pair(0U, &X86::GR8RegClass);
23601 if (VT == MVT::i64 || VT == MVT::f64)
23602 return std::make_pair(0U, &X86::GR64RegClass);
23605 // 32-bit fallthrough
23606 case 'Q': // Q_REGS
23607 if (VT == MVT::i32 || VT == MVT::f32)
23608 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23609 if (VT == MVT::i16)
23610 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23611 if (VT == MVT::i8 || VT == MVT::i1)
23612 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23613 if (VT == MVT::i64)
23614 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23616 case 'r': // GENERAL_REGS
23617 case 'l': // INDEX_REGS
23618 if (VT == MVT::i8 || VT == MVT::i1)
23619 return std::make_pair(0U, &X86::GR8RegClass);
23620 if (VT == MVT::i16)
23621 return std::make_pair(0U, &X86::GR16RegClass);
23622 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23623 return std::make_pair(0U, &X86::GR32RegClass);
23624 return std::make_pair(0U, &X86::GR64RegClass);
23625 case 'R': // LEGACY_REGS
23626 if (VT == MVT::i8 || VT == MVT::i1)
23627 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23628 if (VT == MVT::i16)
23629 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23630 if (VT == MVT::i32 || !Subtarget->is64Bit())
23631 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23632 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23633 case 'f': // FP Stack registers.
23634 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23635 // value to the correct fpstack register class.
23636 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23637 return std::make_pair(0U, &X86::RFP32RegClass);
23638 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23639 return std::make_pair(0U, &X86::RFP64RegClass);
23640 return std::make_pair(0U, &X86::RFP80RegClass);
23641 case 'y': // MMX_REGS if MMX allowed.
23642 if (!Subtarget->hasMMX()) break;
23643 return std::make_pair(0U, &X86::VR64RegClass);
23644 case 'Y': // SSE_REGS if SSE2 allowed
23645 if (!Subtarget->hasSSE2()) break;
23647 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23648 if (!Subtarget->hasSSE1()) break;
23650 switch (VT.SimpleTy) {
23652 // Scalar SSE types.
23655 return std::make_pair(0U, &X86::FR32RegClass);
23658 return std::make_pair(0U, &X86::FR64RegClass);
23666 return std::make_pair(0U, &X86::VR128RegClass);
23674 return std::make_pair(0U, &X86::VR256RegClass);
23679 return std::make_pair(0U, &X86::VR512RegClass);
23685 // Use the default implementation in TargetLowering to convert the register
23686 // constraint into a member of a register class.
23687 std::pair<unsigned, const TargetRegisterClass*> Res;
23688 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23690 // Not found as a standard register?
23692 // Map st(0) -> st(7) -> ST0
23693 if (Constraint.size() == 7 && Constraint[0] == '{' &&
23694 tolower(Constraint[1]) == 's' &&
23695 tolower(Constraint[2]) == 't' &&
23696 Constraint[3] == '(' &&
23697 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23698 Constraint[5] == ')' &&
23699 Constraint[6] == '}') {
23701 Res.first = X86::FP0+Constraint[4]-'0';
23702 Res.second = &X86::RFP80RegClass;
23706 // GCC allows "st(0)" to be called just plain "st".
23707 if (StringRef("{st}").equals_lower(Constraint)) {
23708 Res.first = X86::FP0;
23709 Res.second = &X86::RFP80RegClass;
23714 if (StringRef("{flags}").equals_lower(Constraint)) {
23715 Res.first = X86::EFLAGS;
23716 Res.second = &X86::CCRRegClass;
23720 // 'A' means EAX + EDX.
23721 if (Constraint == "A") {
23722 Res.first = X86::EAX;
23723 Res.second = &X86::GR32_ADRegClass;
23729 // Otherwise, check to see if this is a register class of the wrong value
23730 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23731 // turn into {ax},{dx}.
23732 if (Res.second->hasType(VT))
23733 return Res; // Correct type already, nothing to do.
23735 // All of the single-register GCC register classes map their values onto
23736 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
23737 // really want an 8-bit or 32-bit register, map to the appropriate register
23738 // class and return the appropriate register.
23739 if (Res.second == &X86::GR16RegClass) {
23740 if (VT == MVT::i8 || VT == MVT::i1) {
23741 unsigned DestReg = 0;
23742 switch (Res.first) {
23744 case X86::AX: DestReg = X86::AL; break;
23745 case X86::DX: DestReg = X86::DL; break;
23746 case X86::CX: DestReg = X86::CL; break;
23747 case X86::BX: DestReg = X86::BL; break;
23750 Res.first = DestReg;
23751 Res.second = &X86::GR8RegClass;
23753 } else if (VT == MVT::i32 || VT == MVT::f32) {
23754 unsigned DestReg = 0;
23755 switch (Res.first) {
23757 case X86::AX: DestReg = X86::EAX; break;
23758 case X86::DX: DestReg = X86::EDX; break;
23759 case X86::CX: DestReg = X86::ECX; break;
23760 case X86::BX: DestReg = X86::EBX; break;
23761 case X86::SI: DestReg = X86::ESI; break;
23762 case X86::DI: DestReg = X86::EDI; break;
23763 case X86::BP: DestReg = X86::EBP; break;
23764 case X86::SP: DestReg = X86::ESP; break;
23767 Res.first = DestReg;
23768 Res.second = &X86::GR32RegClass;
23770 } else if (VT == MVT::i64 || VT == MVT::f64) {
23771 unsigned DestReg = 0;
23772 switch (Res.first) {
23774 case X86::AX: DestReg = X86::RAX; break;
23775 case X86::DX: DestReg = X86::RDX; break;
23776 case X86::CX: DestReg = X86::RCX; break;
23777 case X86::BX: DestReg = X86::RBX; break;
23778 case X86::SI: DestReg = X86::RSI; break;
23779 case X86::DI: DestReg = X86::RDI; break;
23780 case X86::BP: DestReg = X86::RBP; break;
23781 case X86::SP: DestReg = X86::RSP; break;
23784 Res.first = DestReg;
23785 Res.second = &X86::GR64RegClass;
23788 } else if (Res.second == &X86::FR32RegClass ||
23789 Res.second == &X86::FR64RegClass ||
23790 Res.second == &X86::VR128RegClass ||
23791 Res.second == &X86::VR256RegClass ||
23792 Res.second == &X86::FR32XRegClass ||
23793 Res.second == &X86::FR64XRegClass ||
23794 Res.second == &X86::VR128XRegClass ||
23795 Res.second == &X86::VR256XRegClass ||
23796 Res.second == &X86::VR512RegClass) {
23797 // Handle references to XMM physical registers that got mapped into the
23798 // wrong class. This can happen with constraints like {xmm0} where the
23799 // target independent register mapper will just pick the first match it can
23800 // find, ignoring the required type.
23802 if (VT == MVT::f32 || VT == MVT::i32)
23803 Res.second = &X86::FR32RegClass;
23804 else if (VT == MVT::f64 || VT == MVT::i64)
23805 Res.second = &X86::FR64RegClass;
23806 else if (X86::VR128RegClass.hasType(VT))
23807 Res.second = &X86::VR128RegClass;
23808 else if (X86::VR256RegClass.hasType(VT))
23809 Res.second = &X86::VR256RegClass;
23810 else if (X86::VR512RegClass.hasType(VT))
23811 Res.second = &X86::VR512RegClass;
23817 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23819 // Scaling factors are not free at all.
23820 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23821 // will take 2 allocations in the out of order engine instead of 1
23822 // for plain addressing mode, i.e. inst (reg1).
23824 // vaddps (%rsi,%drx), %ymm0, %ymm1
23825 // Requires two allocations (one for the load, one for the computation)
23827 // vaddps (%rsi), %ymm0, %ymm1
23828 // Requires just 1 allocation, i.e., freeing allocations for other operations
23829 // and having less micro operations to execute.
23831 // For some X86 architectures, this is even worse because for instance for
23832 // stores, the complex addressing mode forces the instruction to use the
23833 // "load" ports instead of the dedicated "store" port.
23834 // E.g., on Haswell:
23835 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23836 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
23837 if (isLegalAddressingMode(AM, Ty))
23838 // Scale represents reg2 * scale, thus account for 1
23839 // as soon as we use a second register.
23840 return AM.Scale != 0;
23844 bool X86TargetLowering::isTargetFTOL() const {
23845 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();