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 // SETOEQ and SETUNE require checking two conditions.
321 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
322 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
323 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
324 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
325 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
326 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
328 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
330 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
331 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
332 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
334 if (Subtarget->is64Bit()) {
335 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
336 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
337 } else if (!TM.Options.UseSoftFloat) {
338 // We have an algorithm for SSE2->double, and we turn this into a
339 // 64-bit FILD followed by conditional FADD for other targets.
340 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
341 // We have an algorithm for SSE2, and we turn this into a 64-bit
342 // FILD for other targets.
343 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
346 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
348 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
349 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
351 if (!TM.Options.UseSoftFloat) {
352 // SSE has no i16 to fp conversion, only i32
353 if (X86ScalarSSEf32) {
354 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
355 // f32 and f64 cases are Legal, f80 case is not
356 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
358 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
359 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
362 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
363 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
366 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
367 // are Legal, f80 is custom lowered.
368 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
369 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
371 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
373 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
374 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
376 if (X86ScalarSSEf32) {
377 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
378 // f32 and f64 cases are Legal, f80 case is not
379 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
381 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
382 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
385 // Handle FP_TO_UINT by promoting the destination to a larger signed
387 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
388 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
389 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
391 if (Subtarget->is64Bit()) {
392 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
393 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
394 } else if (!TM.Options.UseSoftFloat) {
395 // Since AVX is a superset of SSE3, only check for SSE here.
396 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
397 // Expand FP_TO_UINT into a select.
398 // FIXME: We would like to use a Custom expander here eventually to do
399 // the optimal thing for SSE vs. the default expansion in the legalizer.
400 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
402 // With SSE3 we can use fisttpll to convert to a signed i64; without
403 // SSE, we're stuck with a fistpll.
404 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
407 if (isTargetFTOL()) {
408 // Use the _ftol2 runtime function, which has a pseudo-instruction
409 // to handle its weird calling convention.
410 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
413 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
414 if (!X86ScalarSSEf64) {
415 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
416 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
417 if (Subtarget->is64Bit()) {
418 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
419 // Without SSE, i64->f64 goes through memory.
420 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
424 // Scalar integer divide and remainder are lowered to use operations that
425 // produce two results, to match the available instructions. This exposes
426 // the two-result form to trivial CSE, which is able to combine x/y and x%y
427 // into a single instruction.
429 // Scalar integer multiply-high is also lowered to use two-result
430 // operations, to match the available instructions. However, plain multiply
431 // (low) operations are left as Legal, as there are single-result
432 // instructions for this in x86. Using the two-result multiply instructions
433 // when both high and low results are needed must be arranged by dagcombine.
434 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
436 setOperationAction(ISD::MULHS, VT, Expand);
437 setOperationAction(ISD::MULHU, VT, Expand);
438 setOperationAction(ISD::SDIV, VT, Expand);
439 setOperationAction(ISD::UDIV, VT, Expand);
440 setOperationAction(ISD::SREM, VT, Expand);
441 setOperationAction(ISD::UREM, VT, Expand);
443 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
444 setOperationAction(ISD::ADDC, VT, Custom);
445 setOperationAction(ISD::ADDE, VT, Custom);
446 setOperationAction(ISD::SUBC, VT, Custom);
447 setOperationAction(ISD::SUBE, VT, Custom);
450 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
451 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
452 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
453 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
454 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
455 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
456 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
457 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
458 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
459 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
460 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
461 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
462 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
463 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
464 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
465 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
466 if (Subtarget->is64Bit())
467 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
468 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
469 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
470 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
471 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
472 setOperationAction(ISD::FREM , MVT::f32 , Expand);
473 setOperationAction(ISD::FREM , MVT::f64 , Expand);
474 setOperationAction(ISD::FREM , MVT::f80 , Expand);
475 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
477 // Promote the i8 variants and force them on up to i32 which has a shorter
479 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
480 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
481 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
482 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
483 if (Subtarget->hasBMI()) {
484 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
485 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
486 if (Subtarget->is64Bit())
487 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
489 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
490 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
491 if (Subtarget->is64Bit())
492 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
495 if (Subtarget->hasLZCNT()) {
496 // When promoting the i8 variants, force them to i32 for a shorter
498 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
499 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
500 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
501 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
502 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
503 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
504 if (Subtarget->is64Bit())
505 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
507 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
508 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
509 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
510 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
511 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
512 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
513 if (Subtarget->is64Bit()) {
514 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
515 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
519 // Special handling for half-precision floating point conversions.
520 // If we don't have F16C support, then lower half float conversions
521 // into library calls.
522 if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
523 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
524 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
527 // There's never any support for operations beyond MVT::f32.
528 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
529 setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
530 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
531 setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
533 setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
534 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
535 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
536 setTruncStoreAction(MVT::f80, MVT::f16, Expand);
538 if (Subtarget->hasPOPCNT()) {
539 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
541 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
542 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
543 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
544 if (Subtarget->is64Bit())
545 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
548 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
550 if (!Subtarget->hasMOVBE())
551 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
553 // These should be promoted to a larger select which is supported.
554 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
555 // X86 wants to expand cmov itself.
556 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
557 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
558 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
559 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
560 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
561 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
562 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
563 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
564 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
565 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
566 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
567 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
568 if (Subtarget->is64Bit()) {
569 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
570 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
572 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
573 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
574 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
575 // support continuation, user-level threading, and etc.. As a result, no
576 // other SjLj exception interfaces are implemented and please don't build
577 // your own exception handling based on them.
578 // LLVM/Clang supports zero-cost DWARF exception handling.
579 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
580 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
583 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
584 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
585 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
586 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
587 if (Subtarget->is64Bit())
588 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
589 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
590 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
591 if (Subtarget->is64Bit()) {
592 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
593 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
594 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
595 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
596 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
598 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
599 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
600 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
601 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
602 if (Subtarget->is64Bit()) {
603 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
604 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
605 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
608 if (Subtarget->hasSSE1())
609 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
611 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
613 // Expand certain atomics
614 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
616 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
617 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
618 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
621 if (Subtarget->hasCmpxchg16b()) {
622 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
625 // FIXME - use subtarget debug flags
626 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
627 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
628 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
631 if (Subtarget->is64Bit()) {
632 setExceptionPointerRegister(X86::RAX);
633 setExceptionSelectorRegister(X86::RDX);
635 setExceptionPointerRegister(X86::EAX);
636 setExceptionSelectorRegister(X86::EDX);
638 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
639 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
641 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
642 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
644 setOperationAction(ISD::TRAP, MVT::Other, Legal);
645 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
647 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
648 setOperationAction(ISD::VASTART , MVT::Other, Custom);
649 setOperationAction(ISD::VAEND , MVT::Other, Expand);
650 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
651 // TargetInfo::X86_64ABIBuiltinVaList
652 setOperationAction(ISD::VAARG , MVT::Other, Custom);
653 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
655 // TargetInfo::CharPtrBuiltinVaList
656 setOperationAction(ISD::VAARG , MVT::Other, Expand);
657 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
660 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
661 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
663 setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
665 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666 // f32 and f64 use SSE.
667 // Set up the FP register classes.
668 addRegisterClass(MVT::f32, &X86::FR32RegClass);
669 addRegisterClass(MVT::f64, &X86::FR64RegClass);
671 // Use ANDPD to simulate FABS.
672 setOperationAction(ISD::FABS , MVT::f64, Custom);
673 setOperationAction(ISD::FABS , MVT::f32, Custom);
675 // Use XORP to simulate FNEG.
676 setOperationAction(ISD::FNEG , MVT::f64, Custom);
677 setOperationAction(ISD::FNEG , MVT::f32, Custom);
679 // Use ANDPD and ORPD to simulate FCOPYSIGN.
680 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
683 // Lower this to FGETSIGNx86 plus an AND.
684 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
687 // We don't support sin/cos/fmod
688 setOperationAction(ISD::FSIN , MVT::f64, Expand);
689 setOperationAction(ISD::FCOS , MVT::f64, Expand);
690 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691 setOperationAction(ISD::FSIN , MVT::f32, Expand);
692 setOperationAction(ISD::FCOS , MVT::f32, Expand);
693 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
695 // Expand FP immediates into loads from the stack, except for the special
697 addLegalFPImmediate(APFloat(+0.0)); // xorpd
698 addLegalFPImmediate(APFloat(+0.0f)); // xorps
699 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700 // Use SSE for f32, x87 for f64.
701 // Set up the FP register classes.
702 addRegisterClass(MVT::f32, &X86::FR32RegClass);
703 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
705 // Use ANDPS to simulate FABS.
706 setOperationAction(ISD::FABS , MVT::f32, Custom);
708 // Use XORP to simulate FNEG.
709 setOperationAction(ISD::FNEG , MVT::f32, Custom);
711 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
713 // Use ANDPS and ORPS to simulate FCOPYSIGN.
714 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
717 // We don't support sin/cos/fmod
718 setOperationAction(ISD::FSIN , MVT::f32, Expand);
719 setOperationAction(ISD::FCOS , MVT::f32, Expand);
720 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
722 // Special cases we handle for FP constants.
723 addLegalFPImmediate(APFloat(+0.0f)); // xorps
724 addLegalFPImmediate(APFloat(+0.0)); // FLD0
725 addLegalFPImmediate(APFloat(+1.0)); // FLD1
726 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
729 if (!TM.Options.UnsafeFPMath) {
730 setOperationAction(ISD::FSIN , MVT::f64, Expand);
731 setOperationAction(ISD::FCOS , MVT::f64, Expand);
732 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
734 } else if (!TM.Options.UseSoftFloat) {
735 // f32 and f64 in x87.
736 // Set up the FP register classes.
737 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
740 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
741 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
742 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
745 if (!TM.Options.UnsafeFPMath) {
746 setOperationAction(ISD::FSIN , MVT::f64, Expand);
747 setOperationAction(ISD::FSIN , MVT::f32, Expand);
748 setOperationAction(ISD::FCOS , MVT::f64, Expand);
749 setOperationAction(ISD::FCOS , MVT::f32, Expand);
750 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
753 addLegalFPImmediate(APFloat(+0.0)); // FLD0
754 addLegalFPImmediate(APFloat(+1.0)); // FLD1
755 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
763 // We don't support FMA.
764 setOperationAction(ISD::FMA, MVT::f64, Expand);
765 setOperationAction(ISD::FMA, MVT::f32, Expand);
767 // Long double always uses X87.
768 if (!TM.Options.UseSoftFloat) {
769 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
771 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
773 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774 addLegalFPImmediate(TmpFlt); // FLD0
776 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
779 APFloat TmpFlt2(+1.0);
780 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
782 addLegalFPImmediate(TmpFlt2); // FLD1
783 TmpFlt2.changeSign();
784 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
787 if (!TM.Options.UnsafeFPMath) {
788 setOperationAction(ISD::FSIN , MVT::f80, Expand);
789 setOperationAction(ISD::FCOS , MVT::f80, Expand);
790 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
793 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
795 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796 setOperationAction(ISD::FRINT, MVT::f80, Expand);
797 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798 setOperationAction(ISD::FMA, MVT::f80, Expand);
801 // Always use a library call for pow.
802 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
803 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
804 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
806 setOperationAction(ISD::FLOG, MVT::f80, Expand);
807 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809 setOperationAction(ISD::FEXP, MVT::f80, Expand);
810 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
812 // First set operation action for all vector types to either promote
813 // (for widening) or expand (for scalarization). Then we will selectively
814 // turn on ones that can be effectively codegen'd.
815 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817 MVT VT = (MVT::SimpleValueType)i;
818 setOperationAction(ISD::ADD , VT, Expand);
819 setOperationAction(ISD::SUB , VT, Expand);
820 setOperationAction(ISD::FADD, VT, Expand);
821 setOperationAction(ISD::FNEG, VT, Expand);
822 setOperationAction(ISD::FSUB, VT, Expand);
823 setOperationAction(ISD::MUL , VT, Expand);
824 setOperationAction(ISD::FMUL, VT, Expand);
825 setOperationAction(ISD::SDIV, VT, Expand);
826 setOperationAction(ISD::UDIV, VT, Expand);
827 setOperationAction(ISD::FDIV, VT, Expand);
828 setOperationAction(ISD::SREM, VT, Expand);
829 setOperationAction(ISD::UREM, VT, Expand);
830 setOperationAction(ISD::LOAD, VT, Expand);
831 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836 setOperationAction(ISD::FABS, VT, Expand);
837 setOperationAction(ISD::FSIN, VT, Expand);
838 setOperationAction(ISD::FSINCOS, VT, Expand);
839 setOperationAction(ISD::FCOS, VT, Expand);
840 setOperationAction(ISD::FSINCOS, VT, Expand);
841 setOperationAction(ISD::FREM, VT, Expand);
842 setOperationAction(ISD::FMA, VT, Expand);
843 setOperationAction(ISD::FPOWI, VT, Expand);
844 setOperationAction(ISD::FSQRT, VT, Expand);
845 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846 setOperationAction(ISD::FFLOOR, VT, Expand);
847 setOperationAction(ISD::FCEIL, VT, Expand);
848 setOperationAction(ISD::FTRUNC, VT, Expand);
849 setOperationAction(ISD::FRINT, VT, Expand);
850 setOperationAction(ISD::FNEARBYINT, VT, Expand);
851 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852 setOperationAction(ISD::MULHS, VT, Expand);
853 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854 setOperationAction(ISD::MULHU, VT, Expand);
855 setOperationAction(ISD::SDIVREM, VT, Expand);
856 setOperationAction(ISD::UDIVREM, VT, Expand);
857 setOperationAction(ISD::FPOW, VT, Expand);
858 setOperationAction(ISD::CTPOP, VT, Expand);
859 setOperationAction(ISD::CTTZ, VT, Expand);
860 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861 setOperationAction(ISD::CTLZ, VT, Expand);
862 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863 setOperationAction(ISD::SHL, VT, Expand);
864 setOperationAction(ISD::SRA, VT, Expand);
865 setOperationAction(ISD::SRL, VT, Expand);
866 setOperationAction(ISD::ROTL, VT, Expand);
867 setOperationAction(ISD::ROTR, VT, Expand);
868 setOperationAction(ISD::BSWAP, VT, Expand);
869 setOperationAction(ISD::SETCC, VT, Expand);
870 setOperationAction(ISD::FLOG, VT, Expand);
871 setOperationAction(ISD::FLOG2, VT, Expand);
872 setOperationAction(ISD::FLOG10, VT, Expand);
873 setOperationAction(ISD::FEXP, VT, Expand);
874 setOperationAction(ISD::FEXP2, VT, Expand);
875 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880 setOperationAction(ISD::TRUNCATE, VT, Expand);
881 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884 setOperationAction(ISD::VSELECT, VT, Expand);
885 setOperationAction(ISD::SELECT_CC, VT, Expand);
886 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888 setTruncStoreAction(VT,
889 (MVT::SimpleValueType)InnerVT, Expand);
890 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
893 // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894 // we have to deal with them whether we ask for Expansion or not. Setting
895 // Expand causes its own optimisation problems though, so leave them legal.
896 if (VT.getVectorElementType() == MVT::i1)
897 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
900 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901 // with -msoft-float, disable use of MMX as well.
902 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904 // No operations on x86mmx supported, everything uses intrinsics.
907 // MMX-sized vectors (other than x86mmx) are expected to be expanded
908 // into smaller operations.
909 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
910 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
911 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
912 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
913 setOperationAction(ISD::AND, MVT::v8i8, Expand);
914 setOperationAction(ISD::AND, MVT::v4i16, Expand);
915 setOperationAction(ISD::AND, MVT::v2i32, Expand);
916 setOperationAction(ISD::AND, MVT::v1i64, Expand);
917 setOperationAction(ISD::OR, MVT::v8i8, Expand);
918 setOperationAction(ISD::OR, MVT::v4i16, Expand);
919 setOperationAction(ISD::OR, MVT::v2i32, Expand);
920 setOperationAction(ISD::OR, MVT::v1i64, Expand);
921 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
922 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
923 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
924 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
925 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
926 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
927 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
928 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
929 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
930 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
931 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
932 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
933 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
934 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
935 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
936 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
937 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
939 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
942 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
943 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
944 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
945 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
946 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
947 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
948 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
949 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
950 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
951 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
952 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
956 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
959 // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
960 // registers cannot be used even for integer operations.
961 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
966 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
967 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
968 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
969 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
970 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
971 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
972 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
973 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
974 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
975 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
976 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
977 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
978 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
979 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
980 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
981 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
982 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
983 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
984 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
985 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
986 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
987 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
989 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
990 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
991 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
992 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
994 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
995 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
998 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1000 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002 MVT VT = (MVT::SimpleValueType)i;
1003 // Do not attempt to custom lower non-power-of-2 vectors
1004 if (!isPowerOf2_32(VT.getVectorNumElements()))
1006 // Do not attempt to custom lower non-128-bit vectors
1007 if (!VT.is128BitVector())
1009 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1010 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1014 // We support custom legalizing of sext and anyext loads for specific
1015 // memory vector types which we can load as a scalar (or sequence of
1016 // scalars) and extend in-register to a legal 128-bit vector type. For sext
1017 // loads these must work with a single scalar load.
1018 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1019 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1020 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1021 setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1022 setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1023 setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1024 setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1025 setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1026 setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1028 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1029 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1030 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1031 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1032 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1033 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1035 if (Subtarget->is64Bit()) {
1036 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1037 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1040 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1041 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1042 MVT VT = (MVT::SimpleValueType)i;
1044 // Do not attempt to promote non-128-bit vectors
1045 if (!VT.is128BitVector())
1048 setOperationAction(ISD::AND, VT, Promote);
1049 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1050 setOperationAction(ISD::OR, VT, Promote);
1051 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1052 setOperationAction(ISD::XOR, VT, Promote);
1053 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1054 setOperationAction(ISD::LOAD, VT, Promote);
1055 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1056 setOperationAction(ISD::SELECT, VT, Promote);
1057 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1060 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
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 InitIntrinsicTables();
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);
2330 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2331 CallingConv::ID CallConv,
2333 const SmallVectorImpl<ISD::InputArg> &Ins,
2336 SmallVectorImpl<SDValue> &InVals)
2338 MachineFunction &MF = DAG.getMachineFunction();
2339 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2341 const Function* Fn = MF.getFunction();
2342 if (Fn->hasExternalLinkage() &&
2343 Subtarget->isTargetCygMing() &&
2344 Fn->getName() == "main")
2345 FuncInfo->setForceFramePointer(true);
2347 MachineFrameInfo *MFI = MF.getFrameInfo();
2348 bool Is64Bit = Subtarget->is64Bit();
2349 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2351 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2352 "Var args not supported with calling convention fastcc, ghc or hipe");
2354 // Assign locations to all of the incoming arguments.
2355 SmallVector<CCValAssign, 16> ArgLocs;
2356 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2358 // Allocate shadow area for Win64
2360 CCInfo.AllocateStack(32, 8);
2362 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2364 unsigned LastVal = ~0U;
2366 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2367 CCValAssign &VA = ArgLocs[i];
2368 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2370 assert(VA.getValNo() != LastVal &&
2371 "Don't support value assigned to multiple locs yet");
2373 LastVal = VA.getValNo();
2375 if (VA.isRegLoc()) {
2376 EVT RegVT = VA.getLocVT();
2377 const TargetRegisterClass *RC;
2378 if (RegVT == MVT::i32)
2379 RC = &X86::GR32RegClass;
2380 else if (Is64Bit && RegVT == MVT::i64)
2381 RC = &X86::GR64RegClass;
2382 else if (RegVT == MVT::f32)
2383 RC = &X86::FR32RegClass;
2384 else if (RegVT == MVT::f64)
2385 RC = &X86::FR64RegClass;
2386 else if (RegVT.is512BitVector())
2387 RC = &X86::VR512RegClass;
2388 else if (RegVT.is256BitVector())
2389 RC = &X86::VR256RegClass;
2390 else if (RegVT.is128BitVector())
2391 RC = &X86::VR128RegClass;
2392 else if (RegVT == MVT::x86mmx)
2393 RC = &X86::VR64RegClass;
2394 else if (RegVT == MVT::i1)
2395 RC = &X86::VK1RegClass;
2396 else if (RegVT == MVT::v8i1)
2397 RC = &X86::VK8RegClass;
2398 else if (RegVT == MVT::v16i1)
2399 RC = &X86::VK16RegClass;
2400 else if (RegVT == MVT::v32i1)
2401 RC = &X86::VK32RegClass;
2402 else if (RegVT == MVT::v64i1)
2403 RC = &X86::VK64RegClass;
2405 llvm_unreachable("Unknown argument type!");
2407 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2408 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2410 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2411 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2413 if (VA.getLocInfo() == CCValAssign::SExt)
2414 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2415 DAG.getValueType(VA.getValVT()));
2416 else if (VA.getLocInfo() == CCValAssign::ZExt)
2417 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2418 DAG.getValueType(VA.getValVT()));
2419 else if (VA.getLocInfo() == CCValAssign::BCvt)
2420 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2422 if (VA.isExtInLoc()) {
2423 // Handle MMX values passed in XMM regs.
2424 if (RegVT.isVector())
2425 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2427 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2430 assert(VA.isMemLoc());
2431 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2434 // If value is passed via pointer - do a load.
2435 if (VA.getLocInfo() == CCValAssign::Indirect)
2436 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2437 MachinePointerInfo(), false, false, false, 0);
2439 InVals.push_back(ArgValue);
2442 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2443 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2444 // The x86-64 ABIs require that for returning structs by value we copy
2445 // the sret argument into %rax/%eax (depending on ABI) for the return.
2446 // Win32 requires us to put the sret argument to %eax as well.
2447 // Save the argument into a virtual register so that we can access it
2448 // from the return points.
2449 if (Ins[i].Flags.isSRet()) {
2450 unsigned Reg = FuncInfo->getSRetReturnReg();
2452 MVT PtrTy = getPointerTy();
2453 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2454 FuncInfo->setSRetReturnReg(Reg);
2456 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2457 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2463 unsigned StackSize = CCInfo.getNextStackOffset();
2464 // Align stack specially for tail calls.
2465 if (FuncIsMadeTailCallSafe(CallConv,
2466 MF.getTarget().Options.GuaranteedTailCallOpt))
2467 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2469 // If the function takes variable number of arguments, make a frame index for
2470 // the start of the first vararg value... for expansion of llvm.va_start. We
2471 // can skip this if there are no va_start calls.
2472 if (isVarArg && MFI->hasVAStart()) {
2473 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2474 CallConv != CallingConv::X86_ThisCall)) {
2475 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2478 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2480 // FIXME: We should really autogenerate these arrays
2481 static const MCPhysReg GPR64ArgRegsWin64[] = {
2482 X86::RCX, X86::RDX, X86::R8, X86::R9
2484 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2485 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2487 static const MCPhysReg XMMArgRegs64Bit[] = {
2488 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2489 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2491 const MCPhysReg *GPR64ArgRegs;
2492 unsigned NumXMMRegs = 0;
2495 // The XMM registers which might contain var arg parameters are shadowed
2496 // in their paired GPR. So we only need to save the GPR to their home
2498 TotalNumIntRegs = 4;
2499 GPR64ArgRegs = GPR64ArgRegsWin64;
2501 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2502 GPR64ArgRegs = GPR64ArgRegs64Bit;
2504 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2507 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2510 bool NoImplicitFloatOps = Fn->getAttributes().
2511 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2512 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2513 "SSE register cannot be used when SSE is disabled!");
2514 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2515 NoImplicitFloatOps) &&
2516 "SSE register cannot be used when SSE is disabled!");
2517 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2518 !Subtarget->hasSSE1())
2519 // Kernel mode asks for SSE to be disabled, so don't push them
2521 TotalNumXMMRegs = 0;
2524 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2525 // Get to the caller-allocated home save location. Add 8 to account
2526 // for the return address.
2527 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2528 FuncInfo->setRegSaveFrameIndex(
2529 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2530 // Fixup to set vararg frame on shadow area (4 x i64).
2532 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2534 // For X86-64, if there are vararg parameters that are passed via
2535 // registers, then we must store them to their spots on the stack so
2536 // they may be loaded by deferencing the result of va_next.
2537 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2538 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2539 FuncInfo->setRegSaveFrameIndex(
2540 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2544 // Store the integer parameter registers.
2545 SmallVector<SDValue, 8> MemOps;
2546 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2548 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2549 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2550 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2551 DAG.getIntPtrConstant(Offset));
2552 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2553 &X86::GR64RegClass);
2554 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2556 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2557 MachinePointerInfo::getFixedStack(
2558 FuncInfo->getRegSaveFrameIndex(), Offset),
2560 MemOps.push_back(Store);
2564 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2565 // Now store the XMM (fp + vector) parameter registers.
2566 SmallVector<SDValue, 12> SaveXMMOps;
2567 SaveXMMOps.push_back(Chain);
2569 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2570 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2571 SaveXMMOps.push_back(ALVal);
2573 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2574 FuncInfo->getRegSaveFrameIndex()));
2575 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2576 FuncInfo->getVarArgsFPOffset()));
2578 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2579 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2580 &X86::VR128RegClass);
2581 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2582 SaveXMMOps.push_back(Val);
2584 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2585 MVT::Other, SaveXMMOps));
2588 if (!MemOps.empty())
2589 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2593 // Some CCs need callee pop.
2594 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2595 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2596 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2598 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2599 // If this is an sret function, the return should pop the hidden pointer.
2600 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2601 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2602 argsAreStructReturn(Ins) == StackStructReturn)
2603 FuncInfo->setBytesToPopOnReturn(4);
2607 // RegSaveFrameIndex is X86-64 only.
2608 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2609 if (CallConv == CallingConv::X86_FastCall ||
2610 CallConv == CallingConv::X86_ThisCall)
2611 // fastcc functions can't have varargs.
2612 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2615 FuncInfo->setArgumentStackSize(StackSize);
2621 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2622 SDValue StackPtr, SDValue Arg,
2623 SDLoc dl, SelectionDAG &DAG,
2624 const CCValAssign &VA,
2625 ISD::ArgFlagsTy Flags) const {
2626 unsigned LocMemOffset = VA.getLocMemOffset();
2627 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2628 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2629 if (Flags.isByVal())
2630 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2632 return DAG.getStore(Chain, dl, Arg, PtrOff,
2633 MachinePointerInfo::getStack(LocMemOffset),
2637 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2638 /// optimization is performed and it is required.
2640 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2641 SDValue &OutRetAddr, SDValue Chain,
2642 bool IsTailCall, bool Is64Bit,
2643 int FPDiff, SDLoc dl) const {
2644 // Adjust the Return address stack slot.
2645 EVT VT = getPointerTy();
2646 OutRetAddr = getReturnAddressFrameIndex(DAG);
2648 // Load the "old" Return address.
2649 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2650 false, false, false, 0);
2651 return SDValue(OutRetAddr.getNode(), 1);
2654 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2655 /// optimization is performed and it is required (FPDiff!=0).
2656 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2657 SDValue Chain, SDValue RetAddrFrIdx,
2658 EVT PtrVT, unsigned SlotSize,
2659 int FPDiff, SDLoc dl) {
2660 // Store the return address to the appropriate stack slot.
2661 if (!FPDiff) return Chain;
2662 // Calculate the new stack slot for the return address.
2663 int NewReturnAddrFI =
2664 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2666 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2667 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2668 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2674 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2675 SmallVectorImpl<SDValue> &InVals) const {
2676 SelectionDAG &DAG = CLI.DAG;
2678 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2679 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2680 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2681 SDValue Chain = CLI.Chain;
2682 SDValue Callee = CLI.Callee;
2683 CallingConv::ID CallConv = CLI.CallConv;
2684 bool &isTailCall = CLI.IsTailCall;
2685 bool isVarArg = CLI.IsVarArg;
2687 MachineFunction &MF = DAG.getMachineFunction();
2688 bool Is64Bit = Subtarget->is64Bit();
2689 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2690 StructReturnType SR = callIsStructReturn(Outs);
2691 bool IsSibcall = false;
2693 if (MF.getTarget().Options.DisableTailCalls)
2696 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2698 // Force this to be a tail call. The verifier rules are enough to ensure
2699 // that we can lower this successfully without moving the return address
2702 } else if (isTailCall) {
2703 // Check if it's really possible to do a tail call.
2704 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2705 isVarArg, SR != NotStructReturn,
2706 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2707 Outs, OutVals, Ins, DAG);
2709 // Sibcalls are automatically detected tailcalls which do not require
2711 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2718 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2719 "Var args not supported with calling convention fastcc, ghc or hipe");
2721 // Analyze operands of the call, assigning locations to each operand.
2722 SmallVector<CCValAssign, 16> ArgLocs;
2723 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2725 // Allocate shadow area for Win64
2727 CCInfo.AllocateStack(32, 8);
2729 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2731 // Get a count of how many bytes are to be pushed on the stack.
2732 unsigned NumBytes = CCInfo.getNextStackOffset();
2734 // This is a sibcall. The memory operands are available in caller's
2735 // own caller's stack.
2737 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2738 IsTailCallConvention(CallConv))
2739 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2742 if (isTailCall && !IsSibcall && !IsMustTail) {
2743 // Lower arguments at fp - stackoffset + fpdiff.
2744 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2745 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2747 FPDiff = NumBytesCallerPushed - NumBytes;
2749 // Set the delta of movement of the returnaddr stackslot.
2750 // But only set if delta is greater than previous delta.
2751 if (FPDiff < X86Info->getTCReturnAddrDelta())
2752 X86Info->setTCReturnAddrDelta(FPDiff);
2755 unsigned NumBytesToPush = NumBytes;
2756 unsigned NumBytesToPop = NumBytes;
2758 // If we have an inalloca argument, all stack space has already been allocated
2759 // for us and be right at the top of the stack. We don't support multiple
2760 // arguments passed in memory when using inalloca.
2761 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2763 if (!ArgLocs.back().isMemLoc())
2764 report_fatal_error("cannot use inalloca attribute on a register "
2766 if (ArgLocs.back().getLocMemOffset() != 0)
2767 report_fatal_error("any parameter with the inalloca attribute must be "
2768 "the only memory argument");
2772 Chain = DAG.getCALLSEQ_START(
2773 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2775 SDValue RetAddrFrIdx;
2776 // Load return address for tail calls.
2777 if (isTailCall && FPDiff)
2778 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2779 Is64Bit, FPDiff, dl);
2781 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2782 SmallVector<SDValue, 8> MemOpChains;
2785 // Walk the register/memloc assignments, inserting copies/loads. In the case
2786 // of tail call optimization arguments are handle later.
2787 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2788 DAG.getSubtarget().getRegisterInfo());
2789 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2790 // Skip inalloca arguments, they have already been written.
2791 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2792 if (Flags.isInAlloca())
2795 CCValAssign &VA = ArgLocs[i];
2796 EVT RegVT = VA.getLocVT();
2797 SDValue Arg = OutVals[i];
2798 bool isByVal = Flags.isByVal();
2800 // Promote the value if needed.
2801 switch (VA.getLocInfo()) {
2802 default: llvm_unreachable("Unknown loc info!");
2803 case CCValAssign::Full: break;
2804 case CCValAssign::SExt:
2805 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2807 case CCValAssign::ZExt:
2808 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2810 case CCValAssign::AExt:
2811 if (RegVT.is128BitVector()) {
2812 // Special case: passing MMX values in XMM registers.
2813 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2814 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2815 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2817 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2819 case CCValAssign::BCvt:
2820 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2822 case CCValAssign::Indirect: {
2823 // Store the argument.
2824 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2825 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2826 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2827 MachinePointerInfo::getFixedStack(FI),
2834 if (VA.isRegLoc()) {
2835 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2836 if (isVarArg && IsWin64) {
2837 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2838 // shadow reg if callee is a varargs function.
2839 unsigned ShadowReg = 0;
2840 switch (VA.getLocReg()) {
2841 case X86::XMM0: ShadowReg = X86::RCX; break;
2842 case X86::XMM1: ShadowReg = X86::RDX; break;
2843 case X86::XMM2: ShadowReg = X86::R8; break;
2844 case X86::XMM3: ShadowReg = X86::R9; break;
2847 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2849 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2850 assert(VA.isMemLoc());
2851 if (!StackPtr.getNode())
2852 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2854 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2855 dl, DAG, VA, Flags));
2859 if (!MemOpChains.empty())
2860 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2862 if (Subtarget->isPICStyleGOT()) {
2863 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2866 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2867 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2869 // If we are tail calling and generating PIC/GOT style code load the
2870 // address of the callee into ECX. The value in ecx is used as target of
2871 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2872 // for tail calls on PIC/GOT architectures. Normally we would just put the
2873 // address of GOT into ebx and then call target@PLT. But for tail calls
2874 // ebx would be restored (since ebx is callee saved) before jumping to the
2877 // Note: The actual moving to ECX is done further down.
2878 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2879 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2880 !G->getGlobal()->hasProtectedVisibility())
2881 Callee = LowerGlobalAddress(Callee, DAG);
2882 else if (isa<ExternalSymbolSDNode>(Callee))
2883 Callee = LowerExternalSymbol(Callee, DAG);
2887 if (Is64Bit && isVarArg && !IsWin64) {
2888 // From AMD64 ABI document:
2889 // For calls that may call functions that use varargs or stdargs
2890 // (prototype-less calls or calls to functions containing ellipsis (...) in
2891 // the declaration) %al is used as hidden argument to specify the number
2892 // of SSE registers used. The contents of %al do not need to match exactly
2893 // the number of registers, but must be an ubound on the number of SSE
2894 // registers used and is in the range 0 - 8 inclusive.
2896 // Count the number of XMM registers allocated.
2897 static const MCPhysReg XMMArgRegs[] = {
2898 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2899 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2901 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2902 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2903 && "SSE registers cannot be used when SSE is disabled");
2905 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2906 DAG.getConstant(NumXMMRegs, MVT::i8)));
2909 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2910 // don't need this because the eligibility check rejects calls that require
2911 // shuffling arguments passed in memory.
2912 if (!IsSibcall && isTailCall) {
2913 // Force all the incoming stack arguments to be loaded from the stack
2914 // before any new outgoing arguments are stored to the stack, because the
2915 // outgoing stack slots may alias the incoming argument stack slots, and
2916 // the alias isn't otherwise explicit. This is slightly more conservative
2917 // than necessary, because it means that each store effectively depends
2918 // on every argument instead of just those arguments it would clobber.
2919 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2921 SmallVector<SDValue, 8> MemOpChains2;
2924 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2925 CCValAssign &VA = ArgLocs[i];
2928 assert(VA.isMemLoc());
2929 SDValue Arg = OutVals[i];
2930 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2931 // Skip inalloca arguments. They don't require any work.
2932 if (Flags.isInAlloca())
2934 // Create frame index.
2935 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2936 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2937 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2938 FIN = DAG.getFrameIndex(FI, getPointerTy());
2940 if (Flags.isByVal()) {
2941 // Copy relative to framepointer.
2942 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2943 if (!StackPtr.getNode())
2944 StackPtr = DAG.getCopyFromReg(Chain, dl,
2945 RegInfo->getStackRegister(),
2947 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2949 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2953 // Store relative to framepointer.
2954 MemOpChains2.push_back(
2955 DAG.getStore(ArgChain, dl, Arg, FIN,
2956 MachinePointerInfo::getFixedStack(FI),
2961 if (!MemOpChains2.empty())
2962 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2964 // Store the return address to the appropriate stack slot.
2965 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2966 getPointerTy(), RegInfo->getSlotSize(),
2970 // Build a sequence of copy-to-reg nodes chained together with token chain
2971 // and flag operands which copy the outgoing args into registers.
2973 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2974 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2975 RegsToPass[i].second, InFlag);
2976 InFlag = Chain.getValue(1);
2979 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2980 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2981 // In the 64-bit large code model, we have to make all calls
2982 // through a register, since the call instruction's 32-bit
2983 // pc-relative offset may not be large enough to hold the whole
2985 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2986 // If the callee is a GlobalAddress node (quite common, every direct call
2987 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2990 // We should use extra load for direct calls to dllimported functions in
2992 const GlobalValue *GV = G->getGlobal();
2993 if (!GV->hasDLLImportStorageClass()) {
2994 unsigned char OpFlags = 0;
2995 bool ExtraLoad = false;
2996 unsigned WrapperKind = ISD::DELETED_NODE;
2998 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2999 // external symbols most go through the PLT in PIC mode. If the symbol
3000 // has hidden or protected visibility, or if it is static or local, then
3001 // we don't need to use the PLT - we can directly call it.
3002 if (Subtarget->isTargetELF() &&
3003 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3004 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3005 OpFlags = X86II::MO_PLT;
3006 } else if (Subtarget->isPICStyleStubAny() &&
3007 (GV->isDeclaration() || GV->isWeakForLinker()) &&
3008 (!Subtarget->getTargetTriple().isMacOSX() ||
3009 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3010 // PC-relative references to external symbols should go through $stub,
3011 // unless we're building with the leopard linker or later, which
3012 // automatically synthesizes these stubs.
3013 OpFlags = X86II::MO_DARWIN_STUB;
3014 } else if (Subtarget->isPICStyleRIPRel() &&
3015 isa<Function>(GV) &&
3016 cast<Function>(GV)->getAttributes().
3017 hasAttribute(AttributeSet::FunctionIndex,
3018 Attribute::NonLazyBind)) {
3019 // If the function is marked as non-lazy, generate an indirect call
3020 // which loads from the GOT directly. This avoids runtime overhead
3021 // at the cost of eager binding (and one extra byte of encoding).
3022 OpFlags = X86II::MO_GOTPCREL;
3023 WrapperKind = X86ISD::WrapperRIP;
3027 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3028 G->getOffset(), OpFlags);
3030 // Add a wrapper if needed.
3031 if (WrapperKind != ISD::DELETED_NODE)
3032 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3033 // Add extra indirection if needed.
3035 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3036 MachinePointerInfo::getGOT(),
3037 false, false, false, 0);
3039 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3040 unsigned char OpFlags = 0;
3042 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3043 // external symbols should go through the PLT.
3044 if (Subtarget->isTargetELF() &&
3045 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3046 OpFlags = X86II::MO_PLT;
3047 } else if (Subtarget->isPICStyleStubAny() &&
3048 (!Subtarget->getTargetTriple().isMacOSX() ||
3049 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3050 // PC-relative references to external symbols should go through $stub,
3051 // unless we're building with the leopard linker or later, which
3052 // automatically synthesizes these stubs.
3053 OpFlags = X86II::MO_DARWIN_STUB;
3056 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3060 // Returns a chain & a flag for retval copy to use.
3061 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3062 SmallVector<SDValue, 8> Ops;
3064 if (!IsSibcall && isTailCall) {
3065 Chain = DAG.getCALLSEQ_END(Chain,
3066 DAG.getIntPtrConstant(NumBytesToPop, true),
3067 DAG.getIntPtrConstant(0, true), InFlag, dl);
3068 InFlag = Chain.getValue(1);
3071 Ops.push_back(Chain);
3072 Ops.push_back(Callee);
3075 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3077 // Add argument registers to the end of the list so that they are known live
3079 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3080 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3081 RegsToPass[i].second.getValueType()));
3083 // Add a register mask operand representing the call-preserved registers.
3084 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3085 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3086 assert(Mask && "Missing call preserved mask for calling convention");
3087 Ops.push_back(DAG.getRegisterMask(Mask));
3089 if (InFlag.getNode())
3090 Ops.push_back(InFlag);
3094 //// If this is the first return lowered for this function, add the regs
3095 //// to the liveout set for the function.
3096 // This isn't right, although it's probably harmless on x86; liveouts
3097 // should be computed from returns not tail calls. Consider a void
3098 // function making a tail call to a function returning int.
3099 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3102 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3103 InFlag = Chain.getValue(1);
3105 // Create the CALLSEQ_END node.
3106 unsigned NumBytesForCalleeToPop;
3107 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3108 DAG.getTarget().Options.GuaranteedTailCallOpt))
3109 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3110 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3111 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3112 SR == StackStructReturn)
3113 // If this is a call to a struct-return function, the callee
3114 // pops the hidden struct pointer, so we have to push it back.
3115 // This is common for Darwin/X86, Linux & Mingw32 targets.
3116 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3117 NumBytesForCalleeToPop = 4;
3119 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3121 // Returns a flag for retval copy to use.
3123 Chain = DAG.getCALLSEQ_END(Chain,
3124 DAG.getIntPtrConstant(NumBytesToPop, true),
3125 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3128 InFlag = Chain.getValue(1);
3131 // Handle result values, copying them out of physregs into vregs that we
3133 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3134 Ins, dl, DAG, InVals);
3137 //===----------------------------------------------------------------------===//
3138 // Fast Calling Convention (tail call) implementation
3139 //===----------------------------------------------------------------------===//
3141 // Like std call, callee cleans arguments, convention except that ECX is
3142 // reserved for storing the tail called function address. Only 2 registers are
3143 // free for argument passing (inreg). Tail call optimization is performed
3145 // * tailcallopt is enabled
3146 // * caller/callee are fastcc
3147 // On X86_64 architecture with GOT-style position independent code only local
3148 // (within module) calls are supported at the moment.
3149 // To keep the stack aligned according to platform abi the function
3150 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3151 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3152 // If a tail called function callee has more arguments than the caller the
3153 // caller needs to make sure that there is room to move the RETADDR to. This is
3154 // achieved by reserving an area the size of the argument delta right after the
3155 // original RETADDR, but before the saved framepointer or the spilled registers
3156 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3168 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3169 /// for a 16 byte align requirement.
3171 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3172 SelectionDAG& DAG) const {
3173 MachineFunction &MF = DAG.getMachineFunction();
3174 const TargetMachine &TM = MF.getTarget();
3175 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3176 TM.getSubtargetImpl()->getRegisterInfo());
3177 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3178 unsigned StackAlignment = TFI.getStackAlignment();
3179 uint64_t AlignMask = StackAlignment - 1;
3180 int64_t Offset = StackSize;
3181 unsigned SlotSize = RegInfo->getSlotSize();
3182 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3183 // Number smaller than 12 so just add the difference.
3184 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3186 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3187 Offset = ((~AlignMask) & Offset) + StackAlignment +
3188 (StackAlignment-SlotSize);
3193 /// MatchingStackOffset - Return true if the given stack call argument is
3194 /// already available in the same position (relatively) of the caller's
3195 /// incoming argument stack.
3197 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3198 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3199 const X86InstrInfo *TII) {
3200 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3202 if (Arg.getOpcode() == ISD::CopyFromReg) {
3203 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3204 if (!TargetRegisterInfo::isVirtualRegister(VR))
3206 MachineInstr *Def = MRI->getVRegDef(VR);
3209 if (!Flags.isByVal()) {
3210 if (!TII->isLoadFromStackSlot(Def, FI))
3213 unsigned Opcode = Def->getOpcode();
3214 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3215 Def->getOperand(1).isFI()) {
3216 FI = Def->getOperand(1).getIndex();
3217 Bytes = Flags.getByValSize();
3221 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3222 if (Flags.isByVal())
3223 // ByVal argument is passed in as a pointer but it's now being
3224 // dereferenced. e.g.
3225 // define @foo(%struct.X* %A) {
3226 // tail call @bar(%struct.X* byval %A)
3229 SDValue Ptr = Ld->getBasePtr();
3230 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3233 FI = FINode->getIndex();
3234 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3235 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3236 FI = FINode->getIndex();
3237 Bytes = Flags.getByValSize();
3241 assert(FI != INT_MAX);
3242 if (!MFI->isFixedObjectIndex(FI))
3244 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3247 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3248 /// for tail call optimization. Targets which want to do tail call
3249 /// optimization should implement this function.
3251 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3252 CallingConv::ID CalleeCC,
3254 bool isCalleeStructRet,
3255 bool isCallerStructRet,
3257 const SmallVectorImpl<ISD::OutputArg> &Outs,
3258 const SmallVectorImpl<SDValue> &OutVals,
3259 const SmallVectorImpl<ISD::InputArg> &Ins,
3260 SelectionDAG &DAG) const {
3261 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3264 // If -tailcallopt is specified, make fastcc functions tail-callable.
3265 const MachineFunction &MF = DAG.getMachineFunction();
3266 const Function *CallerF = MF.getFunction();
3268 // If the function return type is x86_fp80 and the callee return type is not,
3269 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3270 // perform a tailcall optimization here.
3271 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3274 CallingConv::ID CallerCC = CallerF->getCallingConv();
3275 bool CCMatch = CallerCC == CalleeCC;
3276 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3277 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3279 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3280 if (IsTailCallConvention(CalleeCC) && CCMatch)
3285 // Look for obvious safe cases to perform tail call optimization that do not
3286 // require ABI changes. This is what gcc calls sibcall.
3288 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3289 // emit a special epilogue.
3290 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3291 DAG.getSubtarget().getRegisterInfo());
3292 if (RegInfo->needsStackRealignment(MF))
3295 // Also avoid sibcall optimization if either caller or callee uses struct
3296 // return semantics.
3297 if (isCalleeStructRet || isCallerStructRet)
3300 // An stdcall/thiscall caller is expected to clean up its arguments; the
3301 // callee isn't going to do that.
3302 // FIXME: this is more restrictive than needed. We could produce a tailcall
3303 // when the stack adjustment matches. For example, with a thiscall that takes
3304 // only one argument.
3305 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3306 CallerCC == CallingConv::X86_ThisCall))
3309 // Do not sibcall optimize vararg calls unless all arguments are passed via
3311 if (isVarArg && !Outs.empty()) {
3313 // Optimizing for varargs on Win64 is unlikely to be safe without
3314 // additional testing.
3315 if (IsCalleeWin64 || IsCallerWin64)
3318 SmallVector<CCValAssign, 16> ArgLocs;
3319 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3322 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3323 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3324 if (!ArgLocs[i].isRegLoc())
3328 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3329 // stack. Therefore, if it's not used by the call it is not safe to optimize
3330 // this into a sibcall.
3331 bool Unused = false;
3332 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3339 SmallVector<CCValAssign, 16> RVLocs;
3340 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3342 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3343 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3344 CCValAssign &VA = RVLocs[i];
3345 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3350 // If the calling conventions do not match, then we'd better make sure the
3351 // results are returned in the same way as what the caller expects.
3353 SmallVector<CCValAssign, 16> RVLocs1;
3354 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3356 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3358 SmallVector<CCValAssign, 16> RVLocs2;
3359 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3361 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3363 if (RVLocs1.size() != RVLocs2.size())
3365 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3366 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3368 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3370 if (RVLocs1[i].isRegLoc()) {
3371 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3374 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3380 // If the callee takes no arguments then go on to check the results of the
3382 if (!Outs.empty()) {
3383 // Check if stack adjustment is needed. For now, do not do this if any
3384 // argument is passed on the stack.
3385 SmallVector<CCValAssign, 16> ArgLocs;
3386 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3389 // Allocate shadow area for Win64
3391 CCInfo.AllocateStack(32, 8);
3393 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3394 if (CCInfo.getNextStackOffset()) {
3395 MachineFunction &MF = DAG.getMachineFunction();
3396 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3399 // Check if the arguments are already laid out in the right way as
3400 // the caller's fixed stack objects.
3401 MachineFrameInfo *MFI = MF.getFrameInfo();
3402 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3403 const X86InstrInfo *TII =
3404 static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3405 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3406 CCValAssign &VA = ArgLocs[i];
3407 SDValue Arg = OutVals[i];
3408 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3409 if (VA.getLocInfo() == CCValAssign::Indirect)
3411 if (!VA.isRegLoc()) {
3412 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3419 // If the tailcall address may be in a register, then make sure it's
3420 // possible to register allocate for it. In 32-bit, the call address can
3421 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3422 // callee-saved registers are restored. These happen to be the same
3423 // registers used to pass 'inreg' arguments so watch out for those.
3424 if (!Subtarget->is64Bit() &&
3425 ((!isa<GlobalAddressSDNode>(Callee) &&
3426 !isa<ExternalSymbolSDNode>(Callee)) ||
3427 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3428 unsigned NumInRegs = 0;
3429 // In PIC we need an extra register to formulate the address computation
3431 unsigned MaxInRegs =
3432 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3434 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3435 CCValAssign &VA = ArgLocs[i];
3438 unsigned Reg = VA.getLocReg();
3441 case X86::EAX: case X86::EDX: case X86::ECX:
3442 if (++NumInRegs == MaxInRegs)
3454 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3455 const TargetLibraryInfo *libInfo) const {
3456 return X86::createFastISel(funcInfo, libInfo);
3459 //===----------------------------------------------------------------------===//
3460 // Other Lowering Hooks
3461 //===----------------------------------------------------------------------===//
3463 static bool MayFoldLoad(SDValue Op) {
3464 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3467 static bool MayFoldIntoStore(SDValue Op) {
3468 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3471 static bool isTargetShuffle(unsigned Opcode) {
3473 default: return false;
3474 case X86ISD::PSHUFB:
3475 case X86ISD::PSHUFD:
3476 case X86ISD::PSHUFHW:
3477 case X86ISD::PSHUFLW:
3479 case X86ISD::PALIGNR:
3480 case X86ISD::MOVLHPS:
3481 case X86ISD::MOVLHPD:
3482 case X86ISD::MOVHLPS:
3483 case X86ISD::MOVLPS:
3484 case X86ISD::MOVLPD:
3485 case X86ISD::MOVSHDUP:
3486 case X86ISD::MOVSLDUP:
3487 case X86ISD::MOVDDUP:
3490 case X86ISD::UNPCKL:
3491 case X86ISD::UNPCKH:
3492 case X86ISD::VPERMILP:
3493 case X86ISD::VPERM2X128:
3494 case X86ISD::VPERMI:
3499 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3500 SDValue V1, SelectionDAG &DAG) {
3502 default: llvm_unreachable("Unknown x86 shuffle node");
3503 case X86ISD::MOVSHDUP:
3504 case X86ISD::MOVSLDUP:
3505 case X86ISD::MOVDDUP:
3506 return DAG.getNode(Opc, dl, VT, V1);
3510 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3511 SDValue V1, unsigned TargetMask,
3512 SelectionDAG &DAG) {
3514 default: llvm_unreachable("Unknown x86 shuffle node");
3515 case X86ISD::PSHUFD:
3516 case X86ISD::PSHUFHW:
3517 case X86ISD::PSHUFLW:
3518 case X86ISD::VPERMILP:
3519 case X86ISD::VPERMI:
3520 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3524 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3525 SDValue V1, SDValue V2, unsigned TargetMask,
3526 SelectionDAG &DAG) {
3528 default: llvm_unreachable("Unknown x86 shuffle node");
3529 case X86ISD::PALIGNR:
3530 case X86ISD::VALIGN:
3532 case X86ISD::VPERM2X128:
3533 return DAG.getNode(Opc, dl, VT, V1, V2,
3534 DAG.getConstant(TargetMask, MVT::i8));
3538 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3539 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3541 default: llvm_unreachable("Unknown x86 shuffle node");
3542 case X86ISD::MOVLHPS:
3543 case X86ISD::MOVLHPD:
3544 case X86ISD::MOVHLPS:
3545 case X86ISD::MOVLPS:
3546 case X86ISD::MOVLPD:
3549 case X86ISD::UNPCKL:
3550 case X86ISD::UNPCKH:
3551 return DAG.getNode(Opc, dl, VT, V1, V2);
3555 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3556 MachineFunction &MF = DAG.getMachineFunction();
3557 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3558 DAG.getSubtarget().getRegisterInfo());
3559 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3560 int ReturnAddrIndex = FuncInfo->getRAIndex();
3562 if (ReturnAddrIndex == 0) {
3563 // Set up a frame object for the return address.
3564 unsigned SlotSize = RegInfo->getSlotSize();
3565 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3568 FuncInfo->setRAIndex(ReturnAddrIndex);
3571 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3574 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3575 bool hasSymbolicDisplacement) {
3576 // Offset should fit into 32 bit immediate field.
3577 if (!isInt<32>(Offset))
3580 // If we don't have a symbolic displacement - we don't have any extra
3582 if (!hasSymbolicDisplacement)
3585 // FIXME: Some tweaks might be needed for medium code model.
3586 if (M != CodeModel::Small && M != CodeModel::Kernel)
3589 // For small code model we assume that latest object is 16MB before end of 31
3590 // bits boundary. We may also accept pretty large negative constants knowing
3591 // that all objects are in the positive half of address space.
3592 if (M == CodeModel::Small && Offset < 16*1024*1024)
3595 // For kernel code model we know that all object resist in the negative half
3596 // of 32bits address space. We may not accept negative offsets, since they may
3597 // be just off and we may accept pretty large positive ones.
3598 if (M == CodeModel::Kernel && Offset > 0)
3604 /// isCalleePop - Determines whether the callee is required to pop its
3605 /// own arguments. Callee pop is necessary to support tail calls.
3606 bool X86::isCalleePop(CallingConv::ID CallingConv,
3607 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3611 switch (CallingConv) {
3614 case CallingConv::X86_StdCall:
3616 case CallingConv::X86_FastCall:
3618 case CallingConv::X86_ThisCall:
3620 case CallingConv::Fast:
3622 case CallingConv::GHC:
3624 case CallingConv::HiPE:
3629 /// \brief Return true if the condition is an unsigned comparison operation.
3630 static bool isX86CCUnsigned(unsigned X86CC) {
3632 default: llvm_unreachable("Invalid integer condition!");
3633 case X86::COND_E: return true;
3634 case X86::COND_G: return false;
3635 case X86::COND_GE: return false;
3636 case X86::COND_L: return false;
3637 case X86::COND_LE: return false;
3638 case X86::COND_NE: return true;
3639 case X86::COND_B: return true;
3640 case X86::COND_A: return true;
3641 case X86::COND_BE: return true;
3642 case X86::COND_AE: return true;
3644 llvm_unreachable("covered switch fell through?!");
3647 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3648 /// specific condition code, returning the condition code and the LHS/RHS of the
3649 /// comparison to make.
3650 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3651 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3653 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3654 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3655 // X > -1 -> X == 0, jump !sign.
3656 RHS = DAG.getConstant(0, RHS.getValueType());
3657 return X86::COND_NS;
3659 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3660 // X < 0 -> X == 0, jump on sign.
3663 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3665 RHS = DAG.getConstant(0, RHS.getValueType());
3666 return X86::COND_LE;
3670 switch (SetCCOpcode) {
3671 default: llvm_unreachable("Invalid integer condition!");
3672 case ISD::SETEQ: return X86::COND_E;
3673 case ISD::SETGT: return X86::COND_G;
3674 case ISD::SETGE: return X86::COND_GE;
3675 case ISD::SETLT: return X86::COND_L;
3676 case ISD::SETLE: return X86::COND_LE;
3677 case ISD::SETNE: return X86::COND_NE;
3678 case ISD::SETULT: return X86::COND_B;
3679 case ISD::SETUGT: return X86::COND_A;
3680 case ISD::SETULE: return X86::COND_BE;
3681 case ISD::SETUGE: return X86::COND_AE;
3685 // First determine if it is required or is profitable to flip the operands.
3687 // If LHS is a foldable load, but RHS is not, flip the condition.
3688 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3689 !ISD::isNON_EXTLoad(RHS.getNode())) {
3690 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3691 std::swap(LHS, RHS);
3694 switch (SetCCOpcode) {
3700 std::swap(LHS, RHS);
3704 // On a floating point condition, the flags are set as follows:
3706 // 0 | 0 | 0 | X > Y
3707 // 0 | 0 | 1 | X < Y
3708 // 1 | 0 | 0 | X == Y
3709 // 1 | 1 | 1 | unordered
3710 switch (SetCCOpcode) {
3711 default: llvm_unreachable("Condcode should be pre-legalized away");
3713 case ISD::SETEQ: return X86::COND_E;
3714 case ISD::SETOLT: // flipped
3716 case ISD::SETGT: return X86::COND_A;
3717 case ISD::SETOLE: // flipped
3719 case ISD::SETGE: return X86::COND_AE;
3720 case ISD::SETUGT: // flipped
3722 case ISD::SETLT: return X86::COND_B;
3723 case ISD::SETUGE: // flipped
3725 case ISD::SETLE: return X86::COND_BE;
3727 case ISD::SETNE: return X86::COND_NE;
3728 case ISD::SETUO: return X86::COND_P;
3729 case ISD::SETO: return X86::COND_NP;
3731 case ISD::SETUNE: return X86::COND_INVALID;
3735 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3736 /// code. Current x86 isa includes the following FP cmov instructions:
3737 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3738 static bool hasFPCMov(unsigned X86CC) {
3754 /// isFPImmLegal - Returns true if the target can instruction select the
3755 /// specified FP immediate natively. If false, the legalizer will
3756 /// materialize the FP immediate as a load from a constant pool.
3757 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3758 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3759 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3765 /// \brief Returns true if it is beneficial to convert a load of a constant
3766 /// to just the constant itself.
3767 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3769 assert(Ty->isIntegerTy());
3771 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3772 if (BitSize == 0 || BitSize > 64)
3777 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3778 /// the specified range (L, H].
3779 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3780 return (Val < 0) || (Val >= Low && Val < Hi);
3783 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3784 /// specified value.
3785 static bool isUndefOrEqual(int Val, int CmpVal) {
3786 return (Val < 0 || Val == CmpVal);
3789 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3790 /// from position Pos and ending in Pos+Size, falls within the specified
3791 /// sequential range (L, L+Pos]. or is undef.
3792 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3793 unsigned Pos, unsigned Size, int Low) {
3794 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3795 if (!isUndefOrEqual(Mask[i], Low))
3800 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3801 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3802 /// the second operand.
3803 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3804 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3805 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3806 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3807 return (Mask[0] < 2 && Mask[1] < 2);
3811 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3812 /// is suitable for input to PSHUFHW.
3813 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3814 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3817 // Lower quadword copied in order or undef.
3818 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3821 // Upper quadword shuffled.
3822 for (unsigned i = 4; i != 8; ++i)
3823 if (!isUndefOrInRange(Mask[i], 4, 8))
3826 if (VT == MVT::v16i16) {
3827 // Lower quadword copied in order or undef.
3828 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3831 // Upper quadword shuffled.
3832 for (unsigned i = 12; i != 16; ++i)
3833 if (!isUndefOrInRange(Mask[i], 12, 16))
3840 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3841 /// is suitable for input to PSHUFLW.
3842 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3843 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3846 // Upper quadword copied in order.
3847 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3850 // Lower quadword shuffled.
3851 for (unsigned i = 0; i != 4; ++i)
3852 if (!isUndefOrInRange(Mask[i], 0, 4))
3855 if (VT == MVT::v16i16) {
3856 // Upper quadword copied in order.
3857 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3860 // Lower quadword shuffled.
3861 for (unsigned i = 8; i != 12; ++i)
3862 if (!isUndefOrInRange(Mask[i], 8, 12))
3869 /// \brief Return true if the mask specifies a shuffle of elements that is
3870 /// suitable for input to intralane (palignr) or interlane (valign) vector
3872 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3873 unsigned NumElts = VT.getVectorNumElements();
3874 unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3875 unsigned NumLaneElts = NumElts/NumLanes;
3877 // Do not handle 64-bit element shuffles with palignr.
3878 if (NumLaneElts == 2)
3881 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3883 for (i = 0; i != NumLaneElts; ++i) {
3888 // Lane is all undef, go to next lane
3889 if (i == NumLaneElts)
3892 int Start = Mask[i+l];
3894 // Make sure its in this lane in one of the sources
3895 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3896 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3899 // If not lane 0, then we must match lane 0
3900 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3903 // Correct second source to be contiguous with first source
3904 if (Start >= (int)NumElts)
3905 Start -= NumElts - NumLaneElts;
3907 // Make sure we're shifting in the right direction.
3908 if (Start <= (int)(i+l))
3913 // Check the rest of the elements to see if they are consecutive.
3914 for (++i; i != NumLaneElts; ++i) {
3915 int Idx = Mask[i+l];
3917 // Make sure its in this lane
3918 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3919 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3922 // If not lane 0, then we must match lane 0
3923 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3926 if (Idx >= (int)NumElts)
3927 Idx -= NumElts - NumLaneElts;
3929 if (!isUndefOrEqual(Idx, Start+i))
3938 /// \brief Return true if the node specifies a shuffle of elements that is
3939 /// suitable for input to PALIGNR.
3940 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3941 const X86Subtarget *Subtarget) {
3942 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3943 (VT.is256BitVector() && !Subtarget->hasInt256()) ||
3944 VT.is512BitVector())
3945 // FIXME: Add AVX512BW.
3948 return isAlignrMask(Mask, VT, false);
3951 /// \brief Return true if the node specifies a shuffle of elements that is
3952 /// suitable for input to VALIGN.
3953 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
3954 const X86Subtarget *Subtarget) {
3955 // FIXME: Add AVX512VL.
3956 if (!VT.is512BitVector() || !Subtarget->hasAVX512())
3958 return isAlignrMask(Mask, VT, true);
3961 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3962 /// the two vector operands have swapped position.
3963 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3964 unsigned NumElems) {
3965 for (unsigned i = 0; i != NumElems; ++i) {
3969 else if (idx < (int)NumElems)
3970 Mask[i] = idx + NumElems;
3972 Mask[i] = idx - NumElems;
3976 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3977 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3978 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3979 /// reverse of what x86 shuffles want.
3980 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3982 unsigned NumElems = VT.getVectorNumElements();
3983 unsigned NumLanes = VT.getSizeInBits()/128;
3984 unsigned NumLaneElems = NumElems/NumLanes;
3986 if (NumLaneElems != 2 && NumLaneElems != 4)
3989 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3990 bool symetricMaskRequired =
3991 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3993 // VSHUFPSY divides the resulting vector into 4 chunks.
3994 // The sources are also splitted into 4 chunks, and each destination
3995 // chunk must come from a different source chunk.
3997 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3998 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
4000 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
4001 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
4003 // VSHUFPDY divides the resulting vector into 4 chunks.
4004 // The sources are also splitted into 4 chunks, and each destination
4005 // chunk must come from a different source chunk.
4007 // SRC1 => X3 X2 X1 X0
4008 // SRC2 => Y3 Y2 Y1 Y0
4010 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
4012 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4013 unsigned HalfLaneElems = NumLaneElems/2;
4014 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4015 for (unsigned i = 0; i != NumLaneElems; ++i) {
4016 int Idx = Mask[i+l];
4017 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4018 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4020 // For VSHUFPSY, the mask of the second half must be the same as the
4021 // first but with the appropriate offsets. This works in the same way as
4022 // VPERMILPS works with masks.
4023 if (!symetricMaskRequired || Idx < 0)
4025 if (MaskVal[i] < 0) {
4026 MaskVal[i] = Idx - l;
4029 if ((signed)(Idx - l) != MaskVal[i])
4037 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4038 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4039 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4040 if (!VT.is128BitVector())
4043 unsigned NumElems = VT.getVectorNumElements();
4048 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4049 return isUndefOrEqual(Mask[0], 6) &&
4050 isUndefOrEqual(Mask[1], 7) &&
4051 isUndefOrEqual(Mask[2], 2) &&
4052 isUndefOrEqual(Mask[3], 3);
4055 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4056 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4058 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4059 if (!VT.is128BitVector())
4062 unsigned NumElems = VT.getVectorNumElements();
4067 return isUndefOrEqual(Mask[0], 2) &&
4068 isUndefOrEqual(Mask[1], 3) &&
4069 isUndefOrEqual(Mask[2], 2) &&
4070 isUndefOrEqual(Mask[3], 3);
4073 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4074 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4075 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4076 if (!VT.is128BitVector())
4079 unsigned NumElems = VT.getVectorNumElements();
4081 if (NumElems != 2 && NumElems != 4)
4084 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4085 if (!isUndefOrEqual(Mask[i], i + NumElems))
4088 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4089 if (!isUndefOrEqual(Mask[i], i))
4095 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4096 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4097 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4098 if (!VT.is128BitVector())
4101 unsigned NumElems = VT.getVectorNumElements();
4103 if (NumElems != 2 && NumElems != 4)
4106 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4107 if (!isUndefOrEqual(Mask[i], i))
4110 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4111 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4117 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4118 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4119 /// i. e: If all but one element come from the same vector.
4120 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4121 // TODO: Deal with AVX's VINSERTPS
4122 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4125 unsigned CorrectPosV1 = 0;
4126 unsigned CorrectPosV2 = 0;
4127 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4128 if (Mask[i] == -1) {
4136 else if (Mask[i] == i + 4)
4140 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4141 // We have 3 elements (undefs count as elements from any vector) from one
4142 // vector, and one from another.
4149 // Some special combinations that can be optimized.
4152 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4153 SelectionDAG &DAG) {
4154 MVT VT = SVOp->getSimpleValueType(0);
4157 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4160 ArrayRef<int> Mask = SVOp->getMask();
4162 // These are the special masks that may be optimized.
4163 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4164 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4165 bool MatchEvenMask = true;
4166 bool MatchOddMask = true;
4167 for (int i=0; i<8; ++i) {
4168 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4169 MatchEvenMask = false;
4170 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4171 MatchOddMask = false;
4174 if (!MatchEvenMask && !MatchOddMask)
4177 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4179 SDValue Op0 = SVOp->getOperand(0);
4180 SDValue Op1 = SVOp->getOperand(1);
4182 if (MatchEvenMask) {
4183 // Shift the second operand right to 32 bits.
4184 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4185 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4187 // Shift the first operand left to 32 bits.
4188 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4189 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4191 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4192 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4195 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4196 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4197 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4198 bool HasInt256, bool V2IsSplat = false) {
4200 assert(VT.getSizeInBits() >= 128 &&
4201 "Unsupported vector type for unpckl");
4203 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4205 unsigned NumOf256BitLanes;
4206 unsigned NumElts = VT.getVectorNumElements();
4207 if (VT.is256BitVector()) {
4208 if (NumElts != 4 && NumElts != 8 &&
4209 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4212 NumOf256BitLanes = 1;
4213 } else if (VT.is512BitVector()) {
4214 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4215 "Unsupported vector type for unpckh");
4217 NumOf256BitLanes = 2;
4220 NumOf256BitLanes = 1;
4223 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4224 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4226 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4227 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4228 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4229 int BitI = Mask[l256*NumEltsInStride+l+i];
4230 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4231 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4233 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4235 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4243 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4244 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4245 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4246 bool HasInt256, bool V2IsSplat = false) {
4247 assert(VT.getSizeInBits() >= 128 &&
4248 "Unsupported vector type for unpckh");
4250 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4252 unsigned NumOf256BitLanes;
4253 unsigned NumElts = VT.getVectorNumElements();
4254 if (VT.is256BitVector()) {
4255 if (NumElts != 4 && NumElts != 8 &&
4256 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4259 NumOf256BitLanes = 1;
4260 } else if (VT.is512BitVector()) {
4261 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4262 "Unsupported vector type for unpckh");
4264 NumOf256BitLanes = 2;
4267 NumOf256BitLanes = 1;
4270 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4271 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4273 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4274 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4275 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4276 int BitI = Mask[l256*NumEltsInStride+l+i];
4277 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4278 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4280 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4282 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4290 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4291 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4293 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4294 unsigned NumElts = VT.getVectorNumElements();
4295 bool Is256BitVec = VT.is256BitVector();
4297 if (VT.is512BitVector())
4299 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4300 "Unsupported vector type for unpckh");
4302 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4303 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4306 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4307 // FIXME: Need a better way to get rid of this, there's no latency difference
4308 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4309 // the former later. We should also remove the "_undef" special mask.
4310 if (NumElts == 4 && Is256BitVec)
4313 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4314 // independently on 128-bit lanes.
4315 unsigned NumLanes = VT.getSizeInBits()/128;
4316 unsigned NumLaneElts = NumElts/NumLanes;
4318 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4319 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4320 int BitI = Mask[l+i];
4321 int BitI1 = Mask[l+i+1];
4323 if (!isUndefOrEqual(BitI, j))
4325 if (!isUndefOrEqual(BitI1, j))
4333 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4334 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4336 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4337 unsigned NumElts = VT.getVectorNumElements();
4339 if (VT.is512BitVector())
4342 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4343 "Unsupported vector type for unpckh");
4345 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4346 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4349 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4350 // independently on 128-bit lanes.
4351 unsigned NumLanes = VT.getSizeInBits()/128;
4352 unsigned NumLaneElts = NumElts/NumLanes;
4354 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4355 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4356 int BitI = Mask[l+i];
4357 int BitI1 = Mask[l+i+1];
4358 if (!isUndefOrEqual(BitI, j))
4360 if (!isUndefOrEqual(BitI1, j))
4367 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4368 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4369 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4370 if (!VT.is512BitVector())
4373 unsigned NumElts = VT.getVectorNumElements();
4374 unsigned HalfSize = NumElts/2;
4375 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4376 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4381 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4382 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4390 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4391 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4392 /// MOVSD, and MOVD, i.e. setting the lowest element.
4393 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4394 if (VT.getVectorElementType().getSizeInBits() < 32)
4396 if (!VT.is128BitVector())
4399 unsigned NumElts = VT.getVectorNumElements();
4401 if (!isUndefOrEqual(Mask[0], NumElts))
4404 for (unsigned i = 1; i != NumElts; ++i)
4405 if (!isUndefOrEqual(Mask[i], i))
4411 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4412 /// as permutations between 128-bit chunks or halves. As an example: this
4414 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4415 /// The first half comes from the second half of V1 and the second half from the
4416 /// the second half of V2.
4417 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4418 if (!HasFp256 || !VT.is256BitVector())
4421 // The shuffle result is divided into half A and half B. In total the two
4422 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4423 // B must come from C, D, E or F.
4424 unsigned HalfSize = VT.getVectorNumElements()/2;
4425 bool MatchA = false, MatchB = false;
4427 // Check if A comes from one of C, D, E, F.
4428 for (unsigned Half = 0; Half != 4; ++Half) {
4429 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4435 // Check if B comes from one of C, D, E, F.
4436 for (unsigned Half = 0; Half != 4; ++Half) {
4437 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4443 return MatchA && MatchB;
4446 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4447 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4448 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4449 MVT VT = SVOp->getSimpleValueType(0);
4451 unsigned HalfSize = VT.getVectorNumElements()/2;
4453 unsigned FstHalf = 0, SndHalf = 0;
4454 for (unsigned i = 0; i < HalfSize; ++i) {
4455 if (SVOp->getMaskElt(i) > 0) {
4456 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4460 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4461 if (SVOp->getMaskElt(i) > 0) {
4462 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4467 return (FstHalf | (SndHalf << 4));
4470 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4471 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4472 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4476 unsigned NumElts = VT.getVectorNumElements();
4478 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4479 for (unsigned i = 0; i != NumElts; ++i) {
4482 Imm8 |= Mask[i] << (i*2);
4487 unsigned LaneSize = 4;
4488 SmallVector<int, 4> MaskVal(LaneSize, -1);
4490 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4491 for (unsigned i = 0; i != LaneSize; ++i) {
4492 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4496 if (MaskVal[i] < 0) {
4497 MaskVal[i] = Mask[i+l] - l;
4498 Imm8 |= MaskVal[i] << (i*2);
4501 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4508 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4509 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4510 /// Note that VPERMIL mask matching is different depending whether theunderlying
4511 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4512 /// to the same elements of the low, but to the higher half of the source.
4513 /// In VPERMILPD the two lanes could be shuffled independently of each other
4514 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4515 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4516 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4517 if (VT.getSizeInBits() < 256 || EltSize < 32)
4519 bool symetricMaskRequired = (EltSize == 32);
4520 unsigned NumElts = VT.getVectorNumElements();
4522 unsigned NumLanes = VT.getSizeInBits()/128;
4523 unsigned LaneSize = NumElts/NumLanes;
4524 // 2 or 4 elements in one lane
4526 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4527 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4528 for (unsigned i = 0; i != LaneSize; ++i) {
4529 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4531 if (symetricMaskRequired) {
4532 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4533 ExpectedMaskVal[i] = Mask[i+l] - l;
4536 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4544 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4545 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4546 /// element of vector 2 and the other elements to come from vector 1 in order.
4547 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4548 bool V2IsSplat = false, bool V2IsUndef = false) {
4549 if (!VT.is128BitVector())
4552 unsigned NumOps = VT.getVectorNumElements();
4553 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4556 if (!isUndefOrEqual(Mask[0], 0))
4559 for (unsigned i = 1; i != NumOps; ++i)
4560 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4561 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4562 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4568 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4569 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4570 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4571 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4572 const X86Subtarget *Subtarget) {
4573 if (!Subtarget->hasSSE3())
4576 unsigned NumElems = VT.getVectorNumElements();
4578 if ((VT.is128BitVector() && NumElems != 4) ||
4579 (VT.is256BitVector() && NumElems != 8) ||
4580 (VT.is512BitVector() && NumElems != 16))
4583 // "i+1" is the value the indexed mask element must have
4584 for (unsigned i = 0; i != NumElems; i += 2)
4585 if (!isUndefOrEqual(Mask[i], i+1) ||
4586 !isUndefOrEqual(Mask[i+1], i+1))
4592 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4593 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4594 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4595 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4596 const X86Subtarget *Subtarget) {
4597 if (!Subtarget->hasSSE3())
4600 unsigned NumElems = VT.getVectorNumElements();
4602 if ((VT.is128BitVector() && NumElems != 4) ||
4603 (VT.is256BitVector() && NumElems != 8) ||
4604 (VT.is512BitVector() && NumElems != 16))
4607 // "i" is the value the indexed mask element must have
4608 for (unsigned i = 0; i != NumElems; i += 2)
4609 if (!isUndefOrEqual(Mask[i], i) ||
4610 !isUndefOrEqual(Mask[i+1], i))
4616 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4617 /// specifies a shuffle of elements that is suitable for input to 256-bit
4618 /// version of MOVDDUP.
4619 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4620 if (!HasFp256 || !VT.is256BitVector())
4623 unsigned NumElts = VT.getVectorNumElements();
4627 for (unsigned i = 0; i != NumElts/2; ++i)
4628 if (!isUndefOrEqual(Mask[i], 0))
4630 for (unsigned i = NumElts/2; i != NumElts; ++i)
4631 if (!isUndefOrEqual(Mask[i], NumElts/2))
4636 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4637 /// specifies a shuffle of elements that is suitable for input to 128-bit
4638 /// version of MOVDDUP.
4639 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4640 if (!VT.is128BitVector())
4643 unsigned e = VT.getVectorNumElements() / 2;
4644 for (unsigned i = 0; i != e; ++i)
4645 if (!isUndefOrEqual(Mask[i], i))
4647 for (unsigned i = 0; i != e; ++i)
4648 if (!isUndefOrEqual(Mask[e+i], i))
4653 /// isVEXTRACTIndex - Return true if the specified
4654 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4655 /// suitable for instruction that extract 128 or 256 bit vectors
4656 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4657 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4658 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4661 // The index should be aligned on a vecWidth-bit boundary.
4663 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4665 MVT VT = N->getSimpleValueType(0);
4666 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4667 bool Result = (Index * ElSize) % vecWidth == 0;
4672 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4673 /// operand specifies a subvector insert that is suitable for input to
4674 /// insertion of 128 or 256-bit subvectors
4675 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4676 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4677 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4679 // The index should be aligned on a vecWidth-bit boundary.
4681 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4683 MVT VT = N->getSimpleValueType(0);
4684 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4685 bool Result = (Index * ElSize) % vecWidth == 0;
4690 bool X86::isVINSERT128Index(SDNode *N) {
4691 return isVINSERTIndex(N, 128);
4694 bool X86::isVINSERT256Index(SDNode *N) {
4695 return isVINSERTIndex(N, 256);
4698 bool X86::isVEXTRACT128Index(SDNode *N) {
4699 return isVEXTRACTIndex(N, 128);
4702 bool X86::isVEXTRACT256Index(SDNode *N) {
4703 return isVEXTRACTIndex(N, 256);
4706 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4707 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4708 /// Handles 128-bit and 256-bit.
4709 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4710 MVT VT = N->getSimpleValueType(0);
4712 assert((VT.getSizeInBits() >= 128) &&
4713 "Unsupported vector type for PSHUF/SHUFP");
4715 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4716 // independently on 128-bit lanes.
4717 unsigned NumElts = VT.getVectorNumElements();
4718 unsigned NumLanes = VT.getSizeInBits()/128;
4719 unsigned NumLaneElts = NumElts/NumLanes;
4721 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4722 "Only supports 2, 4 or 8 elements per lane");
4724 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4726 for (unsigned i = 0; i != NumElts; ++i) {
4727 int Elt = N->getMaskElt(i);
4728 if (Elt < 0) continue;
4729 Elt &= NumLaneElts - 1;
4730 unsigned ShAmt = (i << Shift) % 8;
4731 Mask |= Elt << ShAmt;
4737 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4738 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4739 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4740 MVT VT = N->getSimpleValueType(0);
4742 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4743 "Unsupported vector type for PSHUFHW");
4745 unsigned NumElts = VT.getVectorNumElements();
4748 for (unsigned l = 0; l != NumElts; l += 8) {
4749 // 8 nodes per lane, but we only care about the last 4.
4750 for (unsigned i = 0; i < 4; ++i) {
4751 int Elt = N->getMaskElt(l+i+4);
4752 if (Elt < 0) continue;
4753 Elt &= 0x3; // only 2-bits.
4754 Mask |= Elt << (i * 2);
4761 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4762 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4763 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4764 MVT VT = N->getSimpleValueType(0);
4766 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4767 "Unsupported vector type for PSHUFHW");
4769 unsigned NumElts = VT.getVectorNumElements();
4772 for (unsigned l = 0; l != NumElts; l += 8) {
4773 // 8 nodes per lane, but we only care about the first 4.
4774 for (unsigned i = 0; i < 4; ++i) {
4775 int Elt = N->getMaskElt(l+i);
4776 if (Elt < 0) continue;
4777 Elt &= 0x3; // only 2-bits
4778 Mask |= Elt << (i * 2);
4785 /// \brief Return the appropriate immediate to shuffle the specified
4786 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4787 /// VALIGN (if Interlane is true) instructions.
4788 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4790 MVT VT = SVOp->getSimpleValueType(0);
4791 unsigned EltSize = InterLane ? 1 :
4792 VT.getVectorElementType().getSizeInBits() >> 3;
4794 unsigned NumElts = VT.getVectorNumElements();
4795 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4796 unsigned NumLaneElts = NumElts/NumLanes;
4800 for (i = 0; i != NumElts; ++i) {
4801 Val = SVOp->getMaskElt(i);
4805 if (Val >= (int)NumElts)
4806 Val -= NumElts - NumLaneElts;
4808 assert(Val - i > 0 && "PALIGNR imm should be positive");
4809 return (Val - i) * EltSize;
4812 /// \brief Return the appropriate immediate to shuffle the specified
4813 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4814 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4815 return getShuffleAlignrImmediate(SVOp, false);
4818 /// \brief Return the appropriate immediate to shuffle the specified
4819 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4820 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4821 return getShuffleAlignrImmediate(SVOp, true);
4825 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4826 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4827 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4828 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4831 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4833 MVT VecVT = N->getOperand(0).getSimpleValueType();
4834 MVT ElVT = VecVT.getVectorElementType();
4836 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4837 return Index / NumElemsPerChunk;
4840 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4841 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4842 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4843 llvm_unreachable("Illegal insert subvector for VINSERT");
4846 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4848 MVT VecVT = N->getSimpleValueType(0);
4849 MVT ElVT = VecVT.getVectorElementType();
4851 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4852 return Index / NumElemsPerChunk;
4855 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4856 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4857 /// and VINSERTI128 instructions.
4858 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4859 return getExtractVEXTRACTImmediate(N, 128);
4862 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4863 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4864 /// and VINSERTI64x4 instructions.
4865 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4866 return getExtractVEXTRACTImmediate(N, 256);
4869 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4870 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4871 /// and VINSERTI128 instructions.
4872 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4873 return getInsertVINSERTImmediate(N, 128);
4876 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4877 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4878 /// and VINSERTI64x4 instructions.
4879 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4880 return getInsertVINSERTImmediate(N, 256);
4883 /// isZero - Returns true if Elt is a constant integer zero
4884 static bool isZero(SDValue V) {
4885 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4886 return C && C->isNullValue();
4889 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4891 bool X86::isZeroNode(SDValue Elt) {
4894 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4895 return CFP->getValueAPF().isPosZero();
4899 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4900 /// match movhlps. The lower half elements should come from upper half of
4901 /// V1 (and in order), and the upper half elements should come from the upper
4902 /// half of V2 (and in order).
4903 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4904 if (!VT.is128BitVector())
4906 if (VT.getVectorNumElements() != 4)
4908 for (unsigned i = 0, e = 2; i != e; ++i)
4909 if (!isUndefOrEqual(Mask[i], i+2))
4911 for (unsigned i = 2; i != 4; ++i)
4912 if (!isUndefOrEqual(Mask[i], i+4))
4917 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4918 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4920 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4921 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4923 N = N->getOperand(0).getNode();
4924 if (!ISD::isNON_EXTLoad(N))
4927 *LD = cast<LoadSDNode>(N);
4931 // Test whether the given value is a vector value which will be legalized
4933 static bool WillBeConstantPoolLoad(SDNode *N) {
4934 if (N->getOpcode() != ISD::BUILD_VECTOR)
4937 // Check for any non-constant elements.
4938 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4939 switch (N->getOperand(i).getNode()->getOpcode()) {
4941 case ISD::ConstantFP:
4948 // Vectors of all-zeros and all-ones are materialized with special
4949 // instructions rather than being loaded.
4950 return !ISD::isBuildVectorAllZeros(N) &&
4951 !ISD::isBuildVectorAllOnes(N);
4954 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4955 /// match movlp{s|d}. The lower half elements should come from lower half of
4956 /// V1 (and in order), and the upper half elements should come from the upper
4957 /// half of V2 (and in order). And since V1 will become the source of the
4958 /// MOVLP, it must be either a vector load or a scalar load to vector.
4959 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4960 ArrayRef<int> Mask, MVT VT) {
4961 if (!VT.is128BitVector())
4964 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4966 // Is V2 is a vector load, don't do this transformation. We will try to use
4967 // load folding shufps op.
4968 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4971 unsigned NumElems = VT.getVectorNumElements();
4973 if (NumElems != 2 && NumElems != 4)
4975 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4976 if (!isUndefOrEqual(Mask[i], i))
4978 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4979 if (!isUndefOrEqual(Mask[i], i+NumElems))
4984 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4985 /// to an zero vector.
4986 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4987 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4988 SDValue V1 = N->getOperand(0);
4989 SDValue V2 = N->getOperand(1);
4990 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4991 for (unsigned i = 0; i != NumElems; ++i) {
4992 int Idx = N->getMaskElt(i);
4993 if (Idx >= (int)NumElems) {
4994 unsigned Opc = V2.getOpcode();
4995 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4997 if (Opc != ISD::BUILD_VECTOR ||
4998 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5000 } else if (Idx >= 0) {
5001 unsigned Opc = V1.getOpcode();
5002 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5004 if (Opc != ISD::BUILD_VECTOR ||
5005 !X86::isZeroNode(V1.getOperand(Idx)))
5012 /// getZeroVector - Returns a vector of specified type with all zero elements.
5014 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5015 SelectionDAG &DAG, SDLoc dl) {
5016 assert(VT.isVector() && "Expected a vector type");
5018 // Always build SSE zero vectors as <4 x i32> bitcasted
5019 // to their dest type. This ensures they get CSE'd.
5021 if (VT.is128BitVector()) { // SSE
5022 if (Subtarget->hasSSE2()) { // SSE2
5023 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5024 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5026 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5027 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5029 } else if (VT.is256BitVector()) { // AVX
5030 if (Subtarget->hasInt256()) { // AVX2
5031 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5032 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5033 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5035 // 256-bit logic and arithmetic instructions in AVX are all
5036 // floating-point, no support for integer ops. Emit fp zeroed vectors.
5037 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5038 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5039 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5041 } else if (VT.is512BitVector()) { // AVX-512
5042 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5043 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5044 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5045 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5046 } else if (VT.getScalarType() == MVT::i1) {
5047 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5048 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5049 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5050 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5052 llvm_unreachable("Unexpected vector type");
5054 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5057 /// getOnesVector - Returns a vector of specified type with all bits set.
5058 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5059 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5060 /// Then bitcast to their original type, ensuring they get CSE'd.
5061 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5063 assert(VT.isVector() && "Expected a vector type");
5065 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5067 if (VT.is256BitVector()) {
5068 if (HasInt256) { // AVX2
5069 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5070 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5072 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5073 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5075 } else if (VT.is128BitVector()) {
5076 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5078 llvm_unreachable("Unexpected vector type");
5080 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5083 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5084 /// that point to V2 points to its first element.
5085 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5086 for (unsigned i = 0; i != NumElems; ++i) {
5087 if (Mask[i] > (int)NumElems) {
5093 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5094 /// operation of specified width.
5095 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5097 unsigned NumElems = VT.getVectorNumElements();
5098 SmallVector<int, 8> Mask;
5099 Mask.push_back(NumElems);
5100 for (unsigned i = 1; i != NumElems; ++i)
5102 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5105 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5106 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5108 unsigned NumElems = VT.getVectorNumElements();
5109 SmallVector<int, 8> Mask;
5110 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5112 Mask.push_back(i + NumElems);
5114 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5117 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5118 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5120 unsigned NumElems = VT.getVectorNumElements();
5121 SmallVector<int, 8> Mask;
5122 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5123 Mask.push_back(i + Half);
5124 Mask.push_back(i + NumElems + Half);
5126 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5129 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5130 // a generic shuffle instruction because the target has no such instructions.
5131 // Generate shuffles which repeat i16 and i8 several times until they can be
5132 // represented by v4f32 and then be manipulated by target suported shuffles.
5133 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5134 MVT VT = V.getSimpleValueType();
5135 int NumElems = VT.getVectorNumElements();
5138 while (NumElems > 4) {
5139 if (EltNo < NumElems/2) {
5140 V = getUnpackl(DAG, dl, VT, V, V);
5142 V = getUnpackh(DAG, dl, VT, V, V);
5143 EltNo -= NumElems/2;
5150 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5151 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5152 MVT VT = V.getSimpleValueType();
5155 if (VT.is128BitVector()) {
5156 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5157 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5158 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5160 } else if (VT.is256BitVector()) {
5161 // To use VPERMILPS to splat scalars, the second half of indicies must
5162 // refer to the higher part, which is a duplication of the lower one,
5163 // because VPERMILPS can only handle in-lane permutations.
5164 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5165 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5167 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5168 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5171 llvm_unreachable("Vector size not supported");
5173 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5176 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5177 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5178 MVT SrcVT = SV->getSimpleValueType(0);
5179 SDValue V1 = SV->getOperand(0);
5182 int EltNo = SV->getSplatIndex();
5183 int NumElems = SrcVT.getVectorNumElements();
5184 bool Is256BitVec = SrcVT.is256BitVector();
5186 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5187 "Unknown how to promote splat for type");
5189 // Extract the 128-bit part containing the splat element and update
5190 // the splat element index when it refers to the higher register.
5192 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5193 if (EltNo >= NumElems/2)
5194 EltNo -= NumElems/2;
5197 // All i16 and i8 vector types can't be used directly by a generic shuffle
5198 // instruction because the target has no such instruction. Generate shuffles
5199 // which repeat i16 and i8 several times until they fit in i32, and then can
5200 // be manipulated by target suported shuffles.
5201 MVT EltVT = SrcVT.getVectorElementType();
5202 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5203 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5205 // Recreate the 256-bit vector and place the same 128-bit vector
5206 // into the low and high part. This is necessary because we want
5207 // to use VPERM* to shuffle the vectors
5209 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5212 return getLegalSplat(DAG, V1, EltNo);
5215 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5216 /// vector of zero or undef vector. This produces a shuffle where the low
5217 /// element of V2 is swizzled into the zero/undef vector, landing at element
5218 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5219 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5221 const X86Subtarget *Subtarget,
5222 SelectionDAG &DAG) {
5223 MVT VT = V2.getSimpleValueType();
5225 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5226 unsigned NumElems = VT.getVectorNumElements();
5227 SmallVector<int, 16> MaskVec;
5228 for (unsigned i = 0; i != NumElems; ++i)
5229 // If this is the insertion idx, put the low elt of V2 here.
5230 MaskVec.push_back(i == Idx ? NumElems : i);
5231 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5234 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5235 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5236 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5237 /// shuffles which use a single input multiple times, and in those cases it will
5238 /// adjust the mask to only have indices within that single input.
5239 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5240 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5241 unsigned NumElems = VT.getVectorNumElements();
5245 bool IsFakeUnary = false;
5246 switch(N->getOpcode()) {
5248 ImmN = N->getOperand(N->getNumOperands()-1);
5249 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5250 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5252 case X86ISD::UNPCKH:
5253 DecodeUNPCKHMask(VT, Mask);
5254 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5256 case X86ISD::UNPCKL:
5257 DecodeUNPCKLMask(VT, Mask);
5258 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5260 case X86ISD::MOVHLPS:
5261 DecodeMOVHLPSMask(NumElems, Mask);
5262 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5264 case X86ISD::MOVLHPS:
5265 DecodeMOVLHPSMask(NumElems, Mask);
5266 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5268 case X86ISD::PALIGNR:
5269 ImmN = N->getOperand(N->getNumOperands()-1);
5270 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5272 case X86ISD::PSHUFD:
5273 case X86ISD::VPERMILP:
5274 ImmN = N->getOperand(N->getNumOperands()-1);
5275 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5278 case X86ISD::PSHUFHW:
5279 ImmN = N->getOperand(N->getNumOperands()-1);
5280 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5283 case X86ISD::PSHUFLW:
5284 ImmN = N->getOperand(N->getNumOperands()-1);
5285 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5288 case X86ISD::PSHUFB: {
5290 SDValue MaskNode = N->getOperand(1);
5291 while (MaskNode->getOpcode() == ISD::BITCAST)
5292 MaskNode = MaskNode->getOperand(0);
5294 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5295 // If we have a build-vector, then things are easy.
5296 EVT VT = MaskNode.getValueType();
5297 assert(VT.isVector() &&
5298 "Can't produce a non-vector with a build_vector!");
5299 if (!VT.isInteger())
5302 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5304 SmallVector<uint64_t, 32> RawMask;
5305 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5306 auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5309 APInt MaskElement = CN->getAPIntValue();
5311 // We now have to decode the element which could be any integer size and
5312 // extract each byte of it.
5313 for (int j = 0; j < NumBytesPerElement; ++j) {
5314 // Note that this is x86 and so always little endian: the low byte is
5315 // the first byte of the mask.
5316 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5317 MaskElement = MaskElement.lshr(8);
5320 DecodePSHUFBMask(RawMask, Mask);
5324 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5328 SDValue Ptr = MaskLoad->getBasePtr();
5329 if (Ptr->getOpcode() == X86ISD::Wrapper)
5330 Ptr = Ptr->getOperand(0);
5332 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5333 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5336 if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5337 // FIXME: Support AVX-512 here.
5338 if (!C->getType()->isVectorTy() ||
5339 (C->getNumElements() != 16 && C->getNumElements() != 32))
5342 assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5343 DecodePSHUFBMask(C, Mask);
5349 case X86ISD::VPERMI:
5350 ImmN = N->getOperand(N->getNumOperands()-1);
5351 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5355 case X86ISD::MOVSD: {
5356 // The index 0 always comes from the first element of the second source,
5357 // this is why MOVSS and MOVSD are used in the first place. The other
5358 // elements come from the other positions of the first source vector
5359 Mask.push_back(NumElems);
5360 for (unsigned i = 1; i != NumElems; ++i) {
5365 case X86ISD::VPERM2X128:
5366 ImmN = N->getOperand(N->getNumOperands()-1);
5367 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5368 if (Mask.empty()) return false;
5370 case X86ISD::MOVDDUP:
5371 case X86ISD::MOVLHPD:
5372 case X86ISD::MOVLPD:
5373 case X86ISD::MOVLPS:
5374 case X86ISD::MOVSHDUP:
5375 case X86ISD::MOVSLDUP:
5376 // Not yet implemented
5378 default: llvm_unreachable("unknown target shuffle node");
5381 // If we have a fake unary shuffle, the shuffle mask is spread across two
5382 // inputs that are actually the same node. Re-map the mask to always point
5383 // into the first input.
5386 if (M >= (int)Mask.size())
5392 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5393 /// element of the result of the vector shuffle.
5394 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5397 return SDValue(); // Limit search depth.
5399 SDValue V = SDValue(N, 0);
5400 EVT VT = V.getValueType();
5401 unsigned Opcode = V.getOpcode();
5403 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5404 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5405 int Elt = SV->getMaskElt(Index);
5408 return DAG.getUNDEF(VT.getVectorElementType());
5410 unsigned NumElems = VT.getVectorNumElements();
5411 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5412 : SV->getOperand(1);
5413 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5416 // Recurse into target specific vector shuffles to find scalars.
5417 if (isTargetShuffle(Opcode)) {
5418 MVT ShufVT = V.getSimpleValueType();
5419 unsigned NumElems = ShufVT.getVectorNumElements();
5420 SmallVector<int, 16> ShuffleMask;
5423 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5426 int Elt = ShuffleMask[Index];
5428 return DAG.getUNDEF(ShufVT.getVectorElementType());
5430 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5432 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5436 // Actual nodes that may contain scalar elements
5437 if (Opcode == ISD::BITCAST) {
5438 V = V.getOperand(0);
5439 EVT SrcVT = V.getValueType();
5440 unsigned NumElems = VT.getVectorNumElements();
5442 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5446 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5447 return (Index == 0) ? V.getOperand(0)
5448 : DAG.getUNDEF(VT.getVectorElementType());
5450 if (V.getOpcode() == ISD::BUILD_VECTOR)
5451 return V.getOperand(Index);
5456 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5457 /// shuffle operation which come from a consecutively from a zero. The
5458 /// search can start in two different directions, from left or right.
5459 /// We count undefs as zeros until PreferredNum is reached.
5460 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5461 unsigned NumElems, bool ZerosFromLeft,
5463 unsigned PreferredNum = -1U) {
5464 unsigned NumZeros = 0;
5465 for (unsigned i = 0; i != NumElems; ++i) {
5466 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5467 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5471 if (X86::isZeroNode(Elt))
5473 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5474 NumZeros = std::min(NumZeros + 1, PreferredNum);
5482 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5483 /// correspond consecutively to elements from one of the vector operands,
5484 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5486 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5487 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5488 unsigned NumElems, unsigned &OpNum) {
5489 bool SeenV1 = false;
5490 bool SeenV2 = false;
5492 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5493 int Idx = SVOp->getMaskElt(i);
5494 // Ignore undef indicies
5498 if (Idx < (int)NumElems)
5503 // Only accept consecutive elements from the same vector
5504 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5508 OpNum = SeenV1 ? 0 : 1;
5512 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5513 /// logical left shift of a vector.
5514 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5515 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5517 SVOp->getSimpleValueType(0).getVectorNumElements();
5518 unsigned NumZeros = getNumOfConsecutiveZeros(
5519 SVOp, NumElems, false /* check zeros from right */, DAG,
5520 SVOp->getMaskElt(0));
5526 // Considering the elements in the mask that are not consecutive zeros,
5527 // check if they consecutively come from only one of the source vectors.
5529 // V1 = {X, A, B, C} 0
5531 // vector_shuffle V1, V2 <1, 2, 3, X>
5533 if (!isShuffleMaskConsecutive(SVOp,
5534 0, // Mask Start Index
5535 NumElems-NumZeros, // Mask End Index(exclusive)
5536 NumZeros, // Where to start looking in the src vector
5537 NumElems, // Number of elements in vector
5538 OpSrc)) // Which source operand ?
5543 ShVal = SVOp->getOperand(OpSrc);
5547 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5548 /// logical left shift of a vector.
5549 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5550 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5552 SVOp->getSimpleValueType(0).getVectorNumElements();
5553 unsigned NumZeros = getNumOfConsecutiveZeros(
5554 SVOp, NumElems, true /* check zeros from left */, DAG,
5555 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5561 // Considering the elements in the mask that are not consecutive zeros,
5562 // check if they consecutively come from only one of the source vectors.
5564 // 0 { A, B, X, X } = V2
5566 // vector_shuffle V1, V2 <X, X, 4, 5>
5568 if (!isShuffleMaskConsecutive(SVOp,
5569 NumZeros, // Mask Start Index
5570 NumElems, // Mask End Index(exclusive)
5571 0, // Where to start looking in the src vector
5572 NumElems, // Number of elements in vector
5573 OpSrc)) // Which source operand ?
5578 ShVal = SVOp->getOperand(OpSrc);
5582 /// isVectorShift - Returns true if the shuffle can be implemented as a
5583 /// logical left or right shift of a vector.
5584 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5585 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5586 // Although the logic below support any bitwidth size, there are no
5587 // shift instructions which handle more than 128-bit vectors.
5588 if (!SVOp->getSimpleValueType(0).is128BitVector())
5591 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5592 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5598 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5600 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5601 unsigned NumNonZero, unsigned NumZero,
5603 const X86Subtarget* Subtarget,
5604 const TargetLowering &TLI) {
5611 for (unsigned i = 0; i < 16; ++i) {
5612 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5613 if (ThisIsNonZero && First) {
5615 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5617 V = DAG.getUNDEF(MVT::v8i16);
5622 SDValue ThisElt, LastElt;
5623 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5624 if (LastIsNonZero) {
5625 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5626 MVT::i16, Op.getOperand(i-1));
5628 if (ThisIsNonZero) {
5629 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5630 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5631 ThisElt, DAG.getConstant(8, MVT::i8));
5633 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5637 if (ThisElt.getNode())
5638 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5639 DAG.getIntPtrConstant(i/2));
5643 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5646 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5648 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5649 unsigned NumNonZero, unsigned NumZero,
5651 const X86Subtarget* Subtarget,
5652 const TargetLowering &TLI) {
5659 for (unsigned i = 0; i < 8; ++i) {
5660 bool isNonZero = (NonZeros & (1 << i)) != 0;
5664 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5666 V = DAG.getUNDEF(MVT::v8i16);
5669 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5670 MVT::v8i16, V, Op.getOperand(i),
5671 DAG.getIntPtrConstant(i));
5678 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5679 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5680 unsigned NonZeros, unsigned NumNonZero,
5681 unsigned NumZero, SelectionDAG &DAG,
5682 const X86Subtarget *Subtarget,
5683 const TargetLowering &TLI) {
5684 // We know there's at least one non-zero element
5685 unsigned FirstNonZeroIdx = 0;
5686 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5687 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5688 X86::isZeroNode(FirstNonZero)) {
5690 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5693 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5694 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5697 SDValue V = FirstNonZero.getOperand(0);
5698 MVT VVT = V.getSimpleValueType();
5699 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5702 unsigned FirstNonZeroDst =
5703 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5704 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5705 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5706 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5708 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5709 SDValue Elem = Op.getOperand(Idx);
5710 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5713 // TODO: What else can be here? Deal with it.
5714 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5717 // TODO: Some optimizations are still possible here
5718 // ex: Getting one element from a vector, and the rest from another.
5719 if (Elem.getOperand(0) != V)
5722 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5725 else if (IncorrectIdx == -1U) {
5729 // There was already one element with an incorrect index.
5730 // We can't optimize this case to an insertps.
5734 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5736 EVT VT = Op.getSimpleValueType();
5737 unsigned ElementMoveMask = 0;
5738 if (IncorrectIdx == -1U)
5739 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5741 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5743 SDValue InsertpsMask =
5744 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5745 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5751 /// getVShift - Return a vector logical shift node.
5753 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5754 unsigned NumBits, SelectionDAG &DAG,
5755 const TargetLowering &TLI, SDLoc dl) {
5756 assert(VT.is128BitVector() && "Unknown type for VShift");
5757 EVT ShVT = MVT::v2i64;
5758 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5759 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5760 return DAG.getNode(ISD::BITCAST, dl, VT,
5761 DAG.getNode(Opc, dl, ShVT, SrcOp,
5762 DAG.getConstant(NumBits,
5763 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5767 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5769 // Check if the scalar load can be widened into a vector load. And if
5770 // the address is "base + cst" see if the cst can be "absorbed" into
5771 // the shuffle mask.
5772 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5773 SDValue Ptr = LD->getBasePtr();
5774 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5776 EVT PVT = LD->getValueType(0);
5777 if (PVT != MVT::i32 && PVT != MVT::f32)
5782 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5783 FI = FINode->getIndex();
5785 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5786 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5787 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5788 Offset = Ptr.getConstantOperandVal(1);
5789 Ptr = Ptr.getOperand(0);
5794 // FIXME: 256-bit vector instructions don't require a strict alignment,
5795 // improve this code to support it better.
5796 unsigned RequiredAlign = VT.getSizeInBits()/8;
5797 SDValue Chain = LD->getChain();
5798 // Make sure the stack object alignment is at least 16 or 32.
5799 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5800 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5801 if (MFI->isFixedObjectIndex(FI)) {
5802 // Can't change the alignment. FIXME: It's possible to compute
5803 // the exact stack offset and reference FI + adjust offset instead.
5804 // If someone *really* cares about this. That's the way to implement it.
5807 MFI->setObjectAlignment(FI, RequiredAlign);
5811 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5812 // Ptr + (Offset & ~15).
5815 if ((Offset % RequiredAlign) & 3)
5817 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5819 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5820 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5822 int EltNo = (Offset - StartOffset) >> 2;
5823 unsigned NumElems = VT.getVectorNumElements();
5825 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5826 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5827 LD->getPointerInfo().getWithOffset(StartOffset),
5828 false, false, false, 0);
5830 SmallVector<int, 8> Mask;
5831 for (unsigned i = 0; i != NumElems; ++i)
5832 Mask.push_back(EltNo);
5834 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5840 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5841 /// vector of type 'VT', see if the elements can be replaced by a single large
5842 /// load which has the same value as a build_vector whose operands are 'elts'.
5844 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5846 /// FIXME: we'd also like to handle the case where the last elements are zero
5847 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5848 /// There's even a handy isZeroNode for that purpose.
5849 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5850 SDLoc &DL, SelectionDAG &DAG,
5851 bool isAfterLegalize) {
5852 EVT EltVT = VT.getVectorElementType();
5853 unsigned NumElems = Elts.size();
5855 LoadSDNode *LDBase = nullptr;
5856 unsigned LastLoadedElt = -1U;
5858 // For each element in the initializer, see if we've found a load or an undef.
5859 // If we don't find an initial load element, or later load elements are
5860 // non-consecutive, bail out.
5861 for (unsigned i = 0; i < NumElems; ++i) {
5862 SDValue Elt = Elts[i];
5864 if (!Elt.getNode() ||
5865 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5868 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5870 LDBase = cast<LoadSDNode>(Elt.getNode());
5874 if (Elt.getOpcode() == ISD::UNDEF)
5877 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5878 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5883 // If we have found an entire vector of loads and undefs, then return a large
5884 // load of the entire vector width starting at the base pointer. If we found
5885 // consecutive loads for the low half, generate a vzext_load node.
5886 if (LastLoadedElt == NumElems - 1) {
5888 if (isAfterLegalize &&
5889 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5892 SDValue NewLd = SDValue();
5894 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5895 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5896 LDBase->getPointerInfo(),
5897 LDBase->isVolatile(), LDBase->isNonTemporal(),
5898 LDBase->isInvariant(), 0);
5899 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5900 LDBase->getPointerInfo(),
5901 LDBase->isVolatile(), LDBase->isNonTemporal(),
5902 LDBase->isInvariant(), LDBase->getAlignment());
5904 if (LDBase->hasAnyUseOfValue(1)) {
5905 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5907 SDValue(NewLd.getNode(), 1));
5908 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5909 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5910 SDValue(NewLd.getNode(), 1));
5915 if (NumElems == 4 && LastLoadedElt == 1 &&
5916 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5917 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5918 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5920 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5921 LDBase->getPointerInfo(),
5922 LDBase->getAlignment(),
5923 false/*isVolatile*/, true/*ReadMem*/,
5926 // Make sure the newly-created LOAD is in the same position as LDBase in
5927 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5928 // update uses of LDBase's output chain to use the TokenFactor.
5929 if (LDBase->hasAnyUseOfValue(1)) {
5930 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5931 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5932 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5933 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5934 SDValue(ResNode.getNode(), 1));
5937 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5942 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5943 /// to generate a splat value for the following cases:
5944 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5945 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5946 /// a scalar load, or a constant.
5947 /// The VBROADCAST node is returned when a pattern is found,
5948 /// or SDValue() otherwise.
5949 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5950 SelectionDAG &DAG) {
5951 if (!Subtarget->hasFp256())
5954 MVT VT = Op.getSimpleValueType();
5957 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5958 "Unsupported vector type for broadcast.");
5963 switch (Op.getOpcode()) {
5965 // Unknown pattern found.
5968 case ISD::BUILD_VECTOR: {
5969 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5970 BitVector UndefElements;
5971 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5973 // We need a splat of a single value to use broadcast, and it doesn't
5974 // make any sense if the value is only in one element of the vector.
5975 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5979 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5980 Ld.getOpcode() == ISD::ConstantFP);
5982 // Make sure that all of the users of a non-constant load are from the
5983 // BUILD_VECTOR node.
5984 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5989 case ISD::VECTOR_SHUFFLE: {
5990 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5992 // Shuffles must have a splat mask where the first element is
5994 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5997 SDValue Sc = Op.getOperand(0);
5998 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5999 Sc.getOpcode() != ISD::BUILD_VECTOR) {
6001 if (!Subtarget->hasInt256())
6004 // Use the register form of the broadcast instruction available on AVX2.
6005 if (VT.getSizeInBits() >= 256)
6006 Sc = Extract128BitVector(Sc, 0, DAG, dl);
6007 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6010 Ld = Sc.getOperand(0);
6011 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6012 Ld.getOpcode() == ISD::ConstantFP);
6014 // The scalar_to_vector node and the suspected
6015 // load node must have exactly one user.
6016 // Constants may have multiple users.
6018 // AVX-512 has register version of the broadcast
6019 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6020 Ld.getValueType().getSizeInBits() >= 32;
6021 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6028 bool IsGE256 = (VT.getSizeInBits() >= 256);
6030 // Handle the broadcasting a single constant scalar from the constant pool
6031 // into a vector. On Sandybridge it is still better to load a constant vector
6032 // from the constant pool and not to broadcast it from a scalar.
6033 if (ConstSplatVal && Subtarget->hasInt256()) {
6034 EVT CVT = Ld.getValueType();
6035 assert(!CVT.isVector() && "Must not broadcast a vector type");
6036 unsigned ScalarSize = CVT.getSizeInBits();
6038 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
6039 const Constant *C = nullptr;
6040 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6041 C = CI->getConstantIntValue();
6042 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6043 C = CF->getConstantFPValue();
6045 assert(C && "Invalid constant type");
6047 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6048 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6049 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6050 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6051 MachinePointerInfo::getConstantPool(),
6052 false, false, false, Alignment);
6054 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6058 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6059 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6061 // Handle AVX2 in-register broadcasts.
6062 if (!IsLoad && Subtarget->hasInt256() &&
6063 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6064 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6066 // The scalar source must be a normal load.
6070 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6071 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6073 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6074 // double since there is no vbroadcastsd xmm
6075 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6076 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6077 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6080 // Unsupported broadcast.
6084 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6085 /// underlying vector and index.
6087 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6089 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6091 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6092 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6095 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6097 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6099 // (extract_vector_elt (vector_shuffle<2,u,u,u>
6100 // (extract_subvector (v8f32 %vreg0), Constant<4>),
6103 // In this case the vector is the extract_subvector expression and the index
6104 // is 2, as specified by the shuffle.
6105 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6106 SDValue ShuffleVec = SVOp->getOperand(0);
6107 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6108 assert(ShuffleVecVT.getVectorElementType() ==
6109 ExtractedFromVec.getSimpleValueType().getVectorElementType());
6111 int ShuffleIdx = SVOp->getMaskElt(Idx);
6112 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6113 ExtractedFromVec = ShuffleVec;
6119 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6120 MVT VT = Op.getSimpleValueType();
6122 // Skip if insert_vec_elt is not supported.
6123 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6124 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6128 unsigned NumElems = Op.getNumOperands();
6132 SmallVector<unsigned, 4> InsertIndices;
6133 SmallVector<int, 8> Mask(NumElems, -1);
6135 for (unsigned i = 0; i != NumElems; ++i) {
6136 unsigned Opc = Op.getOperand(i).getOpcode();
6138 if (Opc == ISD::UNDEF)
6141 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6142 // Quit if more than 1 elements need inserting.
6143 if (InsertIndices.size() > 1)
6146 InsertIndices.push_back(i);
6150 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6151 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6152 // Quit if non-constant index.
6153 if (!isa<ConstantSDNode>(ExtIdx))
6155 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6157 // Quit if extracted from vector of different type.
6158 if (ExtractedFromVec.getValueType() != VT)
6161 if (!VecIn1.getNode())
6162 VecIn1 = ExtractedFromVec;
6163 else if (VecIn1 != ExtractedFromVec) {
6164 if (!VecIn2.getNode())
6165 VecIn2 = ExtractedFromVec;
6166 else if (VecIn2 != ExtractedFromVec)
6167 // Quit if more than 2 vectors to shuffle
6171 if (ExtractedFromVec == VecIn1)
6173 else if (ExtractedFromVec == VecIn2)
6174 Mask[i] = Idx + NumElems;
6177 if (!VecIn1.getNode())
6180 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6181 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6182 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6183 unsigned Idx = InsertIndices[i];
6184 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6185 DAG.getIntPtrConstant(Idx));
6191 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6193 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6195 MVT VT = Op.getSimpleValueType();
6196 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6197 "Unexpected type in LowerBUILD_VECTORvXi1!");
6200 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6201 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6202 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6203 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6206 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6207 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6208 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6209 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6212 bool AllContants = true;
6213 uint64_t Immediate = 0;
6214 int NonConstIdx = -1;
6215 bool IsSplat = true;
6216 unsigned NumNonConsts = 0;
6217 unsigned NumConsts = 0;
6218 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6219 SDValue In = Op.getOperand(idx);
6220 if (In.getOpcode() == ISD::UNDEF)
6222 if (!isa<ConstantSDNode>(In)) {
6223 AllContants = false;
6229 if (cast<ConstantSDNode>(In)->getZExtValue())
6230 Immediate |= (1ULL << idx);
6232 if (In != Op.getOperand(0))
6237 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6238 DAG.getConstant(Immediate, MVT::i16));
6239 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6240 DAG.getIntPtrConstant(0));
6243 if (NumNonConsts == 1 && NonConstIdx != 0) {
6246 SDValue VecAsImm = DAG.getConstant(Immediate,
6247 MVT::getIntegerVT(VT.getSizeInBits()));
6248 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6251 DstVec = DAG.getUNDEF(VT);
6252 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6253 Op.getOperand(NonConstIdx),
6254 DAG.getIntPtrConstant(NonConstIdx));
6256 if (!IsSplat && (NonConstIdx != 0))
6257 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6258 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6261 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6262 DAG.getConstant(-1, SelectVT),
6263 DAG.getConstant(0, SelectVT));
6265 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6266 DAG.getConstant((Immediate | 1), SelectVT),
6267 DAG.getConstant(Immediate, SelectVT));
6268 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6271 /// \brief Return true if \p N implements a horizontal binop and return the
6272 /// operands for the horizontal binop into V0 and V1.
6274 /// This is a helper function of PerformBUILD_VECTORCombine.
6275 /// This function checks that the build_vector \p N in input implements a
6276 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6277 /// operation to match.
6278 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6279 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6280 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6283 /// This function only analyzes elements of \p N whose indices are
6284 /// in range [BaseIdx, LastIdx).
6285 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6287 unsigned BaseIdx, unsigned LastIdx,
6288 SDValue &V0, SDValue &V1) {
6289 EVT VT = N->getValueType(0);
6291 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6292 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6293 "Invalid Vector in input!");
6295 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6296 bool CanFold = true;
6297 unsigned ExpectedVExtractIdx = BaseIdx;
6298 unsigned NumElts = LastIdx - BaseIdx;
6299 V0 = DAG.getUNDEF(VT);
6300 V1 = DAG.getUNDEF(VT);
6302 // Check if N implements a horizontal binop.
6303 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6304 SDValue Op = N->getOperand(i + BaseIdx);
6307 if (Op->getOpcode() == ISD::UNDEF) {
6308 // Update the expected vector extract index.
6309 if (i * 2 == NumElts)
6310 ExpectedVExtractIdx = BaseIdx;
6311 ExpectedVExtractIdx += 2;
6315 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6320 SDValue Op0 = Op.getOperand(0);
6321 SDValue Op1 = Op.getOperand(1);
6323 // Try to match the following pattern:
6324 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6325 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6326 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6327 Op0.getOperand(0) == Op1.getOperand(0) &&
6328 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6329 isa<ConstantSDNode>(Op1.getOperand(1)));
6333 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6334 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6336 if (i * 2 < NumElts) {
6337 if (V0.getOpcode() == ISD::UNDEF)
6338 V0 = Op0.getOperand(0);
6340 if (V1.getOpcode() == ISD::UNDEF)
6341 V1 = Op0.getOperand(0);
6342 if (i * 2 == NumElts)
6343 ExpectedVExtractIdx = BaseIdx;
6346 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6347 if (I0 == ExpectedVExtractIdx)
6348 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6349 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6350 // Try to match the following dag sequence:
6351 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6352 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6356 ExpectedVExtractIdx += 2;
6362 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6363 /// a concat_vector.
6365 /// This is a helper function of PerformBUILD_VECTORCombine.
6366 /// This function expects two 256-bit vectors called V0 and V1.
6367 /// At first, each vector is split into two separate 128-bit vectors.
6368 /// Then, the resulting 128-bit vectors are used to implement two
6369 /// horizontal binary operations.
6371 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6373 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6374 /// the two new horizontal binop.
6375 /// When Mode is set, the first horizontal binop dag node would take as input
6376 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6377 /// horizontal binop dag node would take as input the lower 128-bit of V1
6378 /// and the upper 128-bit of V1.
6380 /// HADD V0_LO, V0_HI
6381 /// HADD V1_LO, V1_HI
6383 /// Otherwise, the first horizontal binop dag node takes as input the lower
6384 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6385 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6387 /// HADD V0_LO, V1_LO
6388 /// HADD V0_HI, V1_HI
6390 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6391 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6392 /// the upper 128-bits of the result.
6393 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6394 SDLoc DL, SelectionDAG &DAG,
6395 unsigned X86Opcode, bool Mode,
6396 bool isUndefLO, bool isUndefHI) {
6397 EVT VT = V0.getValueType();
6398 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6399 "Invalid nodes in input!");
6401 unsigned NumElts = VT.getVectorNumElements();
6402 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6403 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6404 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6405 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6406 EVT NewVT = V0_LO.getValueType();
6408 SDValue LO = DAG.getUNDEF(NewVT);
6409 SDValue HI = DAG.getUNDEF(NewVT);
6412 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6413 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6414 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6415 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6416 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6418 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6419 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6420 V1_LO->getOpcode() != ISD::UNDEF))
6421 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6423 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6424 V1_HI->getOpcode() != ISD::UNDEF))
6425 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6428 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6431 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6432 /// sequence of 'vadd + vsub + blendi'.
6433 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6434 const X86Subtarget *Subtarget) {
6436 EVT VT = BV->getValueType(0);
6437 unsigned NumElts = VT.getVectorNumElements();
6438 SDValue InVec0 = DAG.getUNDEF(VT);
6439 SDValue InVec1 = DAG.getUNDEF(VT);
6441 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6442 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6444 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6445 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6446 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6449 // Odd-numbered elements in the input build vector are obtained from
6450 // adding two integer/float elements.
6451 // Even-numbered elements in the input build vector are obtained from
6452 // subtracting two integer/float elements.
6453 unsigned ExpectedOpcode = ISD::FSUB;
6454 unsigned NextExpectedOpcode = ISD::FADD;
6455 bool AddFound = false;
6456 bool SubFound = false;
6458 for (unsigned i = 0, e = NumElts; i != e; i++) {
6459 SDValue Op = BV->getOperand(i);
6461 // Skip 'undef' values.
6462 unsigned Opcode = Op.getOpcode();
6463 if (Opcode == ISD::UNDEF) {
6464 std::swap(ExpectedOpcode, NextExpectedOpcode);
6468 // Early exit if we found an unexpected opcode.
6469 if (Opcode != ExpectedOpcode)
6472 SDValue Op0 = Op.getOperand(0);
6473 SDValue Op1 = Op.getOperand(1);
6475 // Try to match the following pattern:
6476 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6477 // Early exit if we cannot match that sequence.
6478 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6479 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6480 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6481 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6482 Op0.getOperand(1) != Op1.getOperand(1))
6485 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6489 // We found a valid add/sub node. Update the information accordingly.
6495 // Update InVec0 and InVec1.
6496 if (InVec0.getOpcode() == ISD::UNDEF)
6497 InVec0 = Op0.getOperand(0);
6498 if (InVec1.getOpcode() == ISD::UNDEF)
6499 InVec1 = Op1.getOperand(0);
6501 // Make sure that operands in input to each add/sub node always
6502 // come from a same pair of vectors.
6503 if (InVec0 != Op0.getOperand(0)) {
6504 if (ExpectedOpcode == ISD::FSUB)
6507 // FADD is commutable. Try to commute the operands
6508 // and then test again.
6509 std::swap(Op0, Op1);
6510 if (InVec0 != Op0.getOperand(0))
6514 if (InVec1 != Op1.getOperand(0))
6517 // Update the pair of expected opcodes.
6518 std::swap(ExpectedOpcode, NextExpectedOpcode);
6521 // Don't try to fold this build_vector into a VSELECT if it has
6522 // too many UNDEF operands.
6523 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6524 InVec1.getOpcode() != ISD::UNDEF) {
6525 // Emit a sequence of vector add and sub followed by a VSELECT.
6526 // The new VSELECT will be lowered into a BLENDI.
6527 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6528 // and emit a single ADDSUB instruction.
6529 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6530 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6532 // Construct the VSELECT mask.
6533 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6534 EVT SVT = MaskVT.getVectorElementType();
6535 unsigned SVTBits = SVT.getSizeInBits();
6536 SmallVector<SDValue, 8> Ops;
6538 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6539 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6540 APInt::getAllOnesValue(SVTBits);
6541 SDValue Constant = DAG.getConstant(Value, SVT);
6542 Ops.push_back(Constant);
6545 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6546 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6552 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6553 const X86Subtarget *Subtarget) {
6555 EVT VT = N->getValueType(0);
6556 unsigned NumElts = VT.getVectorNumElements();
6557 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6558 SDValue InVec0, InVec1;
6560 // Try to match an ADDSUB.
6561 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6562 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6563 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6564 if (Value.getNode())
6568 // Try to match horizontal ADD/SUB.
6569 unsigned NumUndefsLO = 0;
6570 unsigned NumUndefsHI = 0;
6571 unsigned Half = NumElts/2;
6573 // Count the number of UNDEF operands in the build_vector in input.
6574 for (unsigned i = 0, e = Half; i != e; ++i)
6575 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6578 for (unsigned i = Half, e = NumElts; i != e; ++i)
6579 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6582 // Early exit if this is either a build_vector of all UNDEFs or all the
6583 // operands but one are UNDEF.
6584 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6587 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6588 // Try to match an SSE3 float HADD/HSUB.
6589 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6590 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6592 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6593 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6594 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6595 // Try to match an SSSE3 integer HADD/HSUB.
6596 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6597 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6599 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6600 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6603 if (!Subtarget->hasAVX())
6606 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6607 // Try to match an AVX horizontal add/sub of packed single/double
6608 // precision floating point values from 256-bit vectors.
6609 SDValue InVec2, InVec3;
6610 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6611 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6612 ((InVec0.getOpcode() == ISD::UNDEF ||
6613 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6614 ((InVec1.getOpcode() == ISD::UNDEF ||
6615 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6616 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6618 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6619 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6620 ((InVec0.getOpcode() == ISD::UNDEF ||
6621 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6622 ((InVec1.getOpcode() == ISD::UNDEF ||
6623 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6624 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6625 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6626 // Try to match an AVX2 horizontal add/sub of signed integers.
6627 SDValue InVec2, InVec3;
6629 bool CanFold = true;
6631 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6632 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6633 ((InVec0.getOpcode() == ISD::UNDEF ||
6634 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6635 ((InVec1.getOpcode() == ISD::UNDEF ||
6636 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6637 X86Opcode = X86ISD::HADD;
6638 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6639 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6640 ((InVec0.getOpcode() == ISD::UNDEF ||
6641 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6642 ((InVec1.getOpcode() == ISD::UNDEF ||
6643 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6644 X86Opcode = X86ISD::HSUB;
6649 // Fold this build_vector into a single horizontal add/sub.
6650 // Do this only if the target has AVX2.
6651 if (Subtarget->hasAVX2())
6652 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6654 // Do not try to expand this build_vector into a pair of horizontal
6655 // add/sub if we can emit a pair of scalar add/sub.
6656 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6659 // Convert this build_vector into a pair of horizontal binop followed by
6661 bool isUndefLO = NumUndefsLO == Half;
6662 bool isUndefHI = NumUndefsHI == Half;
6663 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6664 isUndefLO, isUndefHI);
6668 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6669 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6671 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6672 X86Opcode = X86ISD::HADD;
6673 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6674 X86Opcode = X86ISD::HSUB;
6675 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6676 X86Opcode = X86ISD::FHADD;
6677 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6678 X86Opcode = X86ISD::FHSUB;
6682 // Don't try to expand this build_vector into a pair of horizontal add/sub
6683 // if we can simply emit a pair of scalar add/sub.
6684 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6687 // Convert this build_vector into two horizontal add/sub followed by
6689 bool isUndefLO = NumUndefsLO == Half;
6690 bool isUndefHI = NumUndefsHI == Half;
6691 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6692 isUndefLO, isUndefHI);
6699 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6702 MVT VT = Op.getSimpleValueType();
6703 MVT ExtVT = VT.getVectorElementType();
6704 unsigned NumElems = Op.getNumOperands();
6706 // Generate vectors for predicate vectors.
6707 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6708 return LowerBUILD_VECTORvXi1(Op, DAG);
6710 // Vectors containing all zeros can be matched by pxor and xorps later
6711 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6712 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6713 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6714 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6717 return getZeroVector(VT, Subtarget, DAG, dl);
6720 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6721 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6722 // vpcmpeqd on 256-bit vectors.
6723 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6724 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6727 if (!VT.is512BitVector())
6728 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6731 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6732 if (Broadcast.getNode())
6735 unsigned EVTBits = ExtVT.getSizeInBits();
6737 unsigned NumZero = 0;
6738 unsigned NumNonZero = 0;
6739 unsigned NonZeros = 0;
6740 bool IsAllConstants = true;
6741 SmallSet<SDValue, 8> Values;
6742 for (unsigned i = 0; i < NumElems; ++i) {
6743 SDValue Elt = Op.getOperand(i);
6744 if (Elt.getOpcode() == ISD::UNDEF)
6747 if (Elt.getOpcode() != ISD::Constant &&
6748 Elt.getOpcode() != ISD::ConstantFP)
6749 IsAllConstants = false;
6750 if (X86::isZeroNode(Elt))
6753 NonZeros |= (1 << i);
6758 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6759 if (NumNonZero == 0)
6760 return DAG.getUNDEF(VT);
6762 // Special case for single non-zero, non-undef, element.
6763 if (NumNonZero == 1) {
6764 unsigned Idx = countTrailingZeros(NonZeros);
6765 SDValue Item = Op.getOperand(Idx);
6767 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6768 // the value are obviously zero, truncate the value to i32 and do the
6769 // insertion that way. Only do this if the value is non-constant or if the
6770 // value is a constant being inserted into element 0. It is cheaper to do
6771 // a constant pool load than it is to do a movd + shuffle.
6772 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6773 (!IsAllConstants || Idx == 0)) {
6774 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6776 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6777 EVT VecVT = MVT::v4i32;
6778 unsigned VecElts = 4;
6780 // Truncate the value (which may itself be a constant) to i32, and
6781 // convert it to a vector with movd (S2V+shuffle to zero extend).
6782 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6783 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6784 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6786 // Now we have our 32-bit value zero extended in the low element of
6787 // a vector. If Idx != 0, swizzle it into place.
6789 SmallVector<int, 4> Mask;
6790 Mask.push_back(Idx);
6791 for (unsigned i = 1; i != VecElts; ++i)
6793 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6796 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6800 // If we have a constant or non-constant insertion into the low element of
6801 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6802 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6803 // depending on what the source datatype is.
6806 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6808 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6809 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6810 if (VT.is256BitVector() || VT.is512BitVector()) {
6811 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6812 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6813 Item, DAG.getIntPtrConstant(0));
6815 assert(VT.is128BitVector() && "Expected an SSE value type!");
6816 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6817 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6818 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6821 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6822 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6823 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6824 if (VT.is256BitVector()) {
6825 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6826 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6828 assert(VT.is128BitVector() && "Expected an SSE value type!");
6829 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6831 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6835 // Is it a vector logical left shift?
6836 if (NumElems == 2 && Idx == 1 &&
6837 X86::isZeroNode(Op.getOperand(0)) &&
6838 !X86::isZeroNode(Op.getOperand(1))) {
6839 unsigned NumBits = VT.getSizeInBits();
6840 return getVShift(true, VT,
6841 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6842 VT, Op.getOperand(1)),
6843 NumBits/2, DAG, *this, dl);
6846 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6849 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6850 // is a non-constant being inserted into an element other than the low one,
6851 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6852 // movd/movss) to move this into the low element, then shuffle it into
6854 if (EVTBits == 32) {
6855 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6857 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6858 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6859 SmallVector<int, 8> MaskVec;
6860 for (unsigned i = 0; i != NumElems; ++i)
6861 MaskVec.push_back(i == Idx ? 0 : 1);
6862 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6866 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6867 if (Values.size() == 1) {
6868 if (EVTBits == 32) {
6869 // Instead of a shuffle like this:
6870 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6871 // Check if it's possible to issue this instead.
6872 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6873 unsigned Idx = countTrailingZeros(NonZeros);
6874 SDValue Item = Op.getOperand(Idx);
6875 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6876 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6881 // A vector full of immediates; various special cases are already
6882 // handled, so this is best done with a single constant-pool load.
6886 // For AVX-length vectors, build the individual 128-bit pieces and use
6887 // shuffles to put them in place.
6888 if (VT.is256BitVector() || VT.is512BitVector()) {
6889 SmallVector<SDValue, 64> V;
6890 for (unsigned i = 0; i != NumElems; ++i)
6891 V.push_back(Op.getOperand(i));
6893 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6895 // Build both the lower and upper subvector.
6896 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6897 makeArrayRef(&V[0], NumElems/2));
6898 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6899 makeArrayRef(&V[NumElems / 2], NumElems/2));
6901 // Recreate the wider vector with the lower and upper part.
6902 if (VT.is256BitVector())
6903 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6904 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6907 // Let legalizer expand 2-wide build_vectors.
6908 if (EVTBits == 64) {
6909 if (NumNonZero == 1) {
6910 // One half is zero or undef.
6911 unsigned Idx = countTrailingZeros(NonZeros);
6912 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6913 Op.getOperand(Idx));
6914 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6919 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6920 if (EVTBits == 8 && NumElems == 16) {
6921 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6923 if (V.getNode()) return V;
6926 if (EVTBits == 16 && NumElems == 8) {
6927 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6929 if (V.getNode()) return V;
6932 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6933 if (EVTBits == 32 && NumElems == 4) {
6934 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6935 NumZero, DAG, Subtarget, *this);
6940 // If element VT is == 32 bits, turn it into a number of shuffles.
6941 SmallVector<SDValue, 8> V(NumElems);
6942 if (NumElems == 4 && NumZero > 0) {
6943 for (unsigned i = 0; i < 4; ++i) {
6944 bool isZero = !(NonZeros & (1 << i));
6946 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6948 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6951 for (unsigned i = 0; i < 2; ++i) {
6952 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6955 V[i] = V[i*2]; // Must be a zero vector.
6958 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6961 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6964 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6969 bool Reverse1 = (NonZeros & 0x3) == 2;
6970 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6974 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6975 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6977 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6980 if (Values.size() > 1 && VT.is128BitVector()) {
6981 // Check for a build vector of consecutive loads.
6982 for (unsigned i = 0; i < NumElems; ++i)
6983 V[i] = Op.getOperand(i);
6985 // Check for elements which are consecutive loads.
6986 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6990 // Check for a build vector from mostly shuffle plus few inserting.
6991 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6995 // For SSE 4.1, use insertps to put the high elements into the low element.
6996 if (getSubtarget()->hasSSE41()) {
6998 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6999 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7001 Result = DAG.getUNDEF(VT);
7003 for (unsigned i = 1; i < NumElems; ++i) {
7004 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7005 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7006 Op.getOperand(i), DAG.getIntPtrConstant(i));
7011 // Otherwise, expand into a number of unpckl*, start by extending each of
7012 // our (non-undef) elements to the full vector width with the element in the
7013 // bottom slot of the vector (which generates no code for SSE).
7014 for (unsigned i = 0; i < NumElems; ++i) {
7015 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7016 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7018 V[i] = DAG.getUNDEF(VT);
7021 // Next, we iteratively mix elements, e.g. for v4f32:
7022 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7023 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7024 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
7025 unsigned EltStride = NumElems >> 1;
7026 while (EltStride != 0) {
7027 for (unsigned i = 0; i < EltStride; ++i) {
7028 // If V[i+EltStride] is undef and this is the first round of mixing,
7029 // then it is safe to just drop this shuffle: V[i] is already in the
7030 // right place, the one element (since it's the first round) being
7031 // inserted as undef can be dropped. This isn't safe for successive
7032 // rounds because they will permute elements within both vectors.
7033 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7034 EltStride == NumElems/2)
7037 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7046 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7047 // to create 256-bit vectors from two other 128-bit ones.
7048 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7050 MVT ResVT = Op.getSimpleValueType();
7052 assert((ResVT.is256BitVector() ||
7053 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7055 SDValue V1 = Op.getOperand(0);
7056 SDValue V2 = Op.getOperand(1);
7057 unsigned NumElems = ResVT.getVectorNumElements();
7058 if(ResVT.is256BitVector())
7059 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7061 if (Op.getNumOperands() == 4) {
7062 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7063 ResVT.getVectorNumElements()/2);
7064 SDValue V3 = Op.getOperand(2);
7065 SDValue V4 = Op.getOperand(3);
7066 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7067 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7069 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7072 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7073 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7074 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7075 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7076 Op.getNumOperands() == 4)));
7078 // AVX can use the vinsertf128 instruction to create 256-bit vectors
7079 // from two other 128-bit ones.
7081 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7082 return LowerAVXCONCAT_VECTORS(Op, DAG);
7086 //===----------------------------------------------------------------------===//
7087 // Vector shuffle lowering
7089 // This is an experimental code path for lowering vector shuffles on x86. It is
7090 // designed to handle arbitrary vector shuffles and blends, gracefully
7091 // degrading performance as necessary. It works hard to recognize idiomatic
7092 // shuffles and lower them to optimal instruction patterns without leaving
7093 // a framework that allows reasonably efficient handling of all vector shuffle
7095 //===----------------------------------------------------------------------===//
7097 /// \brief Tiny helper function to identify a no-op mask.
7099 /// This is a somewhat boring predicate function. It checks whether the mask
7100 /// array input, which is assumed to be a single-input shuffle mask of the kind
7101 /// used by the X86 shuffle instructions (not a fully general
7102 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7103 /// in-place shuffle are 'no-op's.
7104 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7105 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7106 if (Mask[i] != -1 && Mask[i] != i)
7111 /// \brief Helper function to classify a mask as a single-input mask.
7113 /// This isn't a generic single-input test because in the vector shuffle
7114 /// lowering we canonicalize single inputs to be the first input operand. This
7115 /// means we can more quickly test for a single input by only checking whether
7116 /// an input from the second operand exists. We also assume that the size of
7117 /// mask corresponds to the size of the input vectors which isn't true in the
7118 /// fully general case.
7119 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7121 if (M >= (int)Mask.size())
7126 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7127 // 2013 will allow us to use it as a non-type template parameter.
7130 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7132 /// See its documentation for details.
7133 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7134 if (Mask.size() != Args.size())
7136 for (int i = 0, e = Mask.size(); i < e; ++i) {
7137 assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7138 assert(*Args[i] < (int)Args.size() * 2 &&
7139 "Argument outside the range of possible shuffle inputs!");
7140 if (Mask[i] != -1 && Mask[i] != *Args[i])
7148 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7151 /// This is a fast way to test a shuffle mask against a fixed pattern:
7153 /// if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7155 /// It returns true if the mask is exactly as wide as the argument list, and
7156 /// each element of the mask is either -1 (signifying undef) or the value given
7157 /// in the argument.
7158 static const VariadicFunction1<
7159 bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7161 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7163 /// This helper function produces an 8-bit shuffle immediate corresponding to
7164 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7165 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7168 /// NB: We rely heavily on "undef" masks preserving the input lane.
7169 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7170 SelectionDAG &DAG) {
7171 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7172 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7173 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7174 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7175 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7178 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7179 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7180 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7181 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7182 return DAG.getConstant(Imm, MVT::i8);
7185 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7187 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7188 /// support for floating point shuffles but not integer shuffles. These
7189 /// instructions will incur a domain crossing penalty on some chips though so
7190 /// it is better to avoid lowering through this for integer vectors where
7192 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7193 const X86Subtarget *Subtarget,
7194 SelectionDAG &DAG) {
7196 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7197 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7198 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7199 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7200 ArrayRef<int> Mask = SVOp->getMask();
7201 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7203 if (isSingleInputShuffleMask(Mask)) {
7204 // Straight shuffle of a single input vector. Simulate this by using the
7205 // single input as both of the "inputs" to this instruction..
7206 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7207 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7208 DAG.getConstant(SHUFPDMask, MVT::i8));
7210 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7211 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7213 // Use dedicated unpack instructions for masks that match their pattern.
7214 if (isShuffleEquivalent(Mask, 0, 2))
7215 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7216 if (isShuffleEquivalent(Mask, 1, 3))
7217 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7219 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7220 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7221 DAG.getConstant(SHUFPDMask, MVT::i8));
7224 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7226 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7227 /// the integer unit to minimize domain crossing penalties. However, for blends
7228 /// it falls back to the floating point shuffle operation with appropriate bit
7230 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7231 const X86Subtarget *Subtarget,
7232 SelectionDAG &DAG) {
7234 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7235 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7236 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7237 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7238 ArrayRef<int> Mask = SVOp->getMask();
7239 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7241 if (isSingleInputShuffleMask(Mask)) {
7242 // Straight shuffle of a single input vector. For everything from SSE2
7243 // onward this has a single fast instruction with no scary immediates.
7244 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7245 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7246 int WidenedMask[4] = {
7247 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7248 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7250 ISD::BITCAST, DL, MVT::v2i64,
7251 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7252 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7255 // Use dedicated unpack instructions for masks that match their pattern.
7256 if (isShuffleEquivalent(Mask, 0, 2))
7257 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7258 if (isShuffleEquivalent(Mask, 1, 3))
7259 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7261 // We implement this with SHUFPD which is pretty lame because it will likely
7262 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7263 // However, all the alternatives are still more cycles and newer chips don't
7264 // have this problem. It would be really nice if x86 had better shuffles here.
7265 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7266 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7267 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7268 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7271 /// \brief Lower 4-lane 32-bit floating point shuffles.
7273 /// Uses instructions exclusively from the floating point unit to minimize
7274 /// domain crossing penalties, as these are sufficient to implement all v4f32
7276 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7277 const X86Subtarget *Subtarget,
7278 SelectionDAG &DAG) {
7280 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7281 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7282 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7283 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7284 ArrayRef<int> Mask = SVOp->getMask();
7285 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7287 SDValue LowV = V1, HighV = V2;
7288 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7291 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7293 if (NumV2Elements == 0)
7294 // Straight shuffle of a single input vector. We pass the input vector to
7295 // both operands to simulate this with a SHUFPS.
7296 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7297 getV4X86ShuffleImm8ForMask(Mask, DAG));
7299 // Use dedicated unpack instructions for masks that match their pattern.
7300 if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7301 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7302 if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7303 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7305 if (NumV2Elements == 1) {
7307 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7309 // Compute the index adjacent to V2Index and in the same half by toggling
7311 int V2AdjIndex = V2Index ^ 1;
7313 if (Mask[V2AdjIndex] == -1) {
7314 // Handles all the cases where we have a single V2 element and an undef.
7315 // This will only ever happen in the high lanes because we commute the
7316 // vector otherwise.
7318 std::swap(LowV, HighV);
7319 NewMask[V2Index] -= 4;
7321 // Handle the case where the V2 element ends up adjacent to a V1 element.
7322 // To make this work, blend them together as the first step.
7323 int V1Index = V2AdjIndex;
7324 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7325 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7326 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7328 // Now proceed to reconstruct the final blend as we have the necessary
7329 // high or low half formed.
7336 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7337 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7339 } else if (NumV2Elements == 2) {
7340 if (Mask[0] < 4 && Mask[1] < 4) {
7341 // Handle the easy case where we have V1 in the low lanes and V2 in the
7342 // high lanes. We never see this reversed because we sort the shuffle.
7346 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7347 // trying to place elements directly, just blend them and set up the final
7348 // shuffle to place them.
7350 // The first two blend mask elements are for V1, the second two are for
7352 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7353 Mask[2] < 4 ? Mask[2] : Mask[3],
7354 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7355 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7356 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7357 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7359 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7362 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7363 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7364 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7365 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7368 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7369 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7372 /// \brief Lower 4-lane i32 vector shuffles.
7374 /// We try to handle these with integer-domain shuffles where we can, but for
7375 /// blends we use the floating point domain blend instructions.
7376 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7377 const X86Subtarget *Subtarget,
7378 SelectionDAG &DAG) {
7380 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7381 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7382 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7383 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7384 ArrayRef<int> Mask = SVOp->getMask();
7385 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7387 if (isSingleInputShuffleMask(Mask))
7388 // Straight shuffle of a single input vector. For everything from SSE2
7389 // onward this has a single fast instruction with no scary immediates.
7390 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7391 getV4X86ShuffleImm8ForMask(Mask, DAG));
7393 // Use dedicated unpack instructions for masks that match their pattern.
7394 if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7395 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7396 if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7397 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7399 // We implement this with SHUFPS because it can blend from two vectors.
7400 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7401 // up the inputs, bypassing domain shift penalties that we would encur if we
7402 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7404 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7405 DAG.getVectorShuffle(
7407 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7408 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7411 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7412 /// shuffle lowering, and the most complex part.
7414 /// The lowering strategy is to try to form pairs of input lanes which are
7415 /// targeted at the same half of the final vector, and then use a dword shuffle
7416 /// to place them onto the right half, and finally unpack the paired lanes into
7417 /// their final position.
7419 /// The exact breakdown of how to form these dword pairs and align them on the
7420 /// correct sides is really tricky. See the comments within the function for
7421 /// more of the details.
7422 static SDValue lowerV8I16SingleInputVectorShuffle(
7423 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7424 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7425 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7426 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7427 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7429 SmallVector<int, 4> LoInputs;
7430 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7431 [](int M) { return M >= 0; });
7432 std::sort(LoInputs.begin(), LoInputs.end());
7433 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7434 SmallVector<int, 4> HiInputs;
7435 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7436 [](int M) { return M >= 0; });
7437 std::sort(HiInputs.begin(), HiInputs.end());
7438 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7440 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7441 int NumHToL = LoInputs.size() - NumLToL;
7443 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7444 int NumHToH = HiInputs.size() - NumLToH;
7445 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7446 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7447 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7448 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7450 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7451 // such inputs we can swap two of the dwords across the half mark and end up
7452 // with <=2 inputs to each half in each half. Once there, we can fall through
7453 // to the generic code below. For example:
7455 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7456 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7458 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7459 // and an existing 2-into-2 on the other half. In this case we may have to
7460 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7461 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7462 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7463 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7464 // half than the one we target for fixing) will be fixed when we re-enter this
7465 // path. We will also combine away any sequence of PSHUFD instructions that
7466 // result into a single instruction. Here is an example of the tricky case:
7468 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7469 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7471 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7473 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7474 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7476 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7477 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7479 // The result is fine to be handled by the generic logic.
7480 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7481 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7482 int AOffset, int BOffset) {
7483 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7484 "Must call this with A having 3 or 1 inputs from the A half.");
7485 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7486 "Must call this with B having 1 or 3 inputs from the B half.");
7487 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7488 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7490 // Compute the index of dword with only one word among the three inputs in
7491 // a half by taking the sum of the half with three inputs and subtracting
7492 // the sum of the actual three inputs. The difference is the remaining
7495 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7496 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7497 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7498 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7499 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7500 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7501 int TripleNonInputIdx =
7502 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7503 TripleDWord = TripleNonInputIdx / 2;
7505 // We use xor with one to compute the adjacent DWord to whichever one the
7507 OneInputDWord = (OneInput / 2) ^ 1;
7509 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7510 // and BToA inputs. If there is also such a problem with the BToB and AToB
7511 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7512 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7513 // is essential that we don't *create* a 3<-1 as then we might oscillate.
7514 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7515 // Compute how many inputs will be flipped by swapping these DWords. We
7517 // to balance this to ensure we don't form a 3-1 shuffle in the other
7519 int NumFlippedAToBInputs =
7520 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7521 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7522 int NumFlippedBToBInputs =
7523 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7524 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7525 if ((NumFlippedAToBInputs == 1 &&
7526 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7527 (NumFlippedBToBInputs == 1 &&
7528 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7529 // We choose whether to fix the A half or B half based on whether that
7530 // half has zero flipped inputs. At zero, we may not be able to fix it
7531 // with that half. We also bias towards fixing the B half because that
7532 // will more commonly be the high half, and we have to bias one way.
7533 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7534 ArrayRef<int> Inputs) {
7535 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7536 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7537 PinnedIdx ^ 1) != Inputs.end();
7538 // Determine whether the free index is in the flipped dword or the
7539 // unflipped dword based on where the pinned index is. We use this bit
7540 // in an xor to conditionally select the adjacent dword.
7541 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7542 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7543 FixFreeIdx) != Inputs.end();
7544 if (IsFixIdxInput == IsFixFreeIdxInput)
7546 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7547 FixFreeIdx) != Inputs.end();
7548 assert(IsFixIdxInput != IsFixFreeIdxInput &&
7549 "We need to be changing the number of flipped inputs!");
7550 int PSHUFHalfMask[] = {0, 1, 2, 3};
7551 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7552 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7554 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7557 if (M != -1 && M == FixIdx)
7559 else if (M != -1 && M == FixFreeIdx)
7562 if (NumFlippedBToBInputs != 0) {
7564 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7565 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7567 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7569 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7570 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7575 int PSHUFDMask[] = {0, 1, 2, 3};
7576 PSHUFDMask[ADWord] = BDWord;
7577 PSHUFDMask[BDWord] = ADWord;
7578 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7579 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7580 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7581 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7583 // Adjust the mask to match the new locations of A and B.
7585 if (M != -1 && M/2 == ADWord)
7586 M = 2 * BDWord + M % 2;
7587 else if (M != -1 && M/2 == BDWord)
7588 M = 2 * ADWord + M % 2;
7590 // Recurse back into this routine to re-compute state now that this isn't
7591 // a 3 and 1 problem.
7592 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7595 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7596 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7597 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7598 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7600 // At this point there are at most two inputs to the low and high halves from
7601 // each half. That means the inputs can always be grouped into dwords and
7602 // those dwords can then be moved to the correct half with a dword shuffle.
7603 // We use at most one low and one high word shuffle to collect these paired
7604 // inputs into dwords, and finally a dword shuffle to place them.
7605 int PSHUFLMask[4] = {-1, -1, -1, -1};
7606 int PSHUFHMask[4] = {-1, -1, -1, -1};
7607 int PSHUFDMask[4] = {-1, -1, -1, -1};
7609 // First fix the masks for all the inputs that are staying in their
7610 // original halves. This will then dictate the targets of the cross-half
7612 auto fixInPlaceInputs =
7613 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7614 MutableArrayRef<int> SourceHalfMask,
7615 MutableArrayRef<int> HalfMask, int HalfOffset) {
7616 if (InPlaceInputs.empty())
7618 if (InPlaceInputs.size() == 1) {
7619 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7620 InPlaceInputs[0] - HalfOffset;
7621 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7624 if (IncomingInputs.empty()) {
7625 // Just fix all of the in place inputs.
7626 for (int Input : InPlaceInputs) {
7627 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7628 PSHUFDMask[Input / 2] = Input / 2;
7633 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7634 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7635 InPlaceInputs[0] - HalfOffset;
7636 // Put the second input next to the first so that they are packed into
7637 // a dword. We find the adjacent index by toggling the low bit.
7638 int AdjIndex = InPlaceInputs[0] ^ 1;
7639 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7640 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7641 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7643 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7644 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7646 // Now gather the cross-half inputs and place them into a free dword of
7647 // their target half.
7648 // FIXME: This operation could almost certainly be simplified dramatically to
7649 // look more like the 3-1 fixing operation.
7650 auto moveInputsToRightHalf = [&PSHUFDMask](
7651 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7652 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7653 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7655 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7656 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7658 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7660 int LowWord = Word & ~1;
7661 int HighWord = Word | 1;
7662 return isWordClobbered(SourceHalfMask, LowWord) ||
7663 isWordClobbered(SourceHalfMask, HighWord);
7666 if (IncomingInputs.empty())
7669 if (ExistingInputs.empty()) {
7670 // Map any dwords with inputs from them into the right half.
7671 for (int Input : IncomingInputs) {
7672 // If the source half mask maps over the inputs, turn those into
7673 // swaps and use the swapped lane.
7674 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7675 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7676 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7677 Input - SourceOffset;
7678 // We have to swap the uses in our half mask in one sweep.
7679 for (int &M : HalfMask)
7680 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7682 else if (M == Input)
7683 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7685 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7686 Input - SourceOffset &&
7687 "Previous placement doesn't match!");
7689 // Note that this correctly re-maps both when we do a swap and when
7690 // we observe the other side of the swap above. We rely on that to
7691 // avoid swapping the members of the input list directly.
7692 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7695 // Map the input's dword into the correct half.
7696 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7697 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7699 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7701 "Previous placement doesn't match!");
7704 // And just directly shift any other-half mask elements to be same-half
7705 // as we will have mirrored the dword containing the element into the
7706 // same position within that half.
7707 for (int &M : HalfMask)
7708 if (M >= SourceOffset && M < SourceOffset + 4) {
7709 M = M - SourceOffset + DestOffset;
7710 assert(M >= 0 && "This should never wrap below zero!");
7715 // Ensure we have the input in a viable dword of its current half. This
7716 // is particularly tricky because the original position may be clobbered
7717 // by inputs being moved and *staying* in that half.
7718 if (IncomingInputs.size() == 1) {
7719 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7720 int InputFixed = std::find(std::begin(SourceHalfMask),
7721 std::end(SourceHalfMask), -1) -
7722 std::begin(SourceHalfMask) + SourceOffset;
7723 SourceHalfMask[InputFixed - SourceOffset] =
7724 IncomingInputs[0] - SourceOffset;
7725 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7727 IncomingInputs[0] = InputFixed;
7729 } else if (IncomingInputs.size() == 2) {
7730 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7731 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7732 // We have two non-adjacent or clobbered inputs we need to extract from
7733 // the source half. To do this, we need to map them into some adjacent
7734 // dword slot in the source mask.
7735 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7736 IncomingInputs[1] - SourceOffset};
7738 // If there is a free slot in the source half mask adjacent to one of
7739 // the inputs, place the other input in it. We use (Index XOR 1) to
7740 // compute an adjacent index.
7741 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7742 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7743 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7744 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7745 InputsFixed[1] = InputsFixed[0] ^ 1;
7746 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7747 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7748 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7749 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7750 InputsFixed[0] = InputsFixed[1] ^ 1;
7751 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7752 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7753 // The two inputs are in the same DWord but it is clobbered and the
7754 // adjacent DWord isn't used at all. Move both inputs to the free
7756 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7757 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
7758 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
7759 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
7761 // The only way we hit this point is if there is no clobbering
7762 // (because there are no off-half inputs to this half) and there is no
7763 // free slot adjacent to one of the inputs. In this case, we have to
7764 // swap an input with a non-input.
7765 for (int i = 0; i < 4; ++i)
7766 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
7767 "We can't handle any clobbers here!");
7768 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
7769 "Cannot have adjacent inputs here!");
7771 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7772 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
7774 // We also have to update the final source mask in this case because
7775 // it may need to undo the above swap.
7776 for (int &M : FinalSourceHalfMask)
7777 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
7778 M = InputsFixed[1] + SourceOffset;
7779 else if (M == InputsFixed[1] + SourceOffset)
7780 M = (InputsFixed[0] ^ 1) + SourceOffset;
7782 InputsFixed[1] = InputsFixed[0] ^ 1;
7785 // Point everything at the fixed inputs.
7786 for (int &M : HalfMask)
7787 if (M == IncomingInputs[0])
7788 M = InputsFixed[0] + SourceOffset;
7789 else if (M == IncomingInputs[1])
7790 M = InputsFixed[1] + SourceOffset;
7792 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
7793 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
7796 llvm_unreachable("Unhandled input size!");
7799 // Now hoist the DWord down to the right half.
7800 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7801 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7802 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7803 for (int &M : HalfMask)
7804 for (int Input : IncomingInputs)
7806 M = FreeDWord * 2 + Input % 2;
7808 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
7809 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7810 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
7811 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7813 // Now enact all the shuffles we've computed to move the inputs into their
7815 if (!isNoopShuffleMask(PSHUFLMask))
7816 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7817 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7818 if (!isNoopShuffleMask(PSHUFHMask))
7819 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7820 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7821 if (!isNoopShuffleMask(PSHUFDMask))
7822 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7823 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7824 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7825 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7827 // At this point, each half should contain all its inputs, and we can then
7828 // just shuffle them into their final position.
7829 assert(std::count_if(LoMask.begin(), LoMask.end(),
7830 [](int M) { return M >= 4; }) == 0 &&
7831 "Failed to lift all the high half inputs to the low mask!");
7832 assert(std::count_if(HiMask.begin(), HiMask.end(),
7833 [](int M) { return M >= 0 && M < 4; }) == 0 &&
7834 "Failed to lift all the low half inputs to the high mask!");
7836 // Do a half shuffle for the low mask.
7837 if (!isNoopShuffleMask(LoMask))
7838 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7839 getV4X86ShuffleImm8ForMask(LoMask, DAG));
7841 // Do a half shuffle with the high mask after shifting its values down.
7842 for (int &M : HiMask)
7845 if (!isNoopShuffleMask(HiMask))
7846 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7847 getV4X86ShuffleImm8ForMask(HiMask, DAG));
7852 /// \brief Detect whether the mask pattern should be lowered through
7855 /// This essentially tests whether viewing the mask as an interleaving of two
7856 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7857 /// lowering it through interleaving is a significantly better strategy.
7858 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7859 int NumEvenInputs[2] = {0, 0};
7860 int NumOddInputs[2] = {0, 0};
7861 int NumLoInputs[2] = {0, 0};
7862 int NumHiInputs[2] = {0, 0};
7863 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7867 int InputIdx = Mask[i] >= Size;
7870 ++NumLoInputs[InputIdx];
7872 ++NumHiInputs[InputIdx];
7875 ++NumEvenInputs[InputIdx];
7877 ++NumOddInputs[InputIdx];
7880 // The minimum number of cross-input results for both the interleaved and
7881 // split cases. If interleaving results in fewer cross-input results, return
7883 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7884 NumEvenInputs[0] + NumOddInputs[1]);
7885 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7886 NumLoInputs[0] + NumHiInputs[1]);
7887 return InterleavedCrosses < SplitCrosses;
7890 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7892 /// This strategy only works when the inputs from each vector fit into a single
7893 /// half of that vector, and generally there are not so many inputs as to leave
7894 /// the in-place shuffles required highly constrained (and thus expensive). It
7895 /// shifts all the inputs into a single side of both input vectors and then
7896 /// uses an unpack to interleave these inputs in a single vector. At that
7897 /// point, we will fall back on the generic single input shuffle lowering.
7898 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7900 MutableArrayRef<int> Mask,
7901 const X86Subtarget *Subtarget,
7902 SelectionDAG &DAG) {
7903 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7904 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7905 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7906 for (int i = 0; i < 8; ++i)
7907 if (Mask[i] >= 0 && Mask[i] < 4)
7908 LoV1Inputs.push_back(i);
7909 else if (Mask[i] >= 4 && Mask[i] < 8)
7910 HiV1Inputs.push_back(i);
7911 else if (Mask[i] >= 8 && Mask[i] < 12)
7912 LoV2Inputs.push_back(i);
7913 else if (Mask[i] >= 12)
7914 HiV2Inputs.push_back(i);
7916 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7917 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7920 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7921 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7922 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7924 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7925 HiV1Inputs.size() + HiV2Inputs.size();
7927 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7928 ArrayRef<int> HiInputs, bool MoveToLo,
7930 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7931 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7932 if (BadInputs.empty())
7935 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7936 int MoveOffset = MoveToLo ? 0 : 4;
7938 if (GoodInputs.empty()) {
7939 for (int BadInput : BadInputs) {
7940 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7941 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7944 if (GoodInputs.size() == 2) {
7945 // If the low inputs are spread across two dwords, pack them into
7947 MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
7948 MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
7949 Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
7950 Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
7952 // Otherwise pin the good inputs.
7953 for (int GoodInput : GoodInputs)
7954 MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7957 if (BadInputs.size() == 2) {
7958 // If we have two bad inputs then there may be either one or two good
7959 // inputs fixed in place. Find a fixed input, and then find the *other*
7960 // two adjacent indices by using modular arithmetic.
7962 std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
7963 [](int M) { return M >= 0; }) -
7964 std::begin(MoveMask);
7966 ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
7967 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7968 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7969 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7970 MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
7971 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7972 Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
7974 assert(BadInputs.size() == 1 && "All sizes handled");
7975 int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
7976 std::end(MoveMask), -1) -
7977 std::begin(MoveMask);
7978 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7979 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7983 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7986 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7988 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7991 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7992 // cross-half traffic in the final shuffle.
7994 // Munge the mask to be a single-input mask after the unpack merges the
7998 M = 2 * (M % 4) + (M / 8);
8000 return DAG.getVectorShuffle(
8001 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
8002 DL, MVT::v8i16, V1, V2),
8003 DAG.getUNDEF(MVT::v8i16), Mask);
8006 /// \brief Generic lowering of 8-lane i16 shuffles.
8008 /// This handles both single-input shuffles and combined shuffle/blends with
8009 /// two inputs. The single input shuffles are immediately delegated to
8010 /// a dedicated lowering routine.
8012 /// The blends are lowered in one of three fundamental ways. If there are few
8013 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8014 /// of the input is significantly cheaper when lowered as an interleaving of
8015 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8016 /// halves of the inputs separately (making them have relatively few inputs)
8017 /// and then concatenate them.
8018 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8019 const X86Subtarget *Subtarget,
8020 SelectionDAG &DAG) {
8022 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8023 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8024 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8025 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8026 ArrayRef<int> OrigMask = SVOp->getMask();
8027 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8028 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8029 MutableArrayRef<int> Mask(MaskStorage);
8031 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8033 auto isV1 = [](int M) { return M >= 0 && M < 8; };
8034 auto isV2 = [](int M) { return M >= 8; };
8036 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
8037 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8039 if (NumV2Inputs == 0)
8040 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
8042 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
8043 "to be V1-input shuffles.");
8045 if (NumV1Inputs + NumV2Inputs <= 4)
8046 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
8048 // Check whether an interleaving lowering is likely to be more efficient.
8049 // This isn't perfect but it is a strong heuristic that tends to work well on
8050 // the kinds of shuffles that show up in practice.
8052 // FIXME: Handle 1x, 2x, and 4x interleaving.
8053 if (shouldLowerAsInterleaving(Mask)) {
8054 // FIXME: Figure out whether we should pack these into the low or high
8057 int EMask[8], OMask[8];
8058 for (int i = 0; i < 4; ++i) {
8059 EMask[i] = Mask[2*i];
8060 OMask[i] = Mask[2*i + 1];
8065 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
8066 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
8068 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
8071 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8072 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8074 for (int i = 0; i < 4; ++i) {
8075 LoBlendMask[i] = Mask[i];
8076 HiBlendMask[i] = Mask[i + 4];
8079 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8080 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8081 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
8082 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
8084 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8085 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
8088 /// \brief Check whether a compaction lowering can be done by dropping even
8089 /// elements and compute how many times even elements must be dropped.
8091 /// This handles shuffles which take every Nth element where N is a power of
8092 /// two. Example shuffle masks:
8094 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8095 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8096 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8097 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8098 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8099 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8101 /// Any of these lanes can of course be undef.
8103 /// This routine only supports N <= 3.
8104 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8107 /// \returns N above, or the number of times even elements must be dropped if
8108 /// there is such a number. Otherwise returns zero.
8109 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8110 // Figure out whether we're looping over two inputs or just one.
8111 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8113 // The modulus for the shuffle vector entries is based on whether this is
8114 // a single input or not.
8115 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8116 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8117 "We should only be called with masks with a power-of-2 size!");
8119 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8121 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8122 // and 2^3 simultaneously. This is because we may have ambiguity with
8123 // partially undef inputs.
8124 bool ViableForN[3] = {true, true, true};
8126 for (int i = 0, e = Mask.size(); i < e; ++i) {
8127 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8132 bool IsAnyViable = false;
8133 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8134 if (ViableForN[j]) {
8137 // The shuffle mask must be equal to (i * 2^N) % M.
8138 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8141 ViableForN[j] = false;
8143 // Early exit if we exhaust the possible powers of two.
8148 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8152 // Return 0 as there is no viable power of two.
8156 /// \brief Generic lowering of v16i8 shuffles.
8158 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8159 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8160 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8161 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8163 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8164 const X86Subtarget *Subtarget,
8165 SelectionDAG &DAG) {
8167 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8168 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8169 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8170 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8171 ArrayRef<int> OrigMask = SVOp->getMask();
8172 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8173 int MaskStorage[16] = {
8174 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8175 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
8176 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
8177 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
8178 MutableArrayRef<int> Mask(MaskStorage);
8179 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
8180 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
8182 // For single-input shuffles, there are some nicer lowering tricks we can use.
8183 if (isSingleInputShuffleMask(Mask)) {
8184 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8185 // Notably, this handles splat and partial-splat shuffles more efficiently.
8186 // However, it only makes sense if the pre-duplication shuffle simplifies
8187 // things significantly. Currently, this means we need to be able to
8188 // express the pre-duplication shuffle as an i16 shuffle.
8190 // FIXME: We should check for other patterns which can be widened into an
8191 // i16 shuffle as well.
8192 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8193 for (int i = 0; i < 16; i += 2) {
8194 if (Mask[i] != Mask[i + 1])
8199 auto tryToWidenViaDuplication = [&]() -> SDValue {
8200 if (!canWidenViaDuplication(Mask))
8202 SmallVector<int, 4> LoInputs;
8203 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8204 [](int M) { return M >= 0 && M < 8; });
8205 std::sort(LoInputs.begin(), LoInputs.end());
8206 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8208 SmallVector<int, 4> HiInputs;
8209 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8210 [](int M) { return M >= 8; });
8211 std::sort(HiInputs.begin(), HiInputs.end());
8212 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8215 bool TargetLo = LoInputs.size() >= HiInputs.size();
8216 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8217 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8219 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8220 SmallDenseMap<int, int, 8> LaneMap;
8221 for (int I : InPlaceInputs) {
8222 PreDupI16Shuffle[I/2] = I/2;
8225 int j = TargetLo ? 0 : 4, je = j + 4;
8226 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8227 // Check if j is already a shuffle of this input. This happens when
8228 // there are two adjacent bytes after we move the low one.
8229 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8230 // If we haven't yet mapped the input, search for a slot into which
8232 while (j < je && PreDupI16Shuffle[j] != -1)
8236 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8239 // Map this input with the i16 shuffle.
8240 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8243 // Update the lane map based on the mapping we ended up with.
8244 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8247 ISD::BITCAST, DL, MVT::v16i8,
8248 DAG.getVectorShuffle(MVT::v8i16, DL,
8249 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8250 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8252 // Unpack the bytes to form the i16s that will be shuffled into place.
8253 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8254 MVT::v16i8, V1, V1);
8256 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8257 for (int i = 0; i < 16; i += 2) {
8259 PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8260 assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8263 ISD::BITCAST, DL, MVT::v16i8,
8264 DAG.getVectorShuffle(MVT::v8i16, DL,
8265 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8266 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8268 if (SDValue V = tryToWidenViaDuplication())
8272 // Check whether an interleaving lowering is likely to be more efficient.
8273 // This isn't perfect but it is a strong heuristic that tends to work well on
8274 // the kinds of shuffles that show up in practice.
8276 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8277 if (shouldLowerAsInterleaving(Mask)) {
8278 // FIXME: Figure out whether we should pack these into the low or high
8281 int EMask[16], OMask[16];
8282 for (int i = 0; i < 8; ++i) {
8283 EMask[i] = Mask[2*i];
8284 OMask[i] = Mask[2*i + 1];
8289 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8290 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8292 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8295 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8296 // with PSHUFB. It is important to do this before we attempt to generate any
8297 // blends but after all of the single-input lowerings. If the single input
8298 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8299 // want to preserve that and we can DAG combine any longer sequences into
8300 // a PSHUFB in the end. But once we start blending from multiple inputs,
8301 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8302 // and there are *very* few patterns that would actually be faster than the
8303 // PSHUFB approach because of its ability to zero lanes.
8305 // FIXME: The only exceptions to the above are blends which are exact
8306 // interleavings with direct instructions supporting them. We currently don't
8307 // handle those well here.
8308 if (Subtarget->hasSSSE3()) {
8311 for (int i = 0; i < 16; ++i)
8312 if (Mask[i] == -1) {
8313 V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8315 V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8317 DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8319 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8320 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8321 if (isSingleInputShuffleMask(Mask))
8322 return V1; // Single inputs are easy.
8324 // Otherwise, blend the two.
8325 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8326 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8327 return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8330 // Check whether a compaction lowering can be done. This handles shuffles
8331 // which take every Nth element for some even N. See the helper function for
8334 // We special case these as they can be particularly efficiently handled with
8335 // the PACKUSB instruction on x86 and they show up in common patterns of
8336 // rearranging bytes to truncate wide elements.
8337 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8338 // NumEvenDrops is the power of two stride of the elements. Another way of
8339 // thinking about it is that we need to drop the even elements this many
8340 // times to get the original input.
8341 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8343 // First we need to zero all the dropped bytes.
8344 assert(NumEvenDrops <= 3 &&
8345 "No support for dropping even elements more than 3 times.");
8346 // We use the mask type to pick which bytes are preserved based on how many
8347 // elements are dropped.
8348 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8349 SDValue ByteClearMask =
8350 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8351 DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8352 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8354 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8356 // Now pack things back together.
8357 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8358 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8359 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8360 for (int i = 1; i < NumEvenDrops; ++i) {
8361 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8362 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8368 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8369 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8370 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8371 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8373 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8374 MutableArrayRef<int> V1HalfBlendMask,
8375 MutableArrayRef<int> V2HalfBlendMask) {
8376 for (int i = 0; i < 8; ++i)
8377 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8378 V1HalfBlendMask[i] = HalfMask[i];
8380 } else if (HalfMask[i] >= 16) {
8381 V2HalfBlendMask[i] = HalfMask[i] - 16;
8382 HalfMask[i] = i + 8;
8385 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8386 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8388 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8390 auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8391 MutableArrayRef<int> HiBlendMask) {
8393 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8394 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8396 if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8397 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8398 std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8399 [](int M) { return M >= 0 && M % 2 == 1; })) {
8400 // Use a mask to drop the high bytes.
8401 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8402 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8403 DAG.getConstant(0x00FF, MVT::v8i16));
8405 // This will be a single vector shuffle instead of a blend so nuke V2.
8406 V2 = DAG.getUNDEF(MVT::v8i16);
8408 // Squash the masks to point directly into V1.
8409 for (int &M : LoBlendMask)
8412 for (int &M : HiBlendMask)
8416 // Otherwise just unpack the low half of V into V1 and the high half into
8417 // V2 so that we can blend them as i16s.
8418 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8419 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8420 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8421 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8424 SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8425 SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8426 return std::make_pair(BlendedLo, BlendedHi);
8428 SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8429 std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8430 std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8432 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8433 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8435 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8438 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8440 /// This routine breaks down the specific type of 128-bit shuffle and
8441 /// dispatches to the lowering routines accordingly.
8442 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8443 MVT VT, const X86Subtarget *Subtarget,
8444 SelectionDAG &DAG) {
8445 switch (VT.SimpleTy) {
8447 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8449 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8451 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8453 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8455 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8457 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8460 llvm_unreachable("Unimplemented!");
8464 static bool isHalfCrossingShuffleMask(ArrayRef<int> Mask) {
8465 int Size = Mask.size();
8466 for (int M : Mask.slice(0, Size / 2))
8467 if (M >= 0 && (M % Size) >= Size / 2)
8469 for (int M : Mask.slice(Size / 2, Size / 2))
8470 if (M >= 0 && (M % Size) < Size / 2)
8475 /// \brief Generic routine to split a 256-bit vector shuffle into 128-bit
8478 /// There is a severely limited set of shuffles available in AVX1 for 256-bit
8479 /// vectors resulting in routinely needing to split the shuffle into two 128-bit
8480 /// shuffles. This can be done generically for any 256-bit vector shuffle and so
8481 /// we encode the logic here for specific shuffle lowering routines to bail to
8482 /// when they exhaust the features avaible to more directly handle the shuffle.
8483 static SDValue splitAndLower256BitVectorShuffle(SDValue Op, SDValue V1,
8485 const X86Subtarget *Subtarget,
8486 SelectionDAG &DAG) {
8488 MVT VT = Op.getSimpleValueType();
8489 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8490 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8491 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8492 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8493 ArrayRef<int> Mask = SVOp->getMask();
8495 ArrayRef<int> LoMask = Mask.slice(0, Mask.size()/2);
8496 ArrayRef<int> HiMask = Mask.slice(Mask.size()/2);
8498 int NumElements = VT.getVectorNumElements();
8499 int SplitNumElements = NumElements / 2;
8500 MVT ScalarVT = VT.getScalarType();
8501 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8503 SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8504 DAG.getIntPtrConstant(0));
8505 SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8506 DAG.getIntPtrConstant(SplitNumElements));
8507 SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8508 DAG.getIntPtrConstant(0));
8509 SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8510 DAG.getIntPtrConstant(SplitNumElements));
8512 // Now create two 4-way blends of these half-width vectors.
8513 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8514 SmallVector<int, 16> V1BlendMask, V2BlendMask, BlendMask;
8515 for (int i = 0; i < SplitNumElements; ++i) {
8516 int M = HalfMask[i];
8517 if (M >= NumElements) {
8518 V2BlendMask.push_back(M - NumElements);
8519 V1BlendMask.push_back(-1);
8520 BlendMask.push_back(SplitNumElements + i);
8521 } else if (M >= 0) {
8522 V2BlendMask.push_back(-1);
8523 V1BlendMask.push_back(M);
8524 BlendMask.push_back(i);
8526 V2BlendMask.push_back(-1);
8527 V1BlendMask.push_back(-1);
8528 BlendMask.push_back(-1);
8531 SDValue V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8532 SDValue V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8533 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8535 SDValue Lo = HalfBlend(LoMask);
8536 SDValue Hi = HalfBlend(HiMask);
8537 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8540 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
8542 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
8543 /// isn't available.
8544 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8545 const X86Subtarget *Subtarget,
8546 SelectionDAG &DAG) {
8548 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8549 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8550 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8551 ArrayRef<int> Mask = SVOp->getMask();
8552 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8554 // FIXME: If we have AVX2, we should delegate to generic code as crossing
8555 // shuffles aren't a problem and FP and int have the same patterns.
8557 // FIXME: We can handle these more cleverly than splitting for v4f64.
8558 if (isHalfCrossingShuffleMask(Mask))
8559 return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8561 if (isSingleInputShuffleMask(Mask)) {
8562 // Non-half-crossing single input shuffles can be lowerid with an
8563 // interleaved permutation.
8564 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
8565 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
8566 return DAG.getNode(X86ISD::VPERMILP, DL, MVT::v4f64, V1,
8567 DAG.getConstant(VPERMILPMask, MVT::i8));
8570 // X86 has dedicated unpack instructions that can handle specific blend
8571 // operations: UNPCKH and UNPCKL.
8572 if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
8573 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
8574 if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
8575 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
8576 // FIXME: It would be nice to find a way to get canonicalization to commute
8578 if (isShuffleEquivalent(Mask, 4, 0, 6, 2))
8579 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
8580 if (isShuffleEquivalent(Mask, 5, 1, 7, 3))
8581 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
8583 // Check if the blend happens to exactly fit that of SHUFPD.
8584 if (Mask[0] < 4 && (Mask[1] == -1 || Mask[1] >= 4) &&
8585 Mask[2] < 4 && (Mask[3] == -1 || Mask[3] >= 4)) {
8586 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
8587 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
8588 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
8589 DAG.getConstant(SHUFPDMask, MVT::i8));
8591 if ((Mask[0] == -1 || Mask[0] >= 4) && Mask[1] < 4 &&
8592 (Mask[2] == -1 || Mask[2] >= 4) && Mask[3] < 4) {
8593 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
8594 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
8595 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
8596 DAG.getConstant(SHUFPDMask, MVT::i8));
8599 // Shuffle the input elements into the desired positions in V1 and V2 and
8600 // blend them together.
8601 int V1Mask[] = {-1, -1, -1, -1};
8602 int V2Mask[] = {-1, -1, -1, -1};
8603 for (int i = 0; i < 4; ++i)
8604 if (Mask[i] >= 0 && Mask[i] < 4)
8605 V1Mask[i] = Mask[i];
8606 else if (Mask[i] >= 4)
8607 V2Mask[i] = Mask[i] - 4;
8609 V1 = DAG.getVectorShuffle(MVT::v4f64, DL, V1, DAG.getUNDEF(MVT::v4f64), V1Mask);
8610 V2 = DAG.getVectorShuffle(MVT::v4f64, DL, V2, DAG.getUNDEF(MVT::v4f64), V2Mask);
8612 unsigned BlendMask = 0;
8613 for (int i = 0; i < 4; ++i)
8615 BlendMask |= 1 << i;
8617 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v4f64, V1, V2,
8618 DAG.getConstant(BlendMask, MVT::i8));
8621 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
8623 /// Largely delegates to common code when we have AVX2 and to the floating-point
8624 /// code when we only have AVX.
8625 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8626 const X86Subtarget *Subtarget,
8627 SelectionDAG &DAG) {
8629 assert(Op.getSimpleValueType() == MVT::v4i64 && "Bad shuffle type!");
8630 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8631 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8632 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8633 ArrayRef<int> Mask = SVOp->getMask();
8634 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8636 // FIXME: If we have AVX2, we should delegate to generic code as crossing
8637 // shuffles aren't a problem and FP and int have the same patterns.
8639 if (isHalfCrossingShuffleMask(Mask))
8640 return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8642 // AVX1 doesn't provide any facilities for v4i64 shuffles, bitcast and
8643 // delegate to floating point code.
8644 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V1);
8645 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V2);
8646 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i64,
8647 lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG));
8650 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
8652 /// This routine either breaks down the specific type of a 256-bit x86 vector
8653 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
8654 /// together based on the available instructions.
8655 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8656 MVT VT, const X86Subtarget *Subtarget,
8657 SelectionDAG &DAG) {
8658 switch (VT.SimpleTy) {
8660 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8662 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8667 // Fall back to the basic pattern of extracting the high half and forming
8669 // FIXME: Add targeted lowering for each type that can document rationale
8670 // for delegating to this when necessary.
8671 return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8674 llvm_unreachable("Not a valid 256-bit x86 vector type!");
8678 /// \brief Tiny helper function to test whether a shuffle mask could be
8679 /// simplified by widening the elements being shuffled.
8680 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
8681 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8682 if (Mask[i] % 2 != 0 || Mask[i] + 1 != Mask[i+1])
8688 /// \brief Top-level lowering for x86 vector shuffles.
8690 /// This handles decomposition, canonicalization, and lowering of all x86
8691 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8692 /// above in helper routines. The canonicalization attempts to widen shuffles
8693 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8694 /// s.t. only one of the two inputs needs to be tested, etc.
8695 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8696 SelectionDAG &DAG) {
8697 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8698 ArrayRef<int> Mask = SVOp->getMask();
8699 SDValue V1 = Op.getOperand(0);
8700 SDValue V2 = Op.getOperand(1);
8701 MVT VT = Op.getSimpleValueType();
8702 int NumElements = VT.getVectorNumElements();
8705 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8707 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8708 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8709 if (V1IsUndef && V2IsUndef)
8710 return DAG.getUNDEF(VT);
8712 // When we create a shuffle node we put the UNDEF node to second operand,
8713 // but in some cases the first operand may be transformed to UNDEF.
8714 // In this case we should just commute the node.
8716 return DAG.getCommutedVectorShuffle(*SVOp);
8718 // Check for non-undef masks pointing at an undef vector and make the masks
8719 // undef as well. This makes it easier to match the shuffle based solely on
8723 if (M >= NumElements) {
8724 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8725 for (int &M : NewMask)
8726 if (M >= NumElements)
8728 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8731 // For integer vector shuffles, try to collapse them into a shuffle of fewer
8732 // lanes but wider integers. We cap this to not form integers larger than i64
8733 // but it might be interesting to form i128 integers to handle flipping the
8734 // low and high halves of AVX 256-bit vectors.
8735 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8736 canWidenShuffleElements(Mask)) {
8737 SmallVector<int, 8> NewMask;
8738 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8739 NewMask.push_back(Mask[i] / 2);
8741 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8742 VT.getVectorNumElements() / 2);
8743 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8744 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8745 return DAG.getNode(ISD::BITCAST, dl, VT,
8746 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8749 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8750 for (int M : SVOp->getMask())
8753 else if (M < NumElements)
8758 // Commute the shuffle as needed such that more elements come from V1 than
8759 // V2. This allows us to match the shuffle pattern strictly on how many
8760 // elements come from V1 without handling the symmetric cases.
8761 if (NumV2Elements > NumV1Elements)
8762 return DAG.getCommutedVectorShuffle(*SVOp);
8764 // When the number of V1 and V2 elements are the same, try to minimize the
8765 // number of uses of V2 in the low half of the vector.
8766 if (NumV1Elements == NumV2Elements) {
8767 int LowV1Elements = 0, LowV2Elements = 0;
8768 for (int M : SVOp->getMask().slice(0, NumElements / 2))
8769 if (M >= NumElements)
8773 if (LowV2Elements > LowV1Elements)
8774 return DAG.getCommutedVectorShuffle(*SVOp);
8777 // For each vector width, delegate to a specialized lowering routine.
8778 if (VT.getSizeInBits() == 128)
8779 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8781 if (VT.getSizeInBits() == 256)
8782 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8784 llvm_unreachable("Unimplemented!");
8788 //===----------------------------------------------------------------------===//
8789 // Legacy vector shuffle lowering
8791 // This code is the legacy code handling vector shuffles until the above
8792 // replaces its functionality and performance.
8793 //===----------------------------------------------------------------------===//
8795 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8796 bool hasInt256, unsigned *MaskOut = nullptr) {
8797 MVT EltVT = VT.getVectorElementType();
8799 // There is no blend with immediate in AVX-512.
8800 if (VT.is512BitVector())
8803 if (!hasSSE41 || EltVT == MVT::i8)
8805 if (!hasInt256 && VT == MVT::v16i16)
8808 unsigned MaskValue = 0;
8809 unsigned NumElems = VT.getVectorNumElements();
8810 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8811 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8812 unsigned NumElemsInLane = NumElems / NumLanes;
8814 // Blend for v16i16 should be symetric for the both lanes.
8815 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8817 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8818 int EltIdx = MaskVals[i];
8820 if ((EltIdx < 0 || EltIdx == (int)i) &&
8821 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8824 if (((unsigned)EltIdx == (i + NumElems)) &&
8825 (SndLaneEltIdx < 0 ||
8826 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8827 MaskValue |= (1 << i);
8833 *MaskOut = MaskValue;
8837 // Try to lower a shuffle node into a simple blend instruction.
8838 // This function assumes isBlendMask returns true for this
8839 // SuffleVectorSDNode
8840 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8842 const X86Subtarget *Subtarget,
8843 SelectionDAG &DAG) {
8844 MVT VT = SVOp->getSimpleValueType(0);
8845 MVT EltVT = VT.getVectorElementType();
8846 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8847 Subtarget->hasInt256() && "Trying to lower a "
8848 "VECTOR_SHUFFLE to a Blend but "
8849 "with the wrong mask"));
8850 SDValue V1 = SVOp->getOperand(0);
8851 SDValue V2 = SVOp->getOperand(1);
8853 unsigned NumElems = VT.getVectorNumElements();
8855 // Convert i32 vectors to floating point if it is not AVX2.
8856 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8858 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8859 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8861 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8862 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8865 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8866 DAG.getConstant(MaskValue, MVT::i32));
8867 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8870 /// In vector type \p VT, return true if the element at index \p InputIdx
8871 /// falls on a different 128-bit lane than \p OutputIdx.
8872 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8873 unsigned OutputIdx) {
8874 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8875 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8878 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
8879 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
8880 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
8881 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8883 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8884 SelectionDAG &DAG) {
8885 MVT VT = V1.getSimpleValueType();
8886 assert(VT.is128BitVector() || VT.is256BitVector());
8888 MVT EltVT = VT.getVectorElementType();
8889 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8890 unsigned NumElts = VT.getVectorNumElements();
8892 SmallVector<SDValue, 32> PshufbMask;
8893 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8894 int InputIdx = MaskVals[OutputIdx];
8895 unsigned InputByteIdx;
8897 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8898 InputByteIdx = 0x80;
8900 // Cross lane is not allowed.
8901 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8903 InputByteIdx = InputIdx * EltSizeInBytes;
8904 // Index is an byte offset within the 128-bit lane.
8905 InputByteIdx &= 0xf;
8908 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8909 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8910 if (InputByteIdx != 0x80)
8915 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8917 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8918 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8919 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8922 // v8i16 shuffles - Prefer shuffles in the following order:
8923 // 1. [all] pshuflw, pshufhw, optional move
8924 // 2. [ssse3] 1 x pshufb
8925 // 3. [ssse3] 2 x pshufb + 1 x por
8926 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8928 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8929 SelectionDAG &DAG) {
8930 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8931 SDValue V1 = SVOp->getOperand(0);
8932 SDValue V2 = SVOp->getOperand(1);
8934 SmallVector<int, 8> MaskVals;
8936 // Determine if more than 1 of the words in each of the low and high quadwords
8937 // of the result come from the same quadword of one of the two inputs. Undef
8938 // mask values count as coming from any quadword, for better codegen.
8940 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8941 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8942 unsigned LoQuad[] = { 0, 0, 0, 0 };
8943 unsigned HiQuad[] = { 0, 0, 0, 0 };
8944 // Indices of quads used.
8945 std::bitset<4> InputQuads;
8946 for (unsigned i = 0; i < 8; ++i) {
8947 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8948 int EltIdx = SVOp->getMaskElt(i);
8949 MaskVals.push_back(EltIdx);
8958 InputQuads.set(EltIdx / 4);
8961 int BestLoQuad = -1;
8962 unsigned MaxQuad = 1;
8963 for (unsigned i = 0; i < 4; ++i) {
8964 if (LoQuad[i] > MaxQuad) {
8966 MaxQuad = LoQuad[i];
8970 int BestHiQuad = -1;
8972 for (unsigned i = 0; i < 4; ++i) {
8973 if (HiQuad[i] > MaxQuad) {
8975 MaxQuad = HiQuad[i];
8979 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8980 // of the two input vectors, shuffle them into one input vector so only a
8981 // single pshufb instruction is necessary. If there are more than 2 input
8982 // quads, disable the next transformation since it does not help SSSE3.
8983 bool V1Used = InputQuads[0] || InputQuads[1];
8984 bool V2Used = InputQuads[2] || InputQuads[3];
8985 if (Subtarget->hasSSSE3()) {
8986 if (InputQuads.count() == 2 && V1Used && V2Used) {
8987 BestLoQuad = InputQuads[0] ? 0 : 1;
8988 BestHiQuad = InputQuads[2] ? 2 : 3;
8990 if (InputQuads.count() > 2) {
8996 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8997 // the shuffle mask. If a quad is scored as -1, that means that it contains
8998 // words from all 4 input quadwords.
9000 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
9002 BestLoQuad < 0 ? 0 : BestLoQuad,
9003 BestHiQuad < 0 ? 1 : BestHiQuad
9005 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
9006 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
9007 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
9008 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
9010 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
9011 // source words for the shuffle, to aid later transformations.
9012 bool AllWordsInNewV = true;
9013 bool InOrder[2] = { true, true };
9014 for (unsigned i = 0; i != 8; ++i) {
9015 int idx = MaskVals[i];
9017 InOrder[i/4] = false;
9018 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
9020 AllWordsInNewV = false;
9024 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
9025 if (AllWordsInNewV) {
9026 for (int i = 0; i != 8; ++i) {
9027 int idx = MaskVals[i];
9030 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
9031 if ((idx != i) && idx < 4)
9033 if ((idx != i) && idx > 3)
9042 // If we've eliminated the use of V2, and the new mask is a pshuflw or
9043 // pshufhw, that's as cheap as it gets. Return the new shuffle.
9044 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
9045 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
9046 unsigned TargetMask = 0;
9047 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
9048 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
9049 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9050 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
9051 getShufflePSHUFLWImmediate(SVOp);
9052 V1 = NewV.getOperand(0);
9053 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
9057 // Promote splats to a larger type which usually leads to more efficient code.
9058 // FIXME: Is this true if pshufb is available?
9059 if (SVOp->isSplat())
9060 return PromoteSplat(SVOp, DAG);
9062 // If we have SSSE3, and all words of the result are from 1 input vector,
9063 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
9064 // is present, fall back to case 4.
9065 if (Subtarget->hasSSSE3()) {
9066 SmallVector<SDValue,16> pshufbMask;
9068 // If we have elements from both input vectors, set the high bit of the
9069 // shuffle mask element to zero out elements that come from V2 in the V1
9070 // mask, and elements that come from V1 in the V2 mask, so that the two
9071 // results can be OR'd together.
9072 bool TwoInputs = V1Used && V2Used;
9073 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
9075 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9077 // Calculate the shuffle mask for the second input, shuffle it, and
9078 // OR it with the first shuffled input.
9079 CommuteVectorShuffleMask(MaskVals, 8);
9080 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
9081 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9082 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9085 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
9086 // and update MaskVals with new element order.
9087 std::bitset<8> InOrder;
9088 if (BestLoQuad >= 0) {
9089 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
9090 for (int i = 0; i != 4; ++i) {
9091 int idx = MaskVals[i];
9094 } else if ((idx / 4) == BestLoQuad) {
9099 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9102 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9103 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9104 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
9106 getShufflePSHUFLWImmediate(SVOp), DAG);
9110 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
9111 // and update MaskVals with the new element order.
9112 if (BestHiQuad >= 0) {
9113 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
9114 for (unsigned i = 4; i != 8; ++i) {
9115 int idx = MaskVals[i];
9118 } else if ((idx / 4) == BestHiQuad) {
9119 MaskV[i] = (idx & 3) + 4;
9123 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9126 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9127 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9128 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
9130 getShufflePSHUFHWImmediate(SVOp), DAG);
9134 // In case BestHi & BestLo were both -1, which means each quadword has a word
9135 // from each of the four input quadwords, calculate the InOrder bitvector now
9136 // before falling through to the insert/extract cleanup.
9137 if (BestLoQuad == -1 && BestHiQuad == -1) {
9139 for (int i = 0; i != 8; ++i)
9140 if (MaskVals[i] < 0 || MaskVals[i] == i)
9144 // The other elements are put in the right place using pextrw and pinsrw.
9145 for (unsigned i = 0; i != 8; ++i) {
9148 int EltIdx = MaskVals[i];
9151 SDValue ExtOp = (EltIdx < 8) ?
9152 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
9153 DAG.getIntPtrConstant(EltIdx)) :
9154 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
9155 DAG.getIntPtrConstant(EltIdx - 8));
9156 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
9157 DAG.getIntPtrConstant(i));
9162 /// \brief v16i16 shuffles
9164 /// FIXME: We only support generation of a single pshufb currently. We can
9165 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
9166 /// well (e.g 2 x pshufb + 1 x por).
9168 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
9169 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9170 SDValue V1 = SVOp->getOperand(0);
9171 SDValue V2 = SVOp->getOperand(1);
9174 if (V2.getOpcode() != ISD::UNDEF)
9177 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9178 return getPSHUFB(MaskVals, V1, dl, DAG);
9181 // v16i8 shuffles - Prefer shuffles in the following order:
9182 // 1. [ssse3] 1 x pshufb
9183 // 2. [ssse3] 2 x pshufb + 1 x por
9184 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
9185 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
9186 const X86Subtarget* Subtarget,
9187 SelectionDAG &DAG) {
9188 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9189 SDValue V1 = SVOp->getOperand(0);
9190 SDValue V2 = SVOp->getOperand(1);
9192 ArrayRef<int> MaskVals = SVOp->getMask();
9194 // Promote splats to a larger type which usually leads to more efficient code.
9195 // FIXME: Is this true if pshufb is available?
9196 if (SVOp->isSplat())
9197 return PromoteSplat(SVOp, DAG);
9199 // If we have SSSE3, case 1 is generated when all result bytes come from
9200 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
9201 // present, fall back to case 3.
9203 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
9204 if (Subtarget->hasSSSE3()) {
9205 SmallVector<SDValue,16> pshufbMask;
9207 // If all result elements are from one input vector, then only translate
9208 // undef mask values to 0x80 (zero out result) in the pshufb mask.
9210 // Otherwise, we have elements from both input vectors, and must zero out
9211 // elements that come from V2 in the first mask, and V1 in the second mask
9212 // so that we can OR them together.
9213 for (unsigned i = 0; i != 16; ++i) {
9214 int EltIdx = MaskVals[i];
9215 if (EltIdx < 0 || EltIdx >= 16)
9217 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9219 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
9220 DAG.getNode(ISD::BUILD_VECTOR, dl,
9221 MVT::v16i8, pshufbMask));
9223 // As PSHUFB will zero elements with negative indices, it's safe to ignore
9224 // the 2nd operand if it's undefined or zero.
9225 if (V2.getOpcode() == ISD::UNDEF ||
9226 ISD::isBuildVectorAllZeros(V2.getNode()))
9229 // Calculate the shuffle mask for the second input, shuffle it, and
9230 // OR it with the first shuffled input.
9232 for (unsigned i = 0; i != 16; ++i) {
9233 int EltIdx = MaskVals[i];
9234 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
9235 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9237 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
9238 DAG.getNode(ISD::BUILD_VECTOR, dl,
9239 MVT::v16i8, pshufbMask));
9240 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9243 // No SSSE3 - Calculate in place words and then fix all out of place words
9244 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
9245 // the 16 different words that comprise the two doublequadword input vectors.
9246 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9247 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9249 for (int i = 0; i != 8; ++i) {
9250 int Elt0 = MaskVals[i*2];
9251 int Elt1 = MaskVals[i*2+1];
9253 // This word of the result is all undef, skip it.
9254 if (Elt0 < 0 && Elt1 < 0)
9257 // This word of the result is already in the correct place, skip it.
9258 if ((Elt0 == i*2) && (Elt1 == i*2+1))
9261 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
9262 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
9265 // If Elt0 and Elt1 are defined, are consecutive, and can be load
9266 // using a single extract together, load it and store it.
9267 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
9268 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9269 DAG.getIntPtrConstant(Elt1 / 2));
9270 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9271 DAG.getIntPtrConstant(i));
9275 // If Elt1 is defined, extract it from the appropriate source. If the
9276 // source byte is not also odd, shift the extracted word left 8 bits
9277 // otherwise clear the bottom 8 bits if we need to do an or.
9279 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9280 DAG.getIntPtrConstant(Elt1 / 2));
9281 if ((Elt1 & 1) == 0)
9282 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
9284 TLI.getShiftAmountTy(InsElt.getValueType())));
9286 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
9287 DAG.getConstant(0xFF00, MVT::i16));
9289 // If Elt0 is defined, extract it from the appropriate source. If the
9290 // source byte is not also even, shift the extracted word right 8 bits. If
9291 // Elt1 was also defined, OR the extracted values together before
9292 // inserting them in the result.
9294 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
9295 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
9296 if ((Elt0 & 1) != 0)
9297 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
9299 TLI.getShiftAmountTy(InsElt0.getValueType())));
9301 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
9302 DAG.getConstant(0x00FF, MVT::i16));
9303 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
9306 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9307 DAG.getIntPtrConstant(i));
9309 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
9312 // v32i8 shuffles - Translate to VPSHUFB if possible.
9314 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
9315 const X86Subtarget *Subtarget,
9316 SelectionDAG &DAG) {
9317 MVT VT = SVOp->getSimpleValueType(0);
9318 SDValue V1 = SVOp->getOperand(0);
9319 SDValue V2 = SVOp->getOperand(1);
9321 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9323 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9324 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
9325 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
9327 // VPSHUFB may be generated if
9328 // (1) one of input vector is undefined or zeroinitializer.
9329 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
9330 // And (2) the mask indexes don't cross the 128-bit lane.
9331 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
9332 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
9335 if (V1IsAllZero && !V2IsAllZero) {
9336 CommuteVectorShuffleMask(MaskVals, 32);
9339 return getPSHUFB(MaskVals, V1, dl, DAG);
9342 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
9343 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
9344 /// done when every pair / quad of shuffle mask elements point to elements in
9345 /// the right sequence. e.g.
9346 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
9348 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
9349 SelectionDAG &DAG) {
9350 MVT VT = SVOp->getSimpleValueType(0);
9352 unsigned NumElems = VT.getVectorNumElements();
9355 switch (VT.SimpleTy) {
9356 default: llvm_unreachable("Unexpected!");
9359 return SDValue(SVOp, 0);
9360 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
9361 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
9362 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
9363 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
9364 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
9365 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
9368 SmallVector<int, 8> MaskVec;
9369 for (unsigned i = 0; i != NumElems; i += Scale) {
9371 for (unsigned j = 0; j != Scale; ++j) {
9372 int EltIdx = SVOp->getMaskElt(i+j);
9376 StartIdx = (EltIdx / Scale);
9377 if (EltIdx != (int)(StartIdx*Scale + j))
9380 MaskVec.push_back(StartIdx);
9383 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
9384 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
9385 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
9388 /// getVZextMovL - Return a zero-extending vector move low node.
9390 static SDValue getVZextMovL(MVT VT, MVT OpVT,
9391 SDValue SrcOp, SelectionDAG &DAG,
9392 const X86Subtarget *Subtarget, SDLoc dl) {
9393 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
9394 LoadSDNode *LD = nullptr;
9395 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
9396 LD = dyn_cast<LoadSDNode>(SrcOp);
9398 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
9400 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
9401 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
9402 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9403 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
9404 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
9406 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
9407 return DAG.getNode(ISD::BITCAST, dl, VT,
9408 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9409 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9417 return DAG.getNode(ISD::BITCAST, dl, VT,
9418 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9419 DAG.getNode(ISD::BITCAST, dl,
9423 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
9424 /// which could not be matched by any known target speficic shuffle
9426 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9428 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
9429 if (NewOp.getNode())
9432 MVT VT = SVOp->getSimpleValueType(0);
9434 unsigned NumElems = VT.getVectorNumElements();
9435 unsigned NumLaneElems = NumElems / 2;
9438 MVT EltVT = VT.getVectorElementType();
9439 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
9442 SmallVector<int, 16> Mask;
9443 for (unsigned l = 0; l < 2; ++l) {
9444 // Build a shuffle mask for the output, discovering on the fly which
9445 // input vectors to use as shuffle operands (recorded in InputUsed).
9446 // If building a suitable shuffle vector proves too hard, then bail
9447 // out with UseBuildVector set.
9448 bool UseBuildVector = false;
9449 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9450 unsigned LaneStart = l * NumLaneElems;
9451 for (unsigned i = 0; i != NumLaneElems; ++i) {
9452 // The mask element. This indexes into the input.
9453 int Idx = SVOp->getMaskElt(i+LaneStart);
9455 // the mask element does not index into any input vector.
9460 // The input vector this mask element indexes into.
9461 int Input = Idx / NumLaneElems;
9463 // Turn the index into an offset from the start of the input vector.
9464 Idx -= Input * NumLaneElems;
9466 // Find or create a shuffle vector operand to hold this input.
9468 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9469 if (InputUsed[OpNo] == Input)
9470 // This input vector is already an operand.
9472 if (InputUsed[OpNo] < 0) {
9473 // Create a new operand for this input vector.
9474 InputUsed[OpNo] = Input;
9479 if (OpNo >= array_lengthof(InputUsed)) {
9480 // More than two input vectors used! Give up on trying to create a
9481 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
9482 UseBuildVector = true;
9486 // Add the mask index for the new shuffle vector.
9487 Mask.push_back(Idx + OpNo * NumLaneElems);
9490 if (UseBuildVector) {
9491 SmallVector<SDValue, 16> SVOps;
9492 for (unsigned i = 0; i != NumLaneElems; ++i) {
9493 // The mask element. This indexes into the input.
9494 int Idx = SVOp->getMaskElt(i+LaneStart);
9496 SVOps.push_back(DAG.getUNDEF(EltVT));
9500 // The input vector this mask element indexes into.
9501 int Input = Idx / NumElems;
9503 // Turn the index into an offset from the start of the input vector.
9504 Idx -= Input * NumElems;
9506 // Extract the vector element by hand.
9507 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9508 SVOp->getOperand(Input),
9509 DAG.getIntPtrConstant(Idx)));
9512 // Construct the output using a BUILD_VECTOR.
9513 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9514 } else if (InputUsed[0] < 0) {
9515 // No input vectors were used! The result is undefined.
9516 Output[l] = DAG.getUNDEF(NVT);
9518 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9519 (InputUsed[0] % 2) * NumLaneElems,
9521 // If only one input was used, use an undefined vector for the other.
9522 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9523 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9524 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9525 // At least one input vector was used. Create a new shuffle vector.
9526 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9532 // Concatenate the result back
9533 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9536 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9537 /// 4 elements, and match them with several different shuffle types.
9539 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9540 SDValue V1 = SVOp->getOperand(0);
9541 SDValue V2 = SVOp->getOperand(1);
9543 MVT VT = SVOp->getSimpleValueType(0);
9545 assert(VT.is128BitVector() && "Unsupported vector size");
9547 std::pair<int, int> Locs[4];
9548 int Mask1[] = { -1, -1, -1, -1 };
9549 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9553 for (unsigned i = 0; i != 4; ++i) {
9554 int Idx = PermMask[i];
9556 Locs[i] = std::make_pair(-1, -1);
9558 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9560 Locs[i] = std::make_pair(0, NumLo);
9564 Locs[i] = std::make_pair(1, NumHi);
9566 Mask1[2+NumHi] = Idx;
9572 if (NumLo <= 2 && NumHi <= 2) {
9573 // If no more than two elements come from either vector. This can be
9574 // implemented with two shuffles. First shuffle gather the elements.
9575 // The second shuffle, which takes the first shuffle as both of its
9576 // vector operands, put the elements into the right order.
9577 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9579 int Mask2[] = { -1, -1, -1, -1 };
9581 for (unsigned i = 0; i != 4; ++i)
9582 if (Locs[i].first != -1) {
9583 unsigned Idx = (i < 2) ? 0 : 4;
9584 Idx += Locs[i].first * 2 + Locs[i].second;
9588 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9591 if (NumLo == 3 || NumHi == 3) {
9592 // Otherwise, we must have three elements from one vector, call it X, and
9593 // one element from the other, call it Y. First, use a shufps to build an
9594 // intermediate vector with the one element from Y and the element from X
9595 // that will be in the same half in the final destination (the indexes don't
9596 // matter). Then, use a shufps to build the final vector, taking the half
9597 // containing the element from Y from the intermediate, and the other half
9600 // Normalize it so the 3 elements come from V1.
9601 CommuteVectorShuffleMask(PermMask, 4);
9605 // Find the element from V2.
9607 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9608 int Val = PermMask[HiIndex];
9615 Mask1[0] = PermMask[HiIndex];
9617 Mask1[2] = PermMask[HiIndex^1];
9619 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9622 Mask1[0] = PermMask[0];
9623 Mask1[1] = PermMask[1];
9624 Mask1[2] = HiIndex & 1 ? 6 : 4;
9625 Mask1[3] = HiIndex & 1 ? 4 : 6;
9626 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9629 Mask1[0] = HiIndex & 1 ? 2 : 0;
9630 Mask1[1] = HiIndex & 1 ? 0 : 2;
9631 Mask1[2] = PermMask[2];
9632 Mask1[3] = PermMask[3];
9637 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9640 // Break it into (shuffle shuffle_hi, shuffle_lo).
9641 int LoMask[] = { -1, -1, -1, -1 };
9642 int HiMask[] = { -1, -1, -1, -1 };
9644 int *MaskPtr = LoMask;
9645 unsigned MaskIdx = 0;
9648 for (unsigned i = 0; i != 4; ++i) {
9655 int Idx = PermMask[i];
9657 Locs[i] = std::make_pair(-1, -1);
9658 } else if (Idx < 4) {
9659 Locs[i] = std::make_pair(MaskIdx, LoIdx);
9660 MaskPtr[LoIdx] = Idx;
9663 Locs[i] = std::make_pair(MaskIdx, HiIdx);
9664 MaskPtr[HiIdx] = Idx;
9669 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9670 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9671 int MaskOps[] = { -1, -1, -1, -1 };
9672 for (unsigned i = 0; i != 4; ++i)
9673 if (Locs[i].first != -1)
9674 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9675 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9678 static bool MayFoldVectorLoad(SDValue V) {
9679 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9680 V = V.getOperand(0);
9682 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9683 V = V.getOperand(0);
9684 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9685 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9686 // BUILD_VECTOR (load), undef
9687 V = V.getOperand(0);
9689 return MayFoldLoad(V);
9693 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9694 MVT VT = Op.getSimpleValueType();
9696 // Canonizalize to v2f64.
9697 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9698 return DAG.getNode(ISD::BITCAST, dl, VT,
9699 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9704 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9706 SDValue V1 = Op.getOperand(0);
9707 SDValue V2 = Op.getOperand(1);
9708 MVT VT = Op.getSimpleValueType();
9710 assert(VT != MVT::v2i64 && "unsupported shuffle type");
9712 if (HasSSE2 && VT == MVT::v2f64)
9713 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9715 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9716 return DAG.getNode(ISD::BITCAST, dl, VT,
9717 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9718 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9719 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9723 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9724 SDValue V1 = Op.getOperand(0);
9725 SDValue V2 = Op.getOperand(1);
9726 MVT VT = Op.getSimpleValueType();
9728 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9729 "unsupported shuffle type");
9731 if (V2.getOpcode() == ISD::UNDEF)
9735 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9739 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9740 SDValue V1 = Op.getOperand(0);
9741 SDValue V2 = Op.getOperand(1);
9742 MVT VT = Op.getSimpleValueType();
9743 unsigned NumElems = VT.getVectorNumElements();
9745 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9746 // operand of these instructions is only memory, so check if there's a
9747 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9749 bool CanFoldLoad = false;
9751 // Trivial case, when V2 comes from a load.
9752 if (MayFoldVectorLoad(V2))
9755 // When V1 is a load, it can be folded later into a store in isel, example:
9756 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9758 // (MOVLPSmr addr:$src1, VR128:$src2)
9759 // So, recognize this potential and also use MOVLPS or MOVLPD
9760 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9763 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9765 if (HasSSE2 && NumElems == 2)
9766 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9769 // If we don't care about the second element, proceed to use movss.
9770 if (SVOp->getMaskElt(1) != -1)
9771 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9774 // movl and movlp will both match v2i64, but v2i64 is never matched by
9775 // movl earlier because we make it strict to avoid messing with the movlp load
9776 // folding logic (see the code above getMOVLP call). Match it here then,
9777 // this is horrible, but will stay like this until we move all shuffle
9778 // matching to x86 specific nodes. Note that for the 1st condition all
9779 // types are matched with movsd.
9781 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9782 // as to remove this logic from here, as much as possible
9783 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9784 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9785 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9788 assert(VT != MVT::v4i32 && "unsupported shuffle type");
9790 // Invert the operand order and use SHUFPS to match it.
9791 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9792 getShuffleSHUFImmediate(SVOp), DAG);
9795 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9796 SelectionDAG &DAG) {
9798 MVT VT = Load->getSimpleValueType(0);
9799 MVT EVT = VT.getVectorElementType();
9800 SDValue Addr = Load->getOperand(1);
9801 SDValue NewAddr = DAG.getNode(
9802 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9803 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9806 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9807 DAG.getMachineFunction().getMachineMemOperand(
9808 Load->getMemOperand(), 0, EVT.getStoreSize()));
9812 // It is only safe to call this function if isINSERTPSMask is true for
9813 // this shufflevector mask.
9814 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9815 SelectionDAG &DAG) {
9816 // Generate an insertps instruction when inserting an f32 from memory onto a
9817 // v4f32 or when copying a member from one v4f32 to another.
9818 // We also use it for transferring i32 from one register to another,
9819 // since it simply copies the same bits.
9820 // If we're transferring an i32 from memory to a specific element in a
9821 // register, we output a generic DAG that will match the PINSRD
9823 MVT VT = SVOp->getSimpleValueType(0);
9824 MVT EVT = VT.getVectorElementType();
9825 SDValue V1 = SVOp->getOperand(0);
9826 SDValue V2 = SVOp->getOperand(1);
9827 auto Mask = SVOp->getMask();
9828 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9829 "unsupported vector type for insertps/pinsrd");
9831 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9832 auto FromV2Predicate = [](const int &i) { return i >= 4; };
9833 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9841 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9844 // If we have 1 element from each vector, we have to check if we're
9845 // changing V1's element's place. If so, we're done. Otherwise, we
9846 // should assume we're changing V2's element's place and behave
9848 int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9849 assert(DestIndex <= INT32_MAX && "truncated destination index");
9850 if (FromV1 == FromV2 &&
9851 static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9855 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9858 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9859 "More than one element from V1 and from V2, or no elements from one "
9860 "of the vectors. This case should not have returned true from "
9865 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9868 // Get an index into the source vector in the range [0,4) (the mask is
9869 // in the range [0,8) because it can address V1 and V2)
9870 unsigned SrcIndex = Mask[DestIndex] % 4;
9871 if (MayFoldLoad(From)) {
9872 // Trivial case, when From comes from a load and is only used by the
9873 // shuffle. Make it use insertps from the vector that we need from that
9876 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9877 if (!NewLoad.getNode())
9880 if (EVT == MVT::f32) {
9881 // Create this as a scalar to vector to match the instruction pattern.
9882 SDValue LoadScalarToVector =
9883 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9884 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9885 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9887 } else { // EVT == MVT::i32
9888 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9889 // instruction, to match the PINSRD instruction, which loads an i32 to a
9890 // certain vector element.
9891 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9892 DAG.getConstant(DestIndex, MVT::i32));
9896 // Vector-element-to-vector
9897 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9898 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9901 // Reduce a vector shuffle to zext.
9902 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9903 SelectionDAG &DAG) {
9904 // PMOVZX is only available from SSE41.
9905 if (!Subtarget->hasSSE41())
9908 MVT VT = Op.getSimpleValueType();
9910 // Only AVX2 support 256-bit vector integer extending.
9911 if (!Subtarget->hasInt256() && VT.is256BitVector())
9914 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9916 SDValue V1 = Op.getOperand(0);
9917 SDValue V2 = Op.getOperand(1);
9918 unsigned NumElems = VT.getVectorNumElements();
9920 // Extending is an unary operation and the element type of the source vector
9921 // won't be equal to or larger than i64.
9922 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9923 VT.getVectorElementType() == MVT::i64)
9926 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9927 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9928 while ((1U << Shift) < NumElems) {
9929 if (SVOp->getMaskElt(1U << Shift) == 1)
9932 // The maximal ratio is 8, i.e. from i8 to i64.
9937 // Check the shuffle mask.
9938 unsigned Mask = (1U << Shift) - 1;
9939 for (unsigned i = 0; i != NumElems; ++i) {
9940 int EltIdx = SVOp->getMaskElt(i);
9941 if ((i & Mask) != 0 && EltIdx != -1)
9943 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9947 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9948 MVT NeVT = MVT::getIntegerVT(NBits);
9949 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9951 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9954 // Simplify the operand as it's prepared to be fed into shuffle.
9955 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9956 if (V1.getOpcode() == ISD::BITCAST &&
9957 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9958 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9959 V1.getOperand(0).getOperand(0)
9960 .getSimpleValueType().getSizeInBits() == SignificantBits) {
9961 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9962 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9963 ConstantSDNode *CIdx =
9964 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9965 // If it's foldable, i.e. normal load with single use, we will let code
9966 // selection to fold it. Otherwise, we will short the conversion sequence.
9967 if (CIdx && CIdx->getZExtValue() == 0 &&
9968 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9969 MVT FullVT = V.getSimpleValueType();
9970 MVT V1VT = V1.getSimpleValueType();
9971 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9972 // The "ext_vec_elt" node is wider than the result node.
9973 // In this case we should extract subvector from V.
9974 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9975 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9976 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9977 FullVT.getVectorNumElements()/Ratio);
9978 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9979 DAG.getIntPtrConstant(0));
9981 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9985 return DAG.getNode(ISD::BITCAST, DL, VT,
9986 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9989 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9990 SelectionDAG &DAG) {
9991 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9992 MVT VT = Op.getSimpleValueType();
9994 SDValue V1 = Op.getOperand(0);
9995 SDValue V2 = Op.getOperand(1);
9997 if (isZeroShuffle(SVOp))
9998 return getZeroVector(VT, Subtarget, DAG, dl);
10000 // Handle splat operations
10001 if (SVOp->isSplat()) {
10002 // Use vbroadcast whenever the splat comes from a foldable load
10003 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
10004 if (Broadcast.getNode())
10008 // Check integer expanding shuffles.
10009 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
10010 if (NewOp.getNode())
10013 // If the shuffle can be profitably rewritten as a narrower shuffle, then
10015 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
10016 VT == MVT::v32i8) {
10017 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10018 if (NewOp.getNode())
10019 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
10020 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
10021 // FIXME: Figure out a cleaner way to do this.
10022 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
10023 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10024 if (NewOp.getNode()) {
10025 MVT NewVT = NewOp.getSimpleValueType();
10026 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
10027 NewVT, true, false))
10028 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
10031 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
10032 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10033 if (NewOp.getNode()) {
10034 MVT NewVT = NewOp.getSimpleValueType();
10035 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
10036 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
10045 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
10046 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10047 SDValue V1 = Op.getOperand(0);
10048 SDValue V2 = Op.getOperand(1);
10049 MVT VT = Op.getSimpleValueType();
10051 unsigned NumElems = VT.getVectorNumElements();
10052 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10053 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10054 bool V1IsSplat = false;
10055 bool V2IsSplat = false;
10056 bool HasSSE2 = Subtarget->hasSSE2();
10057 bool HasFp256 = Subtarget->hasFp256();
10058 bool HasInt256 = Subtarget->hasInt256();
10059 MachineFunction &MF = DAG.getMachineFunction();
10060 bool OptForSize = MF.getFunction()->getAttributes().
10061 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
10063 // Check if we should use the experimental vector shuffle lowering. If so,
10064 // delegate completely to that code path.
10065 if (ExperimentalVectorShuffleLowering)
10066 return lowerVectorShuffle(Op, Subtarget, DAG);
10068 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10070 if (V1IsUndef && V2IsUndef)
10071 return DAG.getUNDEF(VT);
10073 // When we create a shuffle node we put the UNDEF node to second operand,
10074 // but in some cases the first operand may be transformed to UNDEF.
10075 // In this case we should just commute the node.
10077 return DAG.getCommutedVectorShuffle(*SVOp);
10079 // Vector shuffle lowering takes 3 steps:
10081 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
10082 // narrowing and commutation of operands should be handled.
10083 // 2) Matching of shuffles with known shuffle masks to x86 target specific
10085 // 3) Rewriting of unmatched masks into new generic shuffle operations,
10086 // so the shuffle can be broken into other shuffles and the legalizer can
10087 // try the lowering again.
10089 // The general idea is that no vector_shuffle operation should be left to
10090 // be matched during isel, all of them must be converted to a target specific
10093 // Normalize the input vectors. Here splats, zeroed vectors, profitable
10094 // narrowing and commutation of operands should be handled. The actual code
10095 // doesn't include all of those, work in progress...
10096 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
10097 if (NewOp.getNode())
10100 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
10102 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
10103 // unpckh_undef). Only use pshufd if speed is more important than size.
10104 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10105 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10106 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10107 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10109 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
10110 V2IsUndef && MayFoldVectorLoad(V1))
10111 return getMOVDDup(Op, dl, V1, DAG);
10113 if (isMOVHLPS_v_undef_Mask(M, VT))
10114 return getMOVHighToLow(Op, dl, DAG);
10116 // Use to match splats
10117 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
10118 (VT == MVT::v2f64 || VT == MVT::v2i64))
10119 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10121 if (isPSHUFDMask(M, VT)) {
10122 // The actual implementation will match the mask in the if above and then
10123 // during isel it can match several different instructions, not only pshufd
10124 // as its name says, sad but true, emulate the behavior for now...
10125 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
10126 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
10128 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
10130 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
10131 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
10133 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
10134 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
10137 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
10141 if (isPALIGNRMask(M, VT, Subtarget))
10142 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
10143 getShufflePALIGNRImmediate(SVOp),
10146 if (isVALIGNMask(M, VT, Subtarget))
10147 return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
10148 getShuffleVALIGNImmediate(SVOp),
10151 // Check if this can be converted into a logical shift.
10152 bool isLeft = false;
10153 unsigned ShAmt = 0;
10155 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
10156 if (isShift && ShVal.hasOneUse()) {
10157 // If the shifted value has multiple uses, it may be cheaper to use
10158 // v_set0 + movlhps or movhlps, etc.
10159 MVT EltVT = VT.getVectorElementType();
10160 ShAmt *= EltVT.getSizeInBits();
10161 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10164 if (isMOVLMask(M, VT)) {
10165 if (ISD::isBuildVectorAllZeros(V1.getNode()))
10166 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
10167 if (!isMOVLPMask(M, VT)) {
10168 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
10169 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10171 if (VT == MVT::v4i32 || VT == MVT::v4f32)
10172 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10176 // FIXME: fold these into legal mask.
10177 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
10178 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
10180 if (isMOVHLPSMask(M, VT))
10181 return getMOVHighToLow(Op, dl, DAG);
10183 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
10184 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
10186 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
10187 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
10189 if (isMOVLPMask(M, VT))
10190 return getMOVLP(Op, dl, DAG, HasSSE2);
10192 if (ShouldXformToMOVHLPS(M, VT) ||
10193 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
10194 return DAG.getCommutedVectorShuffle(*SVOp);
10197 // No better options. Use a vshldq / vsrldq.
10198 MVT EltVT = VT.getVectorElementType();
10199 ShAmt *= EltVT.getSizeInBits();
10200 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10203 bool Commuted = false;
10204 // FIXME: This should also accept a bitcast of a splat? Be careful, not
10205 // 1,1,1,1 -> v8i16 though.
10206 BitVector UndefElements;
10207 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
10208 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10210 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
10211 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10214 // Canonicalize the splat or undef, if present, to be on the RHS.
10215 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
10216 CommuteVectorShuffleMask(M, NumElems);
10218 std::swap(V1IsSplat, V2IsSplat);
10222 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
10223 // Shuffling low element of v1 into undef, just return v1.
10226 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
10227 // the instruction selector will not match, so get a canonical MOVL with
10228 // swapped operands to undo the commute.
10229 return getMOVL(DAG, dl, VT, V2, V1);
10232 if (isUNPCKLMask(M, VT, HasInt256))
10233 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10235 if (isUNPCKHMask(M, VT, HasInt256))
10236 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10239 // Normalize mask so all entries that point to V2 points to its first
10240 // element then try to match unpck{h|l} again. If match, return a
10241 // new vector_shuffle with the corrected mask.p
10242 SmallVector<int, 8> NewMask(M.begin(), M.end());
10243 NormalizeMask(NewMask, NumElems);
10244 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
10245 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10246 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
10247 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10251 // Commute is back and try unpck* again.
10252 // FIXME: this seems wrong.
10253 CommuteVectorShuffleMask(M, NumElems);
10255 std::swap(V1IsSplat, V2IsSplat);
10257 if (isUNPCKLMask(M, VT, HasInt256))
10258 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10260 if (isUNPCKHMask(M, VT, HasInt256))
10261 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10264 // Normalize the node to match x86 shuffle ops if needed
10265 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
10266 return DAG.getCommutedVectorShuffle(*SVOp);
10268 // The checks below are all present in isShuffleMaskLegal, but they are
10269 // inlined here right now to enable us to directly emit target specific
10270 // nodes, and remove one by one until they don't return Op anymore.
10272 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
10273 SVOp->getSplatIndex() == 0 && V2IsUndef) {
10274 if (VT == MVT::v2f64 || VT == MVT::v2i64)
10275 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10278 if (isPSHUFHWMask(M, VT, HasInt256))
10279 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
10280 getShufflePSHUFHWImmediate(SVOp),
10283 if (isPSHUFLWMask(M, VT, HasInt256))
10284 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
10285 getShufflePSHUFLWImmediate(SVOp),
10288 unsigned MaskValue;
10289 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
10291 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
10293 if (isSHUFPMask(M, VT))
10294 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
10295 getShuffleSHUFImmediate(SVOp), DAG);
10297 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10298 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10299 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10300 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10302 //===--------------------------------------------------------------------===//
10303 // Generate target specific nodes for 128 or 256-bit shuffles only
10304 // supported in the AVX instruction set.
10307 // Handle VMOVDDUPY permutations
10308 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
10309 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
10311 // Handle VPERMILPS/D* permutations
10312 if (isVPERMILPMask(M, VT)) {
10313 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
10314 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
10315 getShuffleSHUFImmediate(SVOp), DAG);
10316 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
10317 getShuffleSHUFImmediate(SVOp), DAG);
10321 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
10322 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
10323 Idx*(NumElems/2), DAG, dl);
10325 // Handle VPERM2F128/VPERM2I128 permutations
10326 if (isVPERM2X128Mask(M, VT, HasFp256))
10327 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
10328 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
10330 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
10331 return getINSERTPS(SVOp, dl, DAG);
10334 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
10335 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
10337 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
10338 VT.is512BitVector()) {
10339 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
10340 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
10341 SmallVector<SDValue, 16> permclMask;
10342 for (unsigned i = 0; i != NumElems; ++i) {
10343 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
10346 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
10348 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
10349 return DAG.getNode(X86ISD::VPERMV, dl, VT,
10350 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
10351 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
10352 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
10355 //===--------------------------------------------------------------------===//
10356 // Since no target specific shuffle was selected for this generic one,
10357 // lower it into other known shuffles. FIXME: this isn't true yet, but
10358 // this is the plan.
10361 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
10362 if (VT == MVT::v8i16) {
10363 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
10364 if (NewOp.getNode())
10368 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
10369 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
10370 if (NewOp.getNode())
10374 if (VT == MVT::v16i8) {
10375 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
10376 if (NewOp.getNode())
10380 if (VT == MVT::v32i8) {
10381 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
10382 if (NewOp.getNode())
10386 // Handle all 128-bit wide vectors with 4 elements, and match them with
10387 // several different shuffle types.
10388 if (NumElems == 4 && VT.is128BitVector())
10389 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
10391 // Handle general 256-bit shuffles
10392 if (VT.is256BitVector())
10393 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
10398 // This function assumes its argument is a BUILD_VECTOR of constants or
10399 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10401 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10402 unsigned &MaskValue) {
10404 unsigned NumElems = BuildVector->getNumOperands();
10405 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10406 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10407 unsigned NumElemsInLane = NumElems / NumLanes;
10409 // Blend for v16i16 should be symetric for the both lanes.
10410 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10411 SDValue EltCond = BuildVector->getOperand(i);
10412 SDValue SndLaneEltCond =
10413 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10415 int Lane1Cond = -1, Lane2Cond = -1;
10416 if (isa<ConstantSDNode>(EltCond))
10417 Lane1Cond = !isZero(EltCond);
10418 if (isa<ConstantSDNode>(SndLaneEltCond))
10419 Lane2Cond = !isZero(SndLaneEltCond);
10421 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10422 // Lane1Cond != 0, means we want the first argument.
10423 // Lane1Cond == 0, means we want the second argument.
10424 // The encoding of this argument is 0 for the first argument, 1
10425 // for the second. Therefore, invert the condition.
10426 MaskValue |= !Lane1Cond << i;
10427 else if (Lane1Cond < 0)
10428 MaskValue |= !Lane2Cond << i;
10435 // Try to lower a vselect node into a simple blend instruction.
10436 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
10437 SelectionDAG &DAG) {
10438 SDValue Cond = Op.getOperand(0);
10439 SDValue LHS = Op.getOperand(1);
10440 SDValue RHS = Op.getOperand(2);
10442 MVT VT = Op.getSimpleValueType();
10443 MVT EltVT = VT.getVectorElementType();
10444 unsigned NumElems = VT.getVectorNumElements();
10446 // There is no blend with immediate in AVX-512.
10447 if (VT.is512BitVector())
10450 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10452 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10455 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10458 // Check the mask for BLEND and build the value.
10459 unsigned MaskValue = 0;
10460 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10463 // Convert i32 vectors to floating point if it is not AVX2.
10464 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10466 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10467 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10469 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10470 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10473 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10474 DAG.getConstant(MaskValue, MVT::i32));
10475 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10478 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10479 // A vselect where all conditions and data are constants can be optimized into
10480 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10481 if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10482 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10483 ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10486 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10487 if (BlendOp.getNode())
10490 // Some types for vselect were previously set to Expand, not Legal or
10491 // Custom. Return an empty SDValue so we fall-through to Expand, after
10492 // the Custom lowering phase.
10493 MVT VT = Op.getSimpleValueType();
10494 switch (VT.SimpleTy) {
10499 if (Subtarget->hasBWI() && Subtarget->hasVLX())
10504 // We couldn't create a "Blend with immediate" node.
10505 // This node should still be legal, but we'll have to emit a blendv*
10510 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10511 MVT VT = Op.getSimpleValueType();
10514 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10517 if (VT.getSizeInBits() == 8) {
10518 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10519 Op.getOperand(0), Op.getOperand(1));
10520 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10521 DAG.getValueType(VT));
10522 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10525 if (VT.getSizeInBits() == 16) {
10526 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10527 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10529 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10530 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10531 DAG.getNode(ISD::BITCAST, dl,
10534 Op.getOperand(1)));
10535 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10536 Op.getOperand(0), Op.getOperand(1));
10537 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10538 DAG.getValueType(VT));
10539 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10542 if (VT == MVT::f32) {
10543 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10544 // the result back to FR32 register. It's only worth matching if the
10545 // result has a single use which is a store or a bitcast to i32. And in
10546 // the case of a store, it's not worth it if the index is a constant 0,
10547 // because a MOVSSmr can be used instead, which is smaller and faster.
10548 if (!Op.hasOneUse())
10550 SDNode *User = *Op.getNode()->use_begin();
10551 if ((User->getOpcode() != ISD::STORE ||
10552 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10553 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10554 (User->getOpcode() != ISD::BITCAST ||
10555 User->getValueType(0) != MVT::i32))
10557 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10558 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10561 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10564 if (VT == MVT::i32 || VT == MVT::i64) {
10565 // ExtractPS/pextrq works with constant index.
10566 if (isa<ConstantSDNode>(Op.getOperand(1)))
10572 /// Extract one bit from mask vector, like v16i1 or v8i1.
10573 /// AVX-512 feature.
10575 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10576 SDValue Vec = Op.getOperand(0);
10578 MVT VecVT = Vec.getSimpleValueType();
10579 SDValue Idx = Op.getOperand(1);
10580 MVT EltVT = Op.getSimpleValueType();
10582 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10584 // variable index can't be handled in mask registers,
10585 // extend vector to VR512
10586 if (!isa<ConstantSDNode>(Idx)) {
10587 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10588 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10589 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10590 ExtVT.getVectorElementType(), Ext, Idx);
10591 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10594 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10595 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10596 unsigned MaxSift = rc->getSize()*8 - 1;
10597 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10598 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10599 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10600 DAG.getConstant(MaxSift, MVT::i8));
10601 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10602 DAG.getIntPtrConstant(0));
10606 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10607 SelectionDAG &DAG) const {
10609 SDValue Vec = Op.getOperand(0);
10610 MVT VecVT = Vec.getSimpleValueType();
10611 SDValue Idx = Op.getOperand(1);
10613 if (Op.getSimpleValueType() == MVT::i1)
10614 return ExtractBitFromMaskVector(Op, DAG);
10616 if (!isa<ConstantSDNode>(Idx)) {
10617 if (VecVT.is512BitVector() ||
10618 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10619 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10622 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10623 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10624 MaskEltVT.getSizeInBits());
10626 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10627 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10628 getZeroVector(MaskVT, Subtarget, DAG, dl),
10629 Idx, DAG.getConstant(0, getPointerTy()));
10630 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10631 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10632 Perm, DAG.getConstant(0, getPointerTy()));
10637 // If this is a 256-bit vector result, first extract the 128-bit vector and
10638 // then extract the element from the 128-bit vector.
10639 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10641 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10642 // Get the 128-bit vector.
10643 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10644 MVT EltVT = VecVT.getVectorElementType();
10646 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10648 //if (IdxVal >= NumElems/2)
10649 // IdxVal -= NumElems/2;
10650 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10651 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10652 DAG.getConstant(IdxVal, MVT::i32));
10655 assert(VecVT.is128BitVector() && "Unexpected vector length");
10657 if (Subtarget->hasSSE41()) {
10658 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10663 MVT VT = Op.getSimpleValueType();
10664 // TODO: handle v16i8.
10665 if (VT.getSizeInBits() == 16) {
10666 SDValue Vec = Op.getOperand(0);
10667 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10669 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10670 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10671 DAG.getNode(ISD::BITCAST, dl,
10673 Op.getOperand(1)));
10674 // Transform it so it match pextrw which produces a 32-bit result.
10675 MVT EltVT = MVT::i32;
10676 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10677 Op.getOperand(0), Op.getOperand(1));
10678 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10679 DAG.getValueType(VT));
10680 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10683 if (VT.getSizeInBits() == 32) {
10684 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10688 // SHUFPS the element to the lowest double word, then movss.
10689 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10690 MVT VVT = Op.getOperand(0).getSimpleValueType();
10691 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10692 DAG.getUNDEF(VVT), Mask);
10693 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10694 DAG.getIntPtrConstant(0));
10697 if (VT.getSizeInBits() == 64) {
10698 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10699 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10700 // to match extract_elt for f64.
10701 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10705 // UNPCKHPD the element to the lowest double word, then movsd.
10706 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10707 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10708 int Mask[2] = { 1, -1 };
10709 MVT VVT = Op.getOperand(0).getSimpleValueType();
10710 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10711 DAG.getUNDEF(VVT), Mask);
10712 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10713 DAG.getIntPtrConstant(0));
10719 /// Insert one bit to mask vector, like v16i1 or v8i1.
10720 /// AVX-512 feature.
10722 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10724 SDValue Vec = Op.getOperand(0);
10725 SDValue Elt = Op.getOperand(1);
10726 SDValue Idx = Op.getOperand(2);
10727 MVT VecVT = Vec.getSimpleValueType();
10729 if (!isa<ConstantSDNode>(Idx)) {
10730 // Non constant index. Extend source and destination,
10731 // insert element and then truncate the result.
10732 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10733 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10734 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10735 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10736 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10737 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10740 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10741 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10742 if (Vec.getOpcode() == ISD::UNDEF)
10743 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10744 DAG.getConstant(IdxVal, MVT::i8));
10745 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10746 unsigned MaxSift = rc->getSize()*8 - 1;
10747 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10748 DAG.getConstant(MaxSift, MVT::i8));
10749 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10750 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10751 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10754 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10755 SelectionDAG &DAG) const {
10756 MVT VT = Op.getSimpleValueType();
10757 MVT EltVT = VT.getVectorElementType();
10759 if (EltVT == MVT::i1)
10760 return InsertBitToMaskVector(Op, DAG);
10763 SDValue N0 = Op.getOperand(0);
10764 SDValue N1 = Op.getOperand(1);
10765 SDValue N2 = Op.getOperand(2);
10766 if (!isa<ConstantSDNode>(N2))
10768 auto *N2C = cast<ConstantSDNode>(N2);
10769 unsigned IdxVal = N2C->getZExtValue();
10771 // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10772 // into that, and then insert the subvector back into the result.
10773 if (VT.is256BitVector() || VT.is512BitVector()) {
10774 // Get the desired 128-bit vector half.
10775 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10777 // Insert the element into the desired half.
10778 unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10779 unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10781 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10782 DAG.getConstant(IdxIn128, MVT::i32));
10784 // Insert the changed part back to the 256-bit vector
10785 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10787 assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10789 if (Subtarget->hasSSE41()) {
10790 if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10792 if (VT == MVT::v8i16) {
10793 Opc = X86ISD::PINSRW;
10795 assert(VT == MVT::v16i8);
10796 Opc = X86ISD::PINSRB;
10799 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10801 if (N1.getValueType() != MVT::i32)
10802 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10803 if (N2.getValueType() != MVT::i32)
10804 N2 = DAG.getIntPtrConstant(IdxVal);
10805 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10808 if (EltVT == MVT::f32) {
10809 // Bits [7:6] of the constant are the source select. This will always be
10810 // zero here. The DAG Combiner may combine an extract_elt index into
10812 // bits. For example (insert (extract, 3), 2) could be matched by
10814 // the '3' into bits [7:6] of X86ISD::INSERTPS.
10815 // Bits [5:4] of the constant are the destination select. This is the
10816 // value of the incoming immediate.
10817 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10818 // combine either bitwise AND or insert of float 0.0 to set these bits.
10819 N2 = DAG.getIntPtrConstant(IdxVal << 4);
10820 // Create this as a scalar to vector..
10821 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10822 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10825 if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10826 // PINSR* works with constant index.
10831 if (EltVT == MVT::i8)
10834 if (EltVT.getSizeInBits() == 16) {
10835 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10836 // as its second argument.
10837 if (N1.getValueType() != MVT::i32)
10838 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10839 if (N2.getValueType() != MVT::i32)
10840 N2 = DAG.getIntPtrConstant(IdxVal);
10841 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10846 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10848 MVT OpVT = Op.getSimpleValueType();
10850 // If this is a 256-bit vector result, first insert into a 128-bit
10851 // vector and then insert into the 256-bit vector.
10852 if (!OpVT.is128BitVector()) {
10853 // Insert into a 128-bit vector.
10854 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10855 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10856 OpVT.getVectorNumElements() / SizeFactor);
10858 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10860 // Insert the 128-bit vector.
10861 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10864 if (OpVT == MVT::v1i64 &&
10865 Op.getOperand(0).getValueType() == MVT::i64)
10866 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10868 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10869 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10870 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10871 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10874 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10875 // a simple subregister reference or explicit instructions to grab
10876 // upper bits of a vector.
10877 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10878 SelectionDAG &DAG) {
10880 SDValue In = Op.getOperand(0);
10881 SDValue Idx = Op.getOperand(1);
10882 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10883 MVT ResVT = Op.getSimpleValueType();
10884 MVT InVT = In.getSimpleValueType();
10886 if (Subtarget->hasFp256()) {
10887 if (ResVT.is128BitVector() &&
10888 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10889 isa<ConstantSDNode>(Idx)) {
10890 return Extract128BitVector(In, IdxVal, DAG, dl);
10892 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10893 isa<ConstantSDNode>(Idx)) {
10894 return Extract256BitVector(In, IdxVal, DAG, dl);
10900 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10901 // simple superregister reference or explicit instructions to insert
10902 // the upper bits of a vector.
10903 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10904 SelectionDAG &DAG) {
10905 if (Subtarget->hasFp256()) {
10906 SDLoc dl(Op.getNode());
10907 SDValue Vec = Op.getNode()->getOperand(0);
10908 SDValue SubVec = Op.getNode()->getOperand(1);
10909 SDValue Idx = Op.getNode()->getOperand(2);
10911 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10912 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10913 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10914 isa<ConstantSDNode>(Idx)) {
10915 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10916 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10919 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10920 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10921 isa<ConstantSDNode>(Idx)) {
10922 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10923 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10929 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10930 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10931 // one of the above mentioned nodes. It has to be wrapped because otherwise
10932 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10933 // be used to form addressing mode. These wrapped nodes will be selected
10936 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10937 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10939 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10940 // global base reg.
10941 unsigned char OpFlag = 0;
10942 unsigned WrapperKind = X86ISD::Wrapper;
10943 CodeModel::Model M = DAG.getTarget().getCodeModel();
10945 if (Subtarget->isPICStyleRIPRel() &&
10946 (M == CodeModel::Small || M == CodeModel::Kernel))
10947 WrapperKind = X86ISD::WrapperRIP;
10948 else if (Subtarget->isPICStyleGOT())
10949 OpFlag = X86II::MO_GOTOFF;
10950 else if (Subtarget->isPICStyleStubPIC())
10951 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10953 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10954 CP->getAlignment(),
10955 CP->getOffset(), OpFlag);
10957 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10958 // With PIC, the address is actually $g + Offset.
10960 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10961 DAG.getNode(X86ISD::GlobalBaseReg,
10962 SDLoc(), getPointerTy()),
10969 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10970 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10972 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10973 // global base reg.
10974 unsigned char OpFlag = 0;
10975 unsigned WrapperKind = X86ISD::Wrapper;
10976 CodeModel::Model M = DAG.getTarget().getCodeModel();
10978 if (Subtarget->isPICStyleRIPRel() &&
10979 (M == CodeModel::Small || M == CodeModel::Kernel))
10980 WrapperKind = X86ISD::WrapperRIP;
10981 else if (Subtarget->isPICStyleGOT())
10982 OpFlag = X86II::MO_GOTOFF;
10983 else if (Subtarget->isPICStyleStubPIC())
10984 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10986 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10989 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10991 // With PIC, the address is actually $g + Offset.
10993 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10994 DAG.getNode(X86ISD::GlobalBaseReg,
10995 SDLoc(), getPointerTy()),
11002 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11003 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11005 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11006 // global base reg.
11007 unsigned char OpFlag = 0;
11008 unsigned WrapperKind = X86ISD::Wrapper;
11009 CodeModel::Model M = DAG.getTarget().getCodeModel();
11011 if (Subtarget->isPICStyleRIPRel() &&
11012 (M == CodeModel::Small || M == CodeModel::Kernel)) {
11013 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11014 OpFlag = X86II::MO_GOTPCREL;
11015 WrapperKind = X86ISD::WrapperRIP;
11016 } else if (Subtarget->isPICStyleGOT()) {
11017 OpFlag = X86II::MO_GOT;
11018 } else if (Subtarget->isPICStyleStubPIC()) {
11019 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11020 } else if (Subtarget->isPICStyleStubNoDynamic()) {
11021 OpFlag = X86II::MO_DARWIN_NONLAZY;
11024 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11027 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11029 // With PIC, the address is actually $g + Offset.
11030 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11031 !Subtarget->is64Bit()) {
11032 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11033 DAG.getNode(X86ISD::GlobalBaseReg,
11034 SDLoc(), getPointerTy()),
11038 // For symbols that require a load from a stub to get the address, emit the
11040 if (isGlobalStubReference(OpFlag))
11041 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11042 MachinePointerInfo::getGOT(), false, false, false, 0);
11048 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11049 // Create the TargetBlockAddressAddress node.
11050 unsigned char OpFlags =
11051 Subtarget->ClassifyBlockAddressReference();
11052 CodeModel::Model M = DAG.getTarget().getCodeModel();
11053 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11054 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11056 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11059 if (Subtarget->isPICStyleRIPRel() &&
11060 (M == CodeModel::Small || M == CodeModel::Kernel))
11061 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11063 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11065 // With PIC, the address is actually $g + Offset.
11066 if (isGlobalRelativeToPICBase(OpFlags)) {
11067 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11068 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11076 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11077 int64_t Offset, SelectionDAG &DAG) const {
11078 // Create the TargetGlobalAddress node, folding in the constant
11079 // offset if it is legal.
11080 unsigned char OpFlags =
11081 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11082 CodeModel::Model M = DAG.getTarget().getCodeModel();
11084 if (OpFlags == X86II::MO_NO_FLAG &&
11085 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11086 // A direct static reference to a global.
11087 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11090 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11093 if (Subtarget->isPICStyleRIPRel() &&
11094 (M == CodeModel::Small || M == CodeModel::Kernel))
11095 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11097 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11099 // With PIC, the address is actually $g + Offset.
11100 if (isGlobalRelativeToPICBase(OpFlags)) {
11101 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11102 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11106 // For globals that require a load from a stub to get the address, emit the
11108 if (isGlobalStubReference(OpFlags))
11109 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11110 MachinePointerInfo::getGOT(), false, false, false, 0);
11112 // If there was a non-zero offset that we didn't fold, create an explicit
11113 // addition for it.
11115 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11116 DAG.getConstant(Offset, getPointerTy()));
11122 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11123 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11124 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11125 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11129 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11130 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11131 unsigned char OperandFlags, bool LocalDynamic = false) {
11132 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11133 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11135 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11136 GA->getValueType(0),
11140 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11144 SDValue Ops[] = { Chain, TGA, *InFlag };
11145 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11147 SDValue Ops[] = { Chain, TGA };
11148 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11151 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11152 MFI->setAdjustsStack(true);
11154 SDValue Flag = Chain.getValue(1);
11155 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11158 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11160 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11163 SDLoc dl(GA); // ? function entry point might be better
11164 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11165 DAG.getNode(X86ISD::GlobalBaseReg,
11166 SDLoc(), PtrVT), InFlag);
11167 InFlag = Chain.getValue(1);
11169 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11172 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11174 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11176 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11177 X86::RAX, X86II::MO_TLSGD);
11180 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11186 // Get the start address of the TLS block for this module.
11187 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11188 .getInfo<X86MachineFunctionInfo>();
11189 MFI->incNumLocalDynamicTLSAccesses();
11193 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11194 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11197 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11198 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11199 InFlag = Chain.getValue(1);
11200 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11201 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11204 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11208 unsigned char OperandFlags = X86II::MO_DTPOFF;
11209 unsigned WrapperKind = X86ISD::Wrapper;
11210 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11211 GA->getValueType(0),
11212 GA->getOffset(), OperandFlags);
11213 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11215 // Add x@dtpoff with the base.
11216 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11219 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11220 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11221 const EVT PtrVT, TLSModel::Model model,
11222 bool is64Bit, bool isPIC) {
11225 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11226 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11227 is64Bit ? 257 : 256));
11229 SDValue ThreadPointer =
11230 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11231 MachinePointerInfo(Ptr), false, false, false, 0);
11233 unsigned char OperandFlags = 0;
11234 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11236 unsigned WrapperKind = X86ISD::Wrapper;
11237 if (model == TLSModel::LocalExec) {
11238 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11239 } else if (model == TLSModel::InitialExec) {
11241 OperandFlags = X86II::MO_GOTTPOFF;
11242 WrapperKind = X86ISD::WrapperRIP;
11244 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11247 llvm_unreachable("Unexpected model");
11250 // emit "addl x@ntpoff,%eax" (local exec)
11251 // or "addl x@indntpoff,%eax" (initial exec)
11252 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11254 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11255 GA->getOffset(), OperandFlags);
11256 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11258 if (model == TLSModel::InitialExec) {
11259 if (isPIC && !is64Bit) {
11260 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11261 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11265 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11266 MachinePointerInfo::getGOT(), false, false, false, 0);
11269 // The address of the thread local variable is the add of the thread
11270 // pointer with the offset of the variable.
11271 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11275 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11277 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11278 const GlobalValue *GV = GA->getGlobal();
11280 if (Subtarget->isTargetELF()) {
11281 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11284 case TLSModel::GeneralDynamic:
11285 if (Subtarget->is64Bit())
11286 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11287 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11288 case TLSModel::LocalDynamic:
11289 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11290 Subtarget->is64Bit());
11291 case TLSModel::InitialExec:
11292 case TLSModel::LocalExec:
11293 return LowerToTLSExecModel(
11294 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11295 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11297 llvm_unreachable("Unknown TLS model.");
11300 if (Subtarget->isTargetDarwin()) {
11301 // Darwin only has one model of TLS. Lower to that.
11302 unsigned char OpFlag = 0;
11303 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11304 X86ISD::WrapperRIP : X86ISD::Wrapper;
11306 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11307 // global base reg.
11308 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11309 !Subtarget->is64Bit();
11311 OpFlag = X86II::MO_TLVP_PIC_BASE;
11313 OpFlag = X86II::MO_TLVP;
11315 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11316 GA->getValueType(0),
11317 GA->getOffset(), OpFlag);
11318 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11320 // With PIC32, the address is actually $g + Offset.
11322 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11323 DAG.getNode(X86ISD::GlobalBaseReg,
11324 SDLoc(), getPointerTy()),
11327 // Lowering the machine isd will make sure everything is in the right
11329 SDValue Chain = DAG.getEntryNode();
11330 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11331 SDValue Args[] = { Chain, Offset };
11332 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11334 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11335 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11336 MFI->setAdjustsStack(true);
11338 // And our return value (tls address) is in the standard call return value
11340 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11341 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11342 Chain.getValue(1));
11345 if (Subtarget->isTargetKnownWindowsMSVC() ||
11346 Subtarget->isTargetWindowsGNU()) {
11347 // Just use the implicit TLS architecture
11348 // Need to generate someting similar to:
11349 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11351 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11352 // mov rcx, qword [rdx+rcx*8]
11353 // mov eax, .tls$:tlsvar
11354 // [rax+rcx] contains the address
11355 // Windows 64bit: gs:0x58
11356 // Windows 32bit: fs:__tls_array
11359 SDValue Chain = DAG.getEntryNode();
11361 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11362 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11363 // use its literal value of 0x2C.
11364 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11365 ? Type::getInt8PtrTy(*DAG.getContext(),
11367 : Type::getInt32PtrTy(*DAG.getContext(),
11371 Subtarget->is64Bit()
11372 ? DAG.getIntPtrConstant(0x58)
11373 : (Subtarget->isTargetWindowsGNU()
11374 ? DAG.getIntPtrConstant(0x2C)
11375 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11377 SDValue ThreadPointer =
11378 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11379 MachinePointerInfo(Ptr), false, false, false, 0);
11381 // Load the _tls_index variable
11382 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11383 if (Subtarget->is64Bit())
11384 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11385 IDX, MachinePointerInfo(), MVT::i32,
11386 false, false, false, 0);
11388 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11389 false, false, false, 0);
11391 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11393 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11395 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11396 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11397 false, false, false, 0);
11399 // Get the offset of start of .tls section
11400 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11401 GA->getValueType(0),
11402 GA->getOffset(), X86II::MO_SECREL);
11403 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11405 // The address of the thread local variable is the add of the thread
11406 // pointer with the offset of the variable.
11407 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11410 llvm_unreachable("TLS not implemented for this target.");
11413 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11414 /// and take a 2 x i32 value to shift plus a shift amount.
11415 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11416 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11417 MVT VT = Op.getSimpleValueType();
11418 unsigned VTBits = VT.getSizeInBits();
11420 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11421 SDValue ShOpLo = Op.getOperand(0);
11422 SDValue ShOpHi = Op.getOperand(1);
11423 SDValue ShAmt = Op.getOperand(2);
11424 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11425 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11427 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11428 DAG.getConstant(VTBits - 1, MVT::i8));
11429 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11430 DAG.getConstant(VTBits - 1, MVT::i8))
11431 : DAG.getConstant(0, VT);
11433 SDValue Tmp2, Tmp3;
11434 if (Op.getOpcode() == ISD::SHL_PARTS) {
11435 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11436 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11438 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11439 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11442 // If the shift amount is larger or equal than the width of a part we can't
11443 // rely on the results of shld/shrd. Insert a test and select the appropriate
11444 // values for large shift amounts.
11445 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11446 DAG.getConstant(VTBits, MVT::i8));
11447 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11448 AndNode, DAG.getConstant(0, MVT::i8));
11451 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11452 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11453 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11455 if (Op.getOpcode() == ISD::SHL_PARTS) {
11456 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11457 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11459 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11460 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11463 SDValue Ops[2] = { Lo, Hi };
11464 return DAG.getMergeValues(Ops, dl);
11467 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11468 SelectionDAG &DAG) const {
11469 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11471 if (SrcVT.isVector())
11474 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11475 "Unknown SINT_TO_FP to lower!");
11477 // These are really Legal; return the operand so the caller accepts it as
11479 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11481 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11482 Subtarget->is64Bit()) {
11487 unsigned Size = SrcVT.getSizeInBits()/8;
11488 MachineFunction &MF = DAG.getMachineFunction();
11489 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11490 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11491 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11493 MachinePointerInfo::getFixedStack(SSFI),
11495 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11498 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11500 SelectionDAG &DAG) const {
11504 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11506 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11508 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11510 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11512 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11513 MachineMemOperand *MMO;
11515 int SSFI = FI->getIndex();
11517 DAG.getMachineFunction()
11518 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11519 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11521 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11522 StackSlot = StackSlot.getOperand(1);
11524 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11525 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11527 Tys, Ops, SrcVT, MMO);
11530 Chain = Result.getValue(1);
11531 SDValue InFlag = Result.getValue(2);
11533 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11534 // shouldn't be necessary except that RFP cannot be live across
11535 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11536 MachineFunction &MF = DAG.getMachineFunction();
11537 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11538 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11539 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11540 Tys = DAG.getVTList(MVT::Other);
11542 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11544 MachineMemOperand *MMO =
11545 DAG.getMachineFunction()
11546 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11547 MachineMemOperand::MOStore, SSFISize, SSFISize);
11549 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11550 Ops, Op.getValueType(), MMO);
11551 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11552 MachinePointerInfo::getFixedStack(SSFI),
11553 false, false, false, 0);
11559 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11560 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11561 SelectionDAG &DAG) const {
11562 // This algorithm is not obvious. Here it is what we're trying to output:
11565 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11566 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11568 haddpd %xmm0, %xmm0
11570 pshufd $0x4e, %xmm0, %xmm1
11576 LLVMContext *Context = DAG.getContext();
11578 // Build some magic constants.
11579 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11580 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11581 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11583 SmallVector<Constant*,2> CV1;
11585 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11586 APInt(64, 0x4330000000000000ULL))));
11588 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11589 APInt(64, 0x4530000000000000ULL))));
11590 Constant *C1 = ConstantVector::get(CV1);
11591 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11593 // Load the 64-bit value into an XMM register.
11594 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11596 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11597 MachinePointerInfo::getConstantPool(),
11598 false, false, false, 16);
11599 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11600 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11603 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11604 MachinePointerInfo::getConstantPool(),
11605 false, false, false, 16);
11606 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11607 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11610 if (Subtarget->hasSSE3()) {
11611 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11612 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11614 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11615 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11617 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11618 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11622 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11623 DAG.getIntPtrConstant(0));
11626 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11627 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11628 SelectionDAG &DAG) const {
11630 // FP constant to bias correct the final result.
11631 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11634 // Load the 32-bit value into an XMM register.
11635 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11638 // Zero out the upper parts of the register.
11639 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11641 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11642 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11643 DAG.getIntPtrConstant(0));
11645 // Or the load with the bias.
11646 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11647 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11648 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11649 MVT::v2f64, Load)),
11650 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11651 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11652 MVT::v2f64, Bias)));
11653 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11654 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11655 DAG.getIntPtrConstant(0));
11657 // Subtract the bias.
11658 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11660 // Handle final rounding.
11661 EVT DestVT = Op.getValueType();
11663 if (DestVT.bitsLT(MVT::f64))
11664 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11665 DAG.getIntPtrConstant(0));
11666 if (DestVT.bitsGT(MVT::f64))
11667 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11669 // Handle final rounding.
11673 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11674 SelectionDAG &DAG) const {
11675 SDValue N0 = Op.getOperand(0);
11676 MVT SVT = N0.getSimpleValueType();
11679 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11680 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11681 "Custom UINT_TO_FP is not supported!");
11683 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11684 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11685 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11688 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11689 SelectionDAG &DAG) const {
11690 SDValue N0 = Op.getOperand(0);
11693 if (Op.getValueType().isVector())
11694 return lowerUINT_TO_FP_vec(Op, DAG);
11696 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11697 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11698 // the optimization here.
11699 if (DAG.SignBitIsZero(N0))
11700 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11702 MVT SrcVT = N0.getSimpleValueType();
11703 MVT DstVT = Op.getSimpleValueType();
11704 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11705 return LowerUINT_TO_FP_i64(Op, DAG);
11706 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11707 return LowerUINT_TO_FP_i32(Op, DAG);
11708 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11711 // Make a 64-bit buffer, and use it to build an FILD.
11712 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11713 if (SrcVT == MVT::i32) {
11714 SDValue WordOff = DAG.getConstant(4, getPointerTy());
11715 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11716 getPointerTy(), StackSlot, WordOff);
11717 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11718 StackSlot, MachinePointerInfo(),
11720 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11721 OffsetSlot, MachinePointerInfo(),
11723 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11727 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11728 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11729 StackSlot, MachinePointerInfo(),
11731 // For i64 source, we need to add the appropriate power of 2 if the input
11732 // was negative. This is the same as the optimization in
11733 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11734 // we must be careful to do the computation in x87 extended precision, not
11735 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11736 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11737 MachineMemOperand *MMO =
11738 DAG.getMachineFunction()
11739 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11740 MachineMemOperand::MOLoad, 8, 8);
11742 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11743 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11744 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11747 APInt FF(32, 0x5F800000ULL);
11749 // Check whether the sign bit is set.
11750 SDValue SignSet = DAG.getSetCC(dl,
11751 getSetCCResultType(*DAG.getContext(), MVT::i64),
11752 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11755 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11756 SDValue FudgePtr = DAG.getConstantPool(
11757 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11760 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11761 SDValue Zero = DAG.getIntPtrConstant(0);
11762 SDValue Four = DAG.getIntPtrConstant(4);
11763 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11765 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11767 // Load the value out, extending it from f32 to f80.
11768 // FIXME: Avoid the extend by constructing the right constant pool?
11769 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11770 FudgePtr, MachinePointerInfo::getConstantPool(),
11771 MVT::f32, false, false, false, 4);
11772 // Extend everything to 80 bits to force it to be done on x87.
11773 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11774 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11777 std::pair<SDValue,SDValue>
11778 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11779 bool IsSigned, bool IsReplace) const {
11782 EVT DstTy = Op.getValueType();
11784 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11785 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11789 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11790 DstTy.getSimpleVT() >= MVT::i16 &&
11791 "Unknown FP_TO_INT to lower!");
11793 // These are really Legal.
11794 if (DstTy == MVT::i32 &&
11795 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11796 return std::make_pair(SDValue(), SDValue());
11797 if (Subtarget->is64Bit() &&
11798 DstTy == MVT::i64 &&
11799 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11800 return std::make_pair(SDValue(), SDValue());
11802 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11803 // stack slot, or into the FTOL runtime function.
11804 MachineFunction &MF = DAG.getMachineFunction();
11805 unsigned MemSize = DstTy.getSizeInBits()/8;
11806 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11807 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11810 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11811 Opc = X86ISD::WIN_FTOL;
11813 switch (DstTy.getSimpleVT().SimpleTy) {
11814 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11815 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11816 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11817 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11820 SDValue Chain = DAG.getEntryNode();
11821 SDValue Value = Op.getOperand(0);
11822 EVT TheVT = Op.getOperand(0).getValueType();
11823 // FIXME This causes a redundant load/store if the SSE-class value is already
11824 // in memory, such as if it is on the callstack.
11825 if (isScalarFPTypeInSSEReg(TheVT)) {
11826 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11827 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11828 MachinePointerInfo::getFixedStack(SSFI),
11830 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11832 Chain, StackSlot, DAG.getValueType(TheVT)
11835 MachineMemOperand *MMO =
11836 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11837 MachineMemOperand::MOLoad, MemSize, MemSize);
11838 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11839 Chain = Value.getValue(1);
11840 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11841 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11844 MachineMemOperand *MMO =
11845 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11846 MachineMemOperand::MOStore, MemSize, MemSize);
11848 if (Opc != X86ISD::WIN_FTOL) {
11849 // Build the FP_TO_INT*_IN_MEM
11850 SDValue Ops[] = { Chain, Value, StackSlot };
11851 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11853 return std::make_pair(FIST, StackSlot);
11855 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11856 DAG.getVTList(MVT::Other, MVT::Glue),
11858 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11859 MVT::i32, ftol.getValue(1));
11860 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11861 MVT::i32, eax.getValue(2));
11862 SDValue Ops[] = { eax, edx };
11863 SDValue pair = IsReplace
11864 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11865 : DAG.getMergeValues(Ops, DL);
11866 return std::make_pair(pair, SDValue());
11870 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11871 const X86Subtarget *Subtarget) {
11872 MVT VT = Op->getSimpleValueType(0);
11873 SDValue In = Op->getOperand(0);
11874 MVT InVT = In.getSimpleValueType();
11877 // Optimize vectors in AVX mode:
11880 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11881 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11882 // Concat upper and lower parts.
11885 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11886 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11887 // Concat upper and lower parts.
11890 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11891 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11892 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11895 if (Subtarget->hasInt256())
11896 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11898 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11899 SDValue Undef = DAG.getUNDEF(InVT);
11900 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11901 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11902 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11904 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11905 VT.getVectorNumElements()/2);
11907 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11908 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11910 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11913 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11914 SelectionDAG &DAG) {
11915 MVT VT = Op->getSimpleValueType(0);
11916 SDValue In = Op->getOperand(0);
11917 MVT InVT = In.getSimpleValueType();
11919 unsigned int NumElts = VT.getVectorNumElements();
11920 if (NumElts != 8 && NumElts != 16)
11923 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11924 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11926 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11927 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11928 // Now we have only mask extension
11929 assert(InVT.getVectorElementType() == MVT::i1);
11930 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11931 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11932 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11933 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11934 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11935 MachinePointerInfo::getConstantPool(),
11936 false, false, false, Alignment);
11938 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11939 if (VT.is512BitVector())
11941 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11944 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11945 SelectionDAG &DAG) {
11946 if (Subtarget->hasFp256()) {
11947 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11955 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11956 SelectionDAG &DAG) {
11958 MVT VT = Op.getSimpleValueType();
11959 SDValue In = Op.getOperand(0);
11960 MVT SVT = In.getSimpleValueType();
11962 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11963 return LowerZERO_EXTEND_AVX512(Op, DAG);
11965 if (Subtarget->hasFp256()) {
11966 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11971 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11972 VT.getVectorNumElements() != SVT.getVectorNumElements());
11976 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11978 MVT VT = Op.getSimpleValueType();
11979 SDValue In = Op.getOperand(0);
11980 MVT InVT = In.getSimpleValueType();
11982 if (VT == MVT::i1) {
11983 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11984 "Invalid scalar TRUNCATE operation");
11985 if (InVT.getSizeInBits() >= 32)
11987 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11988 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11990 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11991 "Invalid TRUNCATE operation");
11993 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11994 if (VT.getVectorElementType().getSizeInBits() >=8)
11995 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11997 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11998 unsigned NumElts = InVT.getVectorNumElements();
11999 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12000 if (InVT.getSizeInBits() < 512) {
12001 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12002 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12006 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
12007 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
12008 SDValue CP = DAG.getConstantPool(C, getPointerTy());
12009 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12010 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12011 MachinePointerInfo::getConstantPool(),
12012 false, false, false, Alignment);
12013 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
12014 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12015 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12018 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12019 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12020 if (Subtarget->hasInt256()) {
12021 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12022 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12023 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12025 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12026 DAG.getIntPtrConstant(0));
12029 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12030 DAG.getIntPtrConstant(0));
12031 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12032 DAG.getIntPtrConstant(2));
12033 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12034 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12035 static const int ShufMask[] = {0, 2, 4, 6};
12036 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12039 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12040 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12041 if (Subtarget->hasInt256()) {
12042 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12044 SmallVector<SDValue,32> pshufbMask;
12045 for (unsigned i = 0; i < 2; ++i) {
12046 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
12047 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
12048 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
12049 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
12050 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
12051 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
12052 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
12053 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
12054 for (unsigned j = 0; j < 8; ++j)
12055 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
12057 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12058 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12059 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12061 static const int ShufMask[] = {0, 2, -1, -1};
12062 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12064 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12065 DAG.getIntPtrConstant(0));
12066 return DAG.getNode(ISD::BITCAST, DL, VT, In);
12069 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12070 DAG.getIntPtrConstant(0));
12072 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12073 DAG.getIntPtrConstant(4));
12075 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12076 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12078 // The PSHUFB mask:
12079 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12080 -1, -1, -1, -1, -1, -1, -1, -1};
12082 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12083 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12084 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12086 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12087 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12089 // The MOVLHPS Mask:
12090 static const int ShufMask2[] = {0, 1, 4, 5};
12091 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12092 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12095 // Handle truncation of V256 to V128 using shuffles.
12096 if (!VT.is128BitVector() || !InVT.is256BitVector())
12099 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12101 unsigned NumElems = VT.getVectorNumElements();
12102 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12104 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12105 // Prepare truncation shuffle mask
12106 for (unsigned i = 0; i != NumElems; ++i)
12107 MaskVec[i] = i * 2;
12108 SDValue V = DAG.getVectorShuffle(NVT, DL,
12109 DAG.getNode(ISD::BITCAST, DL, NVT, In),
12110 DAG.getUNDEF(NVT), &MaskVec[0]);
12111 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12112 DAG.getIntPtrConstant(0));
12115 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12116 SelectionDAG &DAG) const {
12117 assert(!Op.getSimpleValueType().isVector());
12119 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12120 /*IsSigned=*/ true, /*IsReplace=*/ false);
12121 SDValue FIST = Vals.first, StackSlot = Vals.second;
12122 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12123 if (!FIST.getNode()) return Op;
12125 if (StackSlot.getNode())
12126 // Load the result.
12127 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12128 FIST, StackSlot, MachinePointerInfo(),
12129 false, false, false, 0);
12131 // The node is the result.
12135 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12136 SelectionDAG &DAG) const {
12137 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12138 /*IsSigned=*/ false, /*IsReplace=*/ false);
12139 SDValue FIST = Vals.first, StackSlot = Vals.second;
12140 assert(FIST.getNode() && "Unexpected failure");
12142 if (StackSlot.getNode())
12143 // Load the result.
12144 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12145 FIST, StackSlot, MachinePointerInfo(),
12146 false, false, false, 0);
12148 // The node is the result.
12152 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12154 MVT VT = Op.getSimpleValueType();
12155 SDValue In = Op.getOperand(0);
12156 MVT SVT = In.getSimpleValueType();
12158 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12160 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12161 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12162 In, DAG.getUNDEF(SVT)));
12165 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
12166 LLVMContext *Context = DAG.getContext();
12168 MVT VT = Op.getSimpleValueType();
12170 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12171 if (VT.isVector()) {
12172 EltVT = VT.getVectorElementType();
12173 NumElts = VT.getVectorNumElements();
12176 if (EltVT == MVT::f64)
12177 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12178 APInt(64, ~(1ULL << 63))));
12180 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12181 APInt(32, ~(1U << 31))));
12182 C = ConstantVector::getSplat(NumElts, C);
12183 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12184 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12185 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12186 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12187 MachinePointerInfo::getConstantPool(),
12188 false, false, false, Alignment);
12189 if (VT.isVector()) {
12190 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12191 return DAG.getNode(ISD::BITCAST, dl, VT,
12192 DAG.getNode(ISD::AND, dl, ANDVT,
12193 DAG.getNode(ISD::BITCAST, dl, ANDVT,
12195 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
12197 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
12200 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
12201 LLVMContext *Context = DAG.getContext();
12203 MVT VT = Op.getSimpleValueType();
12205 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12206 if (VT.isVector()) {
12207 EltVT = VT.getVectorElementType();
12208 NumElts = VT.getVectorNumElements();
12211 if (EltVT == MVT::f64)
12212 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12213 APInt(64, 1ULL << 63)));
12215 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12216 APInt(32, 1U << 31)));
12217 C = ConstantVector::getSplat(NumElts, C);
12218 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12219 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12220 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12221 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12222 MachinePointerInfo::getConstantPool(),
12223 false, false, false, Alignment);
12224 if (VT.isVector()) {
12225 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
12226 return DAG.getNode(ISD::BITCAST, dl, VT,
12227 DAG.getNode(ISD::XOR, dl, XORVT,
12228 DAG.getNode(ISD::BITCAST, dl, XORVT,
12230 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
12233 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
12236 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12237 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12238 LLVMContext *Context = DAG.getContext();
12239 SDValue Op0 = Op.getOperand(0);
12240 SDValue Op1 = Op.getOperand(1);
12242 MVT VT = Op.getSimpleValueType();
12243 MVT SrcVT = Op1.getSimpleValueType();
12245 // If second operand is smaller, extend it first.
12246 if (SrcVT.bitsLT(VT)) {
12247 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12250 // And if it is bigger, shrink it first.
12251 if (SrcVT.bitsGT(VT)) {
12252 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12256 // At this point the operands and the result should have the same
12257 // type, and that won't be f80 since that is not custom lowered.
12259 // First get the sign bit of second operand.
12260 SmallVector<Constant*,4> CV;
12261 if (SrcVT == MVT::f64) {
12262 const fltSemantics &Sem = APFloat::IEEEdouble;
12263 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
12264 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12266 const fltSemantics &Sem = APFloat::IEEEsingle;
12267 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
12268 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12269 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12270 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12272 Constant *C = ConstantVector::get(CV);
12273 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12274 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12275 MachinePointerInfo::getConstantPool(),
12276 false, false, false, 16);
12277 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12279 // Shift sign bit right or left if the two operands have different types.
12280 if (SrcVT.bitsGT(VT)) {
12281 // Op0 is MVT::f32, Op1 is MVT::f64.
12282 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
12283 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
12284 DAG.getConstant(32, MVT::i32));
12285 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
12286 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
12287 DAG.getIntPtrConstant(0));
12290 // Clear first operand sign bit.
12292 if (VT == MVT::f64) {
12293 const fltSemantics &Sem = APFloat::IEEEdouble;
12294 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12295 APInt(64, ~(1ULL << 63)))));
12296 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12298 const fltSemantics &Sem = APFloat::IEEEsingle;
12299 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12300 APInt(32, ~(1U << 31)))));
12301 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12302 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12303 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12305 C = ConstantVector::get(CV);
12306 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12307 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12308 MachinePointerInfo::getConstantPool(),
12309 false, false, false, 16);
12310 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
12312 // Or the value with the sign bit.
12313 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12316 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12317 SDValue N0 = Op.getOperand(0);
12319 MVT VT = Op.getSimpleValueType();
12321 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12322 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12323 DAG.getConstant(1, VT));
12324 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12327 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
12329 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12330 SelectionDAG &DAG) {
12331 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12333 if (!Subtarget->hasSSE41())
12336 if (!Op->hasOneUse())
12339 SDNode *N = Op.getNode();
12342 SmallVector<SDValue, 8> Opnds;
12343 DenseMap<SDValue, unsigned> VecInMap;
12344 SmallVector<SDValue, 8> VecIns;
12345 EVT VT = MVT::Other;
12347 // Recognize a special case where a vector is casted into wide integer to
12349 Opnds.push_back(N->getOperand(0));
12350 Opnds.push_back(N->getOperand(1));
12352 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12353 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12354 // BFS traverse all OR'd operands.
12355 if (I->getOpcode() == ISD::OR) {
12356 Opnds.push_back(I->getOperand(0));
12357 Opnds.push_back(I->getOperand(1));
12358 // Re-evaluate the number of nodes to be traversed.
12359 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12363 // Quit if a non-EXTRACT_VECTOR_ELT
12364 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12367 // Quit if without a constant index.
12368 SDValue Idx = I->getOperand(1);
12369 if (!isa<ConstantSDNode>(Idx))
12372 SDValue ExtractedFromVec = I->getOperand(0);
12373 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12374 if (M == VecInMap.end()) {
12375 VT = ExtractedFromVec.getValueType();
12376 // Quit if not 128/256-bit vector.
12377 if (!VT.is128BitVector() && !VT.is256BitVector())
12379 // Quit if not the same type.
12380 if (VecInMap.begin() != VecInMap.end() &&
12381 VT != VecInMap.begin()->first.getValueType())
12383 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12384 VecIns.push_back(ExtractedFromVec);
12386 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12389 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12390 "Not extracted from 128-/256-bit vector.");
12392 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12394 for (DenseMap<SDValue, unsigned>::const_iterator
12395 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12396 // Quit if not all elements are used.
12397 if (I->second != FullMask)
12401 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12403 // Cast all vectors into TestVT for PTEST.
12404 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12405 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12407 // If more than one full vectors are evaluated, OR them first before PTEST.
12408 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12409 // Each iteration will OR 2 nodes and append the result until there is only
12410 // 1 node left, i.e. the final OR'd value of all vectors.
12411 SDValue LHS = VecIns[Slot];
12412 SDValue RHS = VecIns[Slot + 1];
12413 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12416 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12417 VecIns.back(), VecIns.back());
12420 /// \brief return true if \c Op has a use that doesn't just read flags.
12421 static bool hasNonFlagsUse(SDValue Op) {
12422 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12424 SDNode *User = *UI;
12425 unsigned UOpNo = UI.getOperandNo();
12426 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12427 // Look pass truncate.
12428 UOpNo = User->use_begin().getOperandNo();
12429 User = *User->use_begin();
12432 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12433 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12439 /// Emit nodes that will be selected as "test Op0,Op0", or something
12441 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12442 SelectionDAG &DAG) const {
12443 if (Op.getValueType() == MVT::i1)
12444 // KORTEST instruction should be selected
12445 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12446 DAG.getConstant(0, Op.getValueType()));
12448 // CF and OF aren't always set the way we want. Determine which
12449 // of these we need.
12450 bool NeedCF = false;
12451 bool NeedOF = false;
12454 case X86::COND_A: case X86::COND_AE:
12455 case X86::COND_B: case X86::COND_BE:
12458 case X86::COND_G: case X86::COND_GE:
12459 case X86::COND_L: case X86::COND_LE:
12460 case X86::COND_O: case X86::COND_NO: {
12461 // Check if we really need to set the
12462 // Overflow flag. If NoSignedWrap is present
12463 // that is not actually needed.
12464 switch (Op->getOpcode()) {
12469 const BinaryWithFlagsSDNode *BinNode =
12470 cast<BinaryWithFlagsSDNode>(Op.getNode());
12471 if (BinNode->hasNoSignedWrap())
12481 // See if we can use the EFLAGS value from the operand instead of
12482 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12483 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12484 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12485 // Emit a CMP with 0, which is the TEST pattern.
12486 //if (Op.getValueType() == MVT::i1)
12487 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12488 // DAG.getConstant(0, MVT::i1));
12489 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12490 DAG.getConstant(0, Op.getValueType()));
12492 unsigned Opcode = 0;
12493 unsigned NumOperands = 0;
12495 // Truncate operations may prevent the merge of the SETCC instruction
12496 // and the arithmetic instruction before it. Attempt to truncate the operands
12497 // of the arithmetic instruction and use a reduced bit-width instruction.
12498 bool NeedTruncation = false;
12499 SDValue ArithOp = Op;
12500 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12501 SDValue Arith = Op->getOperand(0);
12502 // Both the trunc and the arithmetic op need to have one user each.
12503 if (Arith->hasOneUse())
12504 switch (Arith.getOpcode()) {
12511 NeedTruncation = true;
12517 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12518 // which may be the result of a CAST. We use the variable 'Op', which is the
12519 // non-casted variable when we check for possible users.
12520 switch (ArithOp.getOpcode()) {
12522 // Due to an isel shortcoming, be conservative if this add is likely to be
12523 // selected as part of a load-modify-store instruction. When the root node
12524 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12525 // uses of other nodes in the match, such as the ADD in this case. This
12526 // leads to the ADD being left around and reselected, with the result being
12527 // two adds in the output. Alas, even if none our users are stores, that
12528 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12529 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12530 // climbing the DAG back to the root, and it doesn't seem to be worth the
12532 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12533 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12534 if (UI->getOpcode() != ISD::CopyToReg &&
12535 UI->getOpcode() != ISD::SETCC &&
12536 UI->getOpcode() != ISD::STORE)
12539 if (ConstantSDNode *C =
12540 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12541 // An add of one will be selected as an INC.
12542 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12543 Opcode = X86ISD::INC;
12548 // An add of negative one (subtract of one) will be selected as a DEC.
12549 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12550 Opcode = X86ISD::DEC;
12556 // Otherwise use a regular EFLAGS-setting add.
12557 Opcode = X86ISD::ADD;
12562 // If we have a constant logical shift that's only used in a comparison
12563 // against zero turn it into an equivalent AND. This allows turning it into
12564 // a TEST instruction later.
12565 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12566 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12567 EVT VT = Op.getValueType();
12568 unsigned BitWidth = VT.getSizeInBits();
12569 unsigned ShAmt = Op->getConstantOperandVal(1);
12570 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12572 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12573 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12574 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12575 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12577 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12578 DAG.getConstant(Mask, VT));
12579 DAG.ReplaceAllUsesWith(Op, New);
12585 // If the primary and result isn't used, don't bother using X86ISD::AND,
12586 // because a TEST instruction will be better.
12587 if (!hasNonFlagsUse(Op))
12593 // Due to the ISEL shortcoming noted above, be conservative if this op is
12594 // likely to be selected as part of a load-modify-store instruction.
12595 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12596 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12597 if (UI->getOpcode() == ISD::STORE)
12600 // Otherwise use a regular EFLAGS-setting instruction.
12601 switch (ArithOp.getOpcode()) {
12602 default: llvm_unreachable("unexpected operator!");
12603 case ISD::SUB: Opcode = X86ISD::SUB; break;
12604 case ISD::XOR: Opcode = X86ISD::XOR; break;
12605 case ISD::AND: Opcode = X86ISD::AND; break;
12607 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12608 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12609 if (EFLAGS.getNode())
12612 Opcode = X86ISD::OR;
12626 return SDValue(Op.getNode(), 1);
12632 // If we found that truncation is beneficial, perform the truncation and
12634 if (NeedTruncation) {
12635 EVT VT = Op.getValueType();
12636 SDValue WideVal = Op->getOperand(0);
12637 EVT WideVT = WideVal.getValueType();
12638 unsigned ConvertedOp = 0;
12639 // Use a target machine opcode to prevent further DAGCombine
12640 // optimizations that may separate the arithmetic operations
12641 // from the setcc node.
12642 switch (WideVal.getOpcode()) {
12644 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12645 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12646 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12647 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12648 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12652 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12653 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12654 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12655 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12656 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12662 // Emit a CMP with 0, which is the TEST pattern.
12663 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12664 DAG.getConstant(0, Op.getValueType()));
12666 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12667 SmallVector<SDValue, 4> Ops;
12668 for (unsigned i = 0; i != NumOperands; ++i)
12669 Ops.push_back(Op.getOperand(i));
12671 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12672 DAG.ReplaceAllUsesWith(Op, New);
12673 return SDValue(New.getNode(), 1);
12676 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12678 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12679 SDLoc dl, SelectionDAG &DAG) const {
12680 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12681 if (C->getAPIntValue() == 0)
12682 return EmitTest(Op0, X86CC, dl, DAG);
12684 if (Op0.getValueType() == MVT::i1)
12685 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12688 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12689 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12690 // Do the comparison at i32 if it's smaller, besides the Atom case.
12691 // This avoids subregister aliasing issues. Keep the smaller reference
12692 // if we're optimizing for size, however, as that'll allow better folding
12693 // of memory operations.
12694 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12695 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12696 AttributeSet::FunctionIndex, Attribute::MinSize) &&
12697 !Subtarget->isAtom()) {
12698 unsigned ExtendOp =
12699 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12700 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12701 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12703 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12704 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12705 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12707 return SDValue(Sub.getNode(), 1);
12709 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12712 /// Convert a comparison if required by the subtarget.
12713 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12714 SelectionDAG &DAG) const {
12715 // If the subtarget does not support the FUCOMI instruction, floating-point
12716 // comparisons have to be converted.
12717 if (Subtarget->hasCMov() ||
12718 Cmp.getOpcode() != X86ISD::CMP ||
12719 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12720 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12723 // The instruction selector will select an FUCOM instruction instead of
12724 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12725 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12726 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12728 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12729 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12730 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12731 DAG.getConstant(8, MVT::i8));
12732 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12733 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12736 static bool isAllOnes(SDValue V) {
12737 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12738 return C && C->isAllOnesValue();
12741 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12742 /// if it's possible.
12743 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12744 SDLoc dl, SelectionDAG &DAG) const {
12745 SDValue Op0 = And.getOperand(0);
12746 SDValue Op1 = And.getOperand(1);
12747 if (Op0.getOpcode() == ISD::TRUNCATE)
12748 Op0 = Op0.getOperand(0);
12749 if (Op1.getOpcode() == ISD::TRUNCATE)
12750 Op1 = Op1.getOperand(0);
12753 if (Op1.getOpcode() == ISD::SHL)
12754 std::swap(Op0, Op1);
12755 if (Op0.getOpcode() == ISD::SHL) {
12756 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12757 if (And00C->getZExtValue() == 1) {
12758 // If we looked past a truncate, check that it's only truncating away
12760 unsigned BitWidth = Op0.getValueSizeInBits();
12761 unsigned AndBitWidth = And.getValueSizeInBits();
12762 if (BitWidth > AndBitWidth) {
12764 DAG.computeKnownBits(Op0, Zeros, Ones);
12765 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12769 RHS = Op0.getOperand(1);
12771 } else if (Op1.getOpcode() == ISD::Constant) {
12772 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12773 uint64_t AndRHSVal = AndRHS->getZExtValue();
12774 SDValue AndLHS = Op0;
12776 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12777 LHS = AndLHS.getOperand(0);
12778 RHS = AndLHS.getOperand(1);
12781 // Use BT if the immediate can't be encoded in a TEST instruction.
12782 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12784 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12788 if (LHS.getNode()) {
12789 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12790 // instruction. Since the shift amount is in-range-or-undefined, we know
12791 // that doing a bittest on the i32 value is ok. We extend to i32 because
12792 // the encoding for the i16 version is larger than the i32 version.
12793 // Also promote i16 to i32 for performance / code size reason.
12794 if (LHS.getValueType() == MVT::i8 ||
12795 LHS.getValueType() == MVT::i16)
12796 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12798 // If the operand types disagree, extend the shift amount to match. Since
12799 // BT ignores high bits (like shifts) we can use anyextend.
12800 if (LHS.getValueType() != RHS.getValueType())
12801 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12803 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12804 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12805 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12806 DAG.getConstant(Cond, MVT::i8), BT);
12812 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12814 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12819 // SSE Condition code mapping:
12828 switch (SetCCOpcode) {
12829 default: llvm_unreachable("Unexpected SETCC condition");
12831 case ISD::SETEQ: SSECC = 0; break;
12833 case ISD::SETGT: Swap = true; // Fallthrough
12835 case ISD::SETOLT: SSECC = 1; break;
12837 case ISD::SETGE: Swap = true; // Fallthrough
12839 case ISD::SETOLE: SSECC = 2; break;
12840 case ISD::SETUO: SSECC = 3; break;
12842 case ISD::SETNE: SSECC = 4; break;
12843 case ISD::SETULE: Swap = true; // Fallthrough
12844 case ISD::SETUGE: SSECC = 5; break;
12845 case ISD::SETULT: Swap = true; // Fallthrough
12846 case ISD::SETUGT: SSECC = 6; break;
12847 case ISD::SETO: SSECC = 7; break;
12849 case ISD::SETONE: SSECC = 8; break;
12852 std::swap(Op0, Op1);
12857 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12858 // ones, and then concatenate the result back.
12859 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12860 MVT VT = Op.getSimpleValueType();
12862 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12863 "Unsupported value type for operation");
12865 unsigned NumElems = VT.getVectorNumElements();
12867 SDValue CC = Op.getOperand(2);
12869 // Extract the LHS vectors
12870 SDValue LHS = Op.getOperand(0);
12871 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12872 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12874 // Extract the RHS vectors
12875 SDValue RHS = Op.getOperand(1);
12876 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12877 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12879 // Issue the operation on the smaller types and concatenate the result back
12880 MVT EltVT = VT.getVectorElementType();
12881 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12882 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12883 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12884 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12887 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12888 const X86Subtarget *Subtarget) {
12889 SDValue Op0 = Op.getOperand(0);
12890 SDValue Op1 = Op.getOperand(1);
12891 SDValue CC = Op.getOperand(2);
12892 MVT VT = Op.getSimpleValueType();
12895 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
12896 Op.getValueType().getScalarType() == MVT::i1 &&
12897 "Cannot set masked compare for this operation");
12899 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12901 bool Unsigned = false;
12904 switch (SetCCOpcode) {
12905 default: llvm_unreachable("Unexpected SETCC condition");
12906 case ISD::SETNE: SSECC = 4; break;
12907 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12908 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12909 case ISD::SETLT: Swap = true; //fall-through
12910 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12911 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12912 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12913 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12914 case ISD::SETULE: Unsigned = true; //fall-through
12915 case ISD::SETLE: SSECC = 2; break;
12919 std::swap(Op0, Op1);
12921 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12922 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12923 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12924 DAG.getConstant(SSECC, MVT::i8));
12927 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12928 /// operand \p Op1. If non-trivial (for example because it's not constant)
12929 /// return an empty value.
12930 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12932 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12936 MVT VT = Op1.getSimpleValueType();
12937 MVT EVT = VT.getVectorElementType();
12938 unsigned n = VT.getVectorNumElements();
12939 SmallVector<SDValue, 8> ULTOp1;
12941 for (unsigned i = 0; i < n; ++i) {
12942 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12943 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12946 // Avoid underflow.
12947 APInt Val = Elt->getAPIntValue();
12951 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12954 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12957 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12958 SelectionDAG &DAG) {
12959 SDValue Op0 = Op.getOperand(0);
12960 SDValue Op1 = Op.getOperand(1);
12961 SDValue CC = Op.getOperand(2);
12962 MVT VT = Op.getSimpleValueType();
12963 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12964 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12969 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12970 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12973 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12974 unsigned Opc = X86ISD::CMPP;
12975 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12976 assert(VT.getVectorNumElements() <= 16);
12977 Opc = X86ISD::CMPM;
12979 // In the two special cases we can't handle, emit two comparisons.
12982 unsigned CombineOpc;
12983 if (SetCCOpcode == ISD::SETUEQ) {
12984 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12986 assert(SetCCOpcode == ISD::SETONE);
12987 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12990 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12991 DAG.getConstant(CC0, MVT::i8));
12992 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12993 DAG.getConstant(CC1, MVT::i8));
12994 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12996 // Handle all other FP comparisons here.
12997 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12998 DAG.getConstant(SSECC, MVT::i8));
13001 // Break 256-bit integer vector compare into smaller ones.
13002 if (VT.is256BitVector() && !Subtarget->hasInt256())
13003 return Lower256IntVSETCC(Op, DAG);
13005 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13006 EVT OpVT = Op1.getValueType();
13007 if (Subtarget->hasAVX512()) {
13008 if (Op1.getValueType().is512BitVector() ||
13009 (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13010 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13011 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13013 // In AVX-512 architecture setcc returns mask with i1 elements,
13014 // But there is no compare instruction for i8 and i16 elements in KNL.
13015 // We are not talking about 512-bit operands in this case, these
13016 // types are illegal.
13018 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13019 OpVT.getVectorElementType().getSizeInBits() >= 8))
13020 return DAG.getNode(ISD::TRUNCATE, dl, VT,
13021 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13024 // We are handling one of the integer comparisons here. Since SSE only has
13025 // GT and EQ comparisons for integer, swapping operands and multiple
13026 // operations may be required for some comparisons.
13028 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13029 bool Subus = false;
13031 switch (SetCCOpcode) {
13032 default: llvm_unreachable("Unexpected SETCC condition");
13033 case ISD::SETNE: Invert = true;
13034 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
13035 case ISD::SETLT: Swap = true;
13036 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
13037 case ISD::SETGE: Swap = true;
13038 case ISD::SETLE: Opc = X86ISD::PCMPGT;
13039 Invert = true; break;
13040 case ISD::SETULT: Swap = true;
13041 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13042 FlipSigns = true; break;
13043 case ISD::SETUGE: Swap = true;
13044 case ISD::SETULE: Opc = X86ISD::PCMPGT;
13045 FlipSigns = true; Invert = true; break;
13048 // Special case: Use min/max operations for SETULE/SETUGE
13049 MVT VET = VT.getVectorElementType();
13051 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13052 || (Subtarget->hasSSE2() && (VET == MVT::i8));
13055 switch (SetCCOpcode) {
13057 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13058 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13061 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13064 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13065 if (!MinMax && hasSubus) {
13066 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13068 // t = psubus Op0, Op1
13069 // pcmpeq t, <0..0>
13070 switch (SetCCOpcode) {
13072 case ISD::SETULT: {
13073 // If the comparison is against a constant we can turn this into a
13074 // setule. With psubus, setule does not require a swap. This is
13075 // beneficial because the constant in the register is no longer
13076 // destructed as the destination so it can be hoisted out of a loop.
13077 // Only do this pre-AVX since vpcmp* is no longer destructive.
13078 if (Subtarget->hasAVX())
13080 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13081 if (ULEOp1.getNode()) {
13083 Subus = true; Invert = false; Swap = false;
13087 // Psubus is better than flip-sign because it requires no inversion.
13088 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13089 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13093 Opc = X86ISD::SUBUS;
13099 std::swap(Op0, Op1);
13101 // Check that the operation in question is available (most are plain SSE2,
13102 // but PCMPGTQ and PCMPEQQ have different requirements).
13103 if (VT == MVT::v2i64) {
13104 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13105 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13107 // First cast everything to the right type.
13108 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13109 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13111 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13112 // bits of the inputs before performing those operations. The lower
13113 // compare is always unsigned.
13116 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13118 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13119 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13120 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13121 Sign, Zero, Sign, Zero);
13123 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13124 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13126 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13127 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13128 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13130 // Create masks for only the low parts/high parts of the 64 bit integers.
13131 static const int MaskHi[] = { 1, 1, 3, 3 };
13132 static const int MaskLo[] = { 0, 0, 2, 2 };
13133 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13134 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13135 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13137 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13138 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13141 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13143 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13146 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13147 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13148 // pcmpeqd + pshufd + pand.
13149 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13151 // First cast everything to the right type.
13152 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13153 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13156 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13158 // Make sure the lower and upper halves are both all-ones.
13159 static const int Mask[] = { 1, 0, 3, 2 };
13160 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13161 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13164 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13166 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13170 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13171 // bits of the inputs before performing those operations.
13173 EVT EltVT = VT.getVectorElementType();
13174 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13175 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13176 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13179 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13181 // If the logical-not of the result is required, perform that now.
13183 Result = DAG.getNOT(dl, Result, VT);
13186 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13189 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13190 getZeroVector(VT, Subtarget, DAG, dl));
13195 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13197 MVT VT = Op.getSimpleValueType();
13199 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13201 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13202 && "SetCC type must be 8-bit or 1-bit integer");
13203 SDValue Op0 = Op.getOperand(0);
13204 SDValue Op1 = Op.getOperand(1);
13206 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13208 // Optimize to BT if possible.
13209 // Lower (X & (1 << N)) == 0 to BT(X, N).
13210 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13211 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13212 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13213 Op1.getOpcode() == ISD::Constant &&
13214 cast<ConstantSDNode>(Op1)->isNullValue() &&
13215 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13216 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13217 if (NewSetCC.getNode())
13221 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13223 if (Op1.getOpcode() == ISD::Constant &&
13224 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13225 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13226 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13228 // If the input is a setcc, then reuse the input setcc or use a new one with
13229 // the inverted condition.
13230 if (Op0.getOpcode() == X86ISD::SETCC) {
13231 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13232 bool Invert = (CC == ISD::SETNE) ^
13233 cast<ConstantSDNode>(Op1)->isNullValue();
13237 CCode = X86::GetOppositeBranchCondition(CCode);
13238 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13239 DAG.getConstant(CCode, MVT::i8),
13240 Op0.getOperand(1));
13242 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13246 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13247 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13248 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13250 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13251 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13254 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13255 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13256 if (X86CC == X86::COND_INVALID)
13259 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13260 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13261 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13262 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13264 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13268 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13269 static bool isX86LogicalCmp(SDValue Op) {
13270 unsigned Opc = Op.getNode()->getOpcode();
13271 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13272 Opc == X86ISD::SAHF)
13274 if (Op.getResNo() == 1 &&
13275 (Opc == X86ISD::ADD ||
13276 Opc == X86ISD::SUB ||
13277 Opc == X86ISD::ADC ||
13278 Opc == X86ISD::SBB ||
13279 Opc == X86ISD::SMUL ||
13280 Opc == X86ISD::UMUL ||
13281 Opc == X86ISD::INC ||
13282 Opc == X86ISD::DEC ||
13283 Opc == X86ISD::OR ||
13284 Opc == X86ISD::XOR ||
13285 Opc == X86ISD::AND))
13288 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13294 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13295 if (V.getOpcode() != ISD::TRUNCATE)
13298 SDValue VOp0 = V.getOperand(0);
13299 unsigned InBits = VOp0.getValueSizeInBits();
13300 unsigned Bits = V.getValueSizeInBits();
13301 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13304 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13305 bool addTest = true;
13306 SDValue Cond = Op.getOperand(0);
13307 SDValue Op1 = Op.getOperand(1);
13308 SDValue Op2 = Op.getOperand(2);
13310 EVT VT = Op1.getValueType();
13313 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13314 // are available. Otherwise fp cmovs get lowered into a less efficient branch
13315 // sequence later on.
13316 if (Cond.getOpcode() == ISD::SETCC &&
13317 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13318 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13319 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13320 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13321 int SSECC = translateX86FSETCC(
13322 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13325 if (Subtarget->hasAVX512()) {
13326 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13327 DAG.getConstant(SSECC, MVT::i8));
13328 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13330 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13331 DAG.getConstant(SSECC, MVT::i8));
13332 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13333 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13334 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13338 if (Cond.getOpcode() == ISD::SETCC) {
13339 SDValue NewCond = LowerSETCC(Cond, DAG);
13340 if (NewCond.getNode())
13344 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13345 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13346 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13347 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13348 if (Cond.getOpcode() == X86ISD::SETCC &&
13349 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13350 isZero(Cond.getOperand(1).getOperand(1))) {
13351 SDValue Cmp = Cond.getOperand(1);
13353 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13355 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13356 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13357 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13359 SDValue CmpOp0 = Cmp.getOperand(0);
13360 // Apply further optimizations for special cases
13361 // (select (x != 0), -1, 0) -> neg & sbb
13362 // (select (x == 0), 0, -1) -> neg & sbb
13363 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13364 if (YC->isNullValue() &&
13365 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13366 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13367 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13368 DAG.getConstant(0, CmpOp0.getValueType()),
13370 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13371 DAG.getConstant(X86::COND_B, MVT::i8),
13372 SDValue(Neg.getNode(), 1));
13376 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13377 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13378 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13380 SDValue Res = // Res = 0 or -1.
13381 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13382 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13384 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13385 Res = DAG.getNOT(DL, Res, Res.getValueType());
13387 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13388 if (!N2C || !N2C->isNullValue())
13389 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13394 // Look past (and (setcc_carry (cmp ...)), 1).
13395 if (Cond.getOpcode() == ISD::AND &&
13396 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13397 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13398 if (C && C->getAPIntValue() == 1)
13399 Cond = Cond.getOperand(0);
13402 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13403 // setting operand in place of the X86ISD::SETCC.
13404 unsigned CondOpcode = Cond.getOpcode();
13405 if (CondOpcode == X86ISD::SETCC ||
13406 CondOpcode == X86ISD::SETCC_CARRY) {
13407 CC = Cond.getOperand(0);
13409 SDValue Cmp = Cond.getOperand(1);
13410 unsigned Opc = Cmp.getOpcode();
13411 MVT VT = Op.getSimpleValueType();
13413 bool IllegalFPCMov = false;
13414 if (VT.isFloatingPoint() && !VT.isVector() &&
13415 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13416 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13418 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13419 Opc == X86ISD::BT) { // FIXME
13423 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13424 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13425 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13426 Cond.getOperand(0).getValueType() != MVT::i8)) {
13427 SDValue LHS = Cond.getOperand(0);
13428 SDValue RHS = Cond.getOperand(1);
13429 unsigned X86Opcode;
13432 switch (CondOpcode) {
13433 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13434 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13435 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13436 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13437 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13438 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13439 default: llvm_unreachable("unexpected overflowing operator");
13441 if (CondOpcode == ISD::UMULO)
13442 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13445 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13447 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13449 if (CondOpcode == ISD::UMULO)
13450 Cond = X86Op.getValue(2);
13452 Cond = X86Op.getValue(1);
13454 CC = DAG.getConstant(X86Cond, MVT::i8);
13459 // Look pass the truncate if the high bits are known zero.
13460 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13461 Cond = Cond.getOperand(0);
13463 // We know the result of AND is compared against zero. Try to match
13465 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13466 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13467 if (NewSetCC.getNode()) {
13468 CC = NewSetCC.getOperand(0);
13469 Cond = NewSetCC.getOperand(1);
13476 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13477 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13480 // a < b ? -1 : 0 -> RES = ~setcc_carry
13481 // a < b ? 0 : -1 -> RES = setcc_carry
13482 // a >= b ? -1 : 0 -> RES = setcc_carry
13483 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13484 if (Cond.getOpcode() == X86ISD::SUB) {
13485 Cond = ConvertCmpIfNecessary(Cond, DAG);
13486 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13488 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13489 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13490 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13491 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13492 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13493 return DAG.getNOT(DL, Res, Res.getValueType());
13498 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13499 // widen the cmov and push the truncate through. This avoids introducing a new
13500 // branch during isel and doesn't add any extensions.
13501 if (Op.getValueType() == MVT::i8 &&
13502 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13503 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13504 if (T1.getValueType() == T2.getValueType() &&
13505 // Blacklist CopyFromReg to avoid partial register stalls.
13506 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13507 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13508 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13509 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13513 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13514 // condition is true.
13515 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13516 SDValue Ops[] = { Op2, Op1, CC, Cond };
13517 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13520 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13521 MVT VT = Op->getSimpleValueType(0);
13522 SDValue In = Op->getOperand(0);
13523 MVT InVT = In.getSimpleValueType();
13526 unsigned int NumElts = VT.getVectorNumElements();
13527 if (NumElts != 8 && NumElts != 16)
13530 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13531 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13533 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13534 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13536 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13537 Constant *C = ConstantInt::get(*DAG.getContext(),
13538 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13540 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13541 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13542 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13543 MachinePointerInfo::getConstantPool(),
13544 false, false, false, Alignment);
13545 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13546 if (VT.is512BitVector())
13548 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13551 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13552 SelectionDAG &DAG) {
13553 MVT VT = Op->getSimpleValueType(0);
13554 SDValue In = Op->getOperand(0);
13555 MVT InVT = In.getSimpleValueType();
13558 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13559 return LowerSIGN_EXTEND_AVX512(Op, DAG);
13561 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13562 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13563 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13566 if (Subtarget->hasInt256())
13567 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13569 // Optimize vectors in AVX mode
13570 // Sign extend v8i16 to v8i32 and
13573 // Divide input vector into two parts
13574 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13575 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13576 // concat the vectors to original VT
13578 unsigned NumElems = InVT.getVectorNumElements();
13579 SDValue Undef = DAG.getUNDEF(InVT);
13581 SmallVector<int,8> ShufMask1(NumElems, -1);
13582 for (unsigned i = 0; i != NumElems/2; ++i)
13585 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13587 SmallVector<int,8> ShufMask2(NumElems, -1);
13588 for (unsigned i = 0; i != NumElems/2; ++i)
13589 ShufMask2[i] = i + NumElems/2;
13591 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13593 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13594 VT.getVectorNumElements()/2);
13596 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13597 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13599 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13602 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13603 // may emit an illegal shuffle but the expansion is still better than scalar
13604 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13605 // we'll emit a shuffle and a arithmetic shift.
13606 // TODO: It is possible to support ZExt by zeroing the undef values during
13607 // the shuffle phase or after the shuffle.
13608 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13609 SelectionDAG &DAG) {
13610 MVT RegVT = Op.getSimpleValueType();
13611 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13612 assert(RegVT.isInteger() &&
13613 "We only custom lower integer vector sext loads.");
13615 // Nothing useful we can do without SSE2 shuffles.
13616 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13618 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13620 EVT MemVT = Ld->getMemoryVT();
13621 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13622 unsigned RegSz = RegVT.getSizeInBits();
13624 ISD::LoadExtType Ext = Ld->getExtensionType();
13626 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13627 && "Only anyext and sext are currently implemented.");
13628 assert(MemVT != RegVT && "Cannot extend to the same type");
13629 assert(MemVT.isVector() && "Must load a vector from memory");
13631 unsigned NumElems = RegVT.getVectorNumElements();
13632 unsigned MemSz = MemVT.getSizeInBits();
13633 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13635 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13636 // The only way in which we have a legal 256-bit vector result but not the
13637 // integer 256-bit operations needed to directly lower a sextload is if we
13638 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13639 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13640 // correctly legalized. We do this late to allow the canonical form of
13641 // sextload to persist throughout the rest of the DAG combiner -- it wants
13642 // to fold together any extensions it can, and so will fuse a sign_extend
13643 // of an sextload into a sextload targeting a wider value.
13645 if (MemSz == 128) {
13646 // Just switch this to a normal load.
13647 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13648 "it must be a legal 128-bit vector "
13650 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13651 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13652 Ld->isInvariant(), Ld->getAlignment());
13654 assert(MemSz < 128 &&
13655 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13656 // Do an sext load to a 128-bit vector type. We want to use the same
13657 // number of elements, but elements half as wide. This will end up being
13658 // recursively lowered by this routine, but will succeed as we definitely
13659 // have all the necessary features if we're using AVX1.
13661 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13662 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13664 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13665 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13666 Ld->isNonTemporal(), Ld->isInvariant(),
13667 Ld->getAlignment());
13670 // Replace chain users with the new chain.
13671 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13672 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13674 // Finally, do a normal sign-extend to the desired register.
13675 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13678 // All sizes must be a power of two.
13679 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13680 "Non-power-of-two elements are not custom lowered!");
13682 // Attempt to load the original value using scalar loads.
13683 // Find the largest scalar type that divides the total loaded size.
13684 MVT SclrLoadTy = MVT::i8;
13685 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13686 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13687 MVT Tp = (MVT::SimpleValueType)tp;
13688 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13693 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13694 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13696 SclrLoadTy = MVT::f64;
13698 // Calculate the number of scalar loads that we need to perform
13699 // in order to load our vector from memory.
13700 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13702 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13703 "Can only lower sext loads with a single scalar load!");
13705 unsigned loadRegZize = RegSz;
13706 if (Ext == ISD::SEXTLOAD && RegSz == 256)
13709 // Represent our vector as a sequence of elements which are the
13710 // largest scalar that we can load.
13711 EVT LoadUnitVecVT = EVT::getVectorVT(
13712 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13714 // Represent the data using the same element type that is stored in
13715 // memory. In practice, we ''widen'' MemVT.
13717 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13718 loadRegZize / MemVT.getScalarType().getSizeInBits());
13720 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13721 "Invalid vector type");
13723 // We can't shuffle using an illegal type.
13724 assert(TLI.isTypeLegal(WideVecVT) &&
13725 "We only lower types that form legal widened vector types");
13727 SmallVector<SDValue, 8> Chains;
13728 SDValue Ptr = Ld->getBasePtr();
13729 SDValue Increment =
13730 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13731 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13733 for (unsigned i = 0; i < NumLoads; ++i) {
13734 // Perform a single load.
13735 SDValue ScalarLoad =
13736 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13737 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13738 Ld->getAlignment());
13739 Chains.push_back(ScalarLoad.getValue(1));
13740 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13741 // another round of DAGCombining.
13743 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13745 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13746 ScalarLoad, DAG.getIntPtrConstant(i));
13748 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13751 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13753 // Bitcast the loaded value to a vector of the original element type, in
13754 // the size of the target vector type.
13755 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13756 unsigned SizeRatio = RegSz / MemSz;
13758 if (Ext == ISD::SEXTLOAD) {
13759 // If we have SSE4.1, we can directly emit a VSEXT node.
13760 if (Subtarget->hasSSE41()) {
13761 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13762 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13766 // Otherwise we'll shuffle the small elements in the high bits of the
13767 // larger type and perform an arithmetic shift. If the shift is not legal
13768 // it's better to scalarize.
13769 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13770 "We can't implement a sext load without an arithmetic right shift!");
13772 // Redistribute the loaded elements into the different locations.
13773 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13774 for (unsigned i = 0; i != NumElems; ++i)
13775 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13777 SDValue Shuff = DAG.getVectorShuffle(
13778 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13780 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13782 // Build the arithmetic shift.
13783 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13784 MemVT.getVectorElementType().getSizeInBits();
13786 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13788 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13792 // Redistribute the loaded elements into the different locations.
13793 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13794 for (unsigned i = 0; i != NumElems; ++i)
13795 ShuffleVec[i * SizeRatio] = i;
13797 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13798 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13800 // Bitcast to the requested type.
13801 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13802 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13806 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13807 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13808 // from the AND / OR.
13809 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13810 Opc = Op.getOpcode();
13811 if (Opc != ISD::OR && Opc != ISD::AND)
13813 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13814 Op.getOperand(0).hasOneUse() &&
13815 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13816 Op.getOperand(1).hasOneUse());
13819 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13820 // 1 and that the SETCC node has a single use.
13821 static bool isXor1OfSetCC(SDValue Op) {
13822 if (Op.getOpcode() != ISD::XOR)
13824 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13825 if (N1C && N1C->getAPIntValue() == 1) {
13826 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13827 Op.getOperand(0).hasOneUse();
13832 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13833 bool addTest = true;
13834 SDValue Chain = Op.getOperand(0);
13835 SDValue Cond = Op.getOperand(1);
13836 SDValue Dest = Op.getOperand(2);
13839 bool Inverted = false;
13841 if (Cond.getOpcode() == ISD::SETCC) {
13842 // Check for setcc([su]{add,sub,mul}o == 0).
13843 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13844 isa<ConstantSDNode>(Cond.getOperand(1)) &&
13845 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13846 Cond.getOperand(0).getResNo() == 1 &&
13847 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13848 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13849 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13850 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13851 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13852 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13854 Cond = Cond.getOperand(0);
13856 SDValue NewCond = LowerSETCC(Cond, DAG);
13857 if (NewCond.getNode())
13862 // FIXME: LowerXALUO doesn't handle these!!
13863 else if (Cond.getOpcode() == X86ISD::ADD ||
13864 Cond.getOpcode() == X86ISD::SUB ||
13865 Cond.getOpcode() == X86ISD::SMUL ||
13866 Cond.getOpcode() == X86ISD::UMUL)
13867 Cond = LowerXALUO(Cond, DAG);
13870 // Look pass (and (setcc_carry (cmp ...)), 1).
13871 if (Cond.getOpcode() == ISD::AND &&
13872 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13873 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13874 if (C && C->getAPIntValue() == 1)
13875 Cond = Cond.getOperand(0);
13878 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13879 // setting operand in place of the X86ISD::SETCC.
13880 unsigned CondOpcode = Cond.getOpcode();
13881 if (CondOpcode == X86ISD::SETCC ||
13882 CondOpcode == X86ISD::SETCC_CARRY) {
13883 CC = Cond.getOperand(0);
13885 SDValue Cmp = Cond.getOperand(1);
13886 unsigned Opc = Cmp.getOpcode();
13887 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13888 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13892 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13896 // These can only come from an arithmetic instruction with overflow,
13897 // e.g. SADDO, UADDO.
13898 Cond = Cond.getNode()->getOperand(1);
13904 CondOpcode = Cond.getOpcode();
13905 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13906 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13907 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13908 Cond.getOperand(0).getValueType() != MVT::i8)) {
13909 SDValue LHS = Cond.getOperand(0);
13910 SDValue RHS = Cond.getOperand(1);
13911 unsigned X86Opcode;
13914 // Keep this in sync with LowerXALUO, otherwise we might create redundant
13915 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13917 switch (CondOpcode) {
13918 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13920 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13922 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13925 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13926 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13928 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13930 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13933 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13934 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13935 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13936 default: llvm_unreachable("unexpected overflowing operator");
13939 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13940 if (CondOpcode == ISD::UMULO)
13941 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13944 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13946 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13948 if (CondOpcode == ISD::UMULO)
13949 Cond = X86Op.getValue(2);
13951 Cond = X86Op.getValue(1);
13953 CC = DAG.getConstant(X86Cond, MVT::i8);
13957 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13958 SDValue Cmp = Cond.getOperand(0).getOperand(1);
13959 if (CondOpc == ISD::OR) {
13960 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13961 // two branches instead of an explicit OR instruction with a
13963 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13964 isX86LogicalCmp(Cmp)) {
13965 CC = Cond.getOperand(0).getOperand(0);
13966 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13967 Chain, Dest, CC, Cmp);
13968 CC = Cond.getOperand(1).getOperand(0);
13972 } else { // ISD::AND
13973 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13974 // two branches instead of an explicit AND instruction with a
13975 // separate test. However, we only do this if this block doesn't
13976 // have a fall-through edge, because this requires an explicit
13977 // jmp when the condition is false.
13978 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13979 isX86LogicalCmp(Cmp) &&
13980 Op.getNode()->hasOneUse()) {
13981 X86::CondCode CCode =
13982 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13983 CCode = X86::GetOppositeBranchCondition(CCode);
13984 CC = DAG.getConstant(CCode, MVT::i8);
13985 SDNode *User = *Op.getNode()->use_begin();
13986 // Look for an unconditional branch following this conditional branch.
13987 // We need this because we need to reverse the successors in order
13988 // to implement FCMP_OEQ.
13989 if (User->getOpcode() == ISD::BR) {
13990 SDValue FalseBB = User->getOperand(1);
13992 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13993 assert(NewBR == User);
13997 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13998 Chain, Dest, CC, Cmp);
13999 X86::CondCode CCode =
14000 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14001 CCode = X86::GetOppositeBranchCondition(CCode);
14002 CC = DAG.getConstant(CCode, MVT::i8);
14008 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14009 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14010 // It should be transformed during dag combiner except when the condition
14011 // is set by a arithmetics with overflow node.
14012 X86::CondCode CCode =
14013 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14014 CCode = X86::GetOppositeBranchCondition(CCode);
14015 CC = DAG.getConstant(CCode, MVT::i8);
14016 Cond = Cond.getOperand(0).getOperand(1);
14018 } else if (Cond.getOpcode() == ISD::SETCC &&
14019 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14020 // For FCMP_OEQ, we can emit
14021 // two branches instead of an explicit AND instruction with a
14022 // separate test. However, we only do this if this block doesn't
14023 // have a fall-through edge, because this requires an explicit
14024 // jmp when the condition is false.
14025 if (Op.getNode()->hasOneUse()) {
14026 SDNode *User = *Op.getNode()->use_begin();
14027 // Look for an unconditional branch following this conditional branch.
14028 // We need this because we need to reverse the successors in order
14029 // to implement FCMP_OEQ.
14030 if (User->getOpcode() == ISD::BR) {
14031 SDValue FalseBB = User->getOperand(1);
14033 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14034 assert(NewBR == User);
14038 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14039 Cond.getOperand(0), Cond.getOperand(1));
14040 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14041 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14042 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14043 Chain, Dest, CC, Cmp);
14044 CC = DAG.getConstant(X86::COND_P, MVT::i8);
14049 } else if (Cond.getOpcode() == ISD::SETCC &&
14050 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14051 // For FCMP_UNE, we can emit
14052 // two branches instead of an explicit AND instruction with a
14053 // separate test. However, we only do this if this block doesn't
14054 // have a fall-through edge, because this requires an explicit
14055 // jmp when the condition is false.
14056 if (Op.getNode()->hasOneUse()) {
14057 SDNode *User = *Op.getNode()->use_begin();
14058 // Look for an unconditional branch following this conditional branch.
14059 // We need this because we need to reverse the successors in order
14060 // to implement FCMP_UNE.
14061 if (User->getOpcode() == ISD::BR) {
14062 SDValue FalseBB = User->getOperand(1);
14064 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14065 assert(NewBR == User);
14068 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14069 Cond.getOperand(0), Cond.getOperand(1));
14070 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14071 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14072 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14073 Chain, Dest, CC, Cmp);
14074 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14084 // Look pass the truncate if the high bits are known zero.
14085 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14086 Cond = Cond.getOperand(0);
14088 // We know the result of AND is compared against zero. Try to match
14090 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14091 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14092 if (NewSetCC.getNode()) {
14093 CC = NewSetCC.getOperand(0);
14094 Cond = NewSetCC.getOperand(1);
14101 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14102 CC = DAG.getConstant(X86Cond, MVT::i8);
14103 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14105 Cond = ConvertCmpIfNecessary(Cond, DAG);
14106 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14107 Chain, Dest, CC, Cond);
14110 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14111 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14112 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14113 // that the guard pages used by the OS virtual memory manager are allocated in
14114 // correct sequence.
14116 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14117 SelectionDAG &DAG) const {
14118 MachineFunction &MF = DAG.getMachineFunction();
14119 bool SplitStack = MF.shouldSplitStack();
14120 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
14125 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14126 SDNode* Node = Op.getNode();
14128 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14129 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14130 " not tell us which reg is the stack pointer!");
14131 EVT VT = Node->getValueType(0);
14132 SDValue Tmp1 = SDValue(Node, 0);
14133 SDValue Tmp2 = SDValue(Node, 1);
14134 SDValue Tmp3 = Node->getOperand(2);
14135 SDValue Chain = Tmp1.getOperand(0);
14137 // Chain the dynamic stack allocation so that it doesn't modify the stack
14138 // pointer when other instructions are using the stack.
14139 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14142 SDValue Size = Tmp2.getOperand(1);
14143 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14144 Chain = SP.getValue(1);
14145 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14146 const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
14147 unsigned StackAlign = TFI.getStackAlignment();
14148 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14149 if (Align > StackAlign)
14150 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14151 DAG.getConstant(-(uint64_t)Align, VT));
14152 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14154 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14155 DAG.getIntPtrConstant(0, true), SDValue(),
14158 SDValue Ops[2] = { Tmp1, Tmp2 };
14159 return DAG.getMergeValues(Ops, dl);
14163 SDValue Chain = Op.getOperand(0);
14164 SDValue Size = Op.getOperand(1);
14165 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14166 EVT VT = Op.getNode()->getValueType(0);
14168 bool Is64Bit = Subtarget->is64Bit();
14169 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
14172 MachineRegisterInfo &MRI = MF.getRegInfo();
14175 // The 64 bit implementation of segmented stacks needs to clobber both r10
14176 // r11. This makes it impossible to use it along with nested parameters.
14177 const Function *F = MF.getFunction();
14179 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14181 if (I->hasNestAttr())
14182 report_fatal_error("Cannot use segmented stacks with functions that "
14183 "have nested arguments.");
14186 const TargetRegisterClass *AddrRegClass =
14187 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
14188 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14189 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14190 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14191 DAG.getRegister(Vreg, SPTy));
14192 SDValue Ops1[2] = { Value, Chain };
14193 return DAG.getMergeValues(Ops1, dl);
14196 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
14198 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14199 Flag = Chain.getValue(1);
14200 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14202 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14204 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
14205 DAG.getSubtarget().getRegisterInfo());
14206 unsigned SPReg = RegInfo->getStackRegister();
14207 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14208 Chain = SP.getValue(1);
14211 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14212 DAG.getConstant(-(uint64_t)Align, VT));
14213 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14216 SDValue Ops1[2] = { SP, Chain };
14217 return DAG.getMergeValues(Ops1, dl);
14221 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14222 MachineFunction &MF = DAG.getMachineFunction();
14223 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14225 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14228 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14229 // vastart just stores the address of the VarArgsFrameIndex slot into the
14230 // memory location argument.
14231 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14233 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14234 MachinePointerInfo(SV), false, false, 0);
14238 // gp_offset (0 - 6 * 8)
14239 // fp_offset (48 - 48 + 8 * 16)
14240 // overflow_arg_area (point to parameters coming in memory).
14242 SmallVector<SDValue, 8> MemOps;
14243 SDValue FIN = Op.getOperand(1);
14245 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14246 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14248 FIN, MachinePointerInfo(SV), false, false, 0);
14249 MemOps.push_back(Store);
14252 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14253 FIN, DAG.getIntPtrConstant(4));
14254 Store = DAG.getStore(Op.getOperand(0), DL,
14255 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14257 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14258 MemOps.push_back(Store);
14260 // Store ptr to overflow_arg_area
14261 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14262 FIN, DAG.getIntPtrConstant(4));
14263 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14265 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14266 MachinePointerInfo(SV, 8),
14268 MemOps.push_back(Store);
14270 // Store ptr to reg_save_area.
14271 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14272 FIN, DAG.getIntPtrConstant(8));
14273 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14275 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14276 MachinePointerInfo(SV, 16), false, false, 0);
14277 MemOps.push_back(Store);
14278 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14281 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14282 assert(Subtarget->is64Bit() &&
14283 "LowerVAARG only handles 64-bit va_arg!");
14284 assert((Subtarget->isTargetLinux() ||
14285 Subtarget->isTargetDarwin()) &&
14286 "Unhandled target in LowerVAARG");
14287 assert(Op.getNode()->getNumOperands() == 4);
14288 SDValue Chain = Op.getOperand(0);
14289 SDValue SrcPtr = Op.getOperand(1);
14290 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14291 unsigned Align = Op.getConstantOperandVal(3);
14294 EVT ArgVT = Op.getNode()->getValueType(0);
14295 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14296 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14299 // Decide which area this value should be read from.
14300 // TODO: Implement the AMD64 ABI in its entirety. This simple
14301 // selection mechanism works only for the basic types.
14302 if (ArgVT == MVT::f80) {
14303 llvm_unreachable("va_arg for f80 not yet implemented");
14304 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14305 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14306 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14307 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14309 llvm_unreachable("Unhandled argument type in LowerVAARG");
14312 if (ArgMode == 2) {
14313 // Sanity Check: Make sure using fp_offset makes sense.
14314 assert(!DAG.getTarget().Options.UseSoftFloat &&
14315 !(DAG.getMachineFunction()
14316 .getFunction()->getAttributes()
14317 .hasAttribute(AttributeSet::FunctionIndex,
14318 Attribute::NoImplicitFloat)) &&
14319 Subtarget->hasSSE1());
14322 // Insert VAARG_64 node into the DAG
14323 // VAARG_64 returns two values: Variable Argument Address, Chain
14324 SmallVector<SDValue, 11> InstOps;
14325 InstOps.push_back(Chain);
14326 InstOps.push_back(SrcPtr);
14327 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
14328 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
14329 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
14330 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14331 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14332 VTs, InstOps, MVT::i64,
14333 MachinePointerInfo(SV),
14335 /*Volatile=*/false,
14337 /*WriteMem=*/true);
14338 Chain = VAARG.getValue(1);
14340 // Load the next argument and return it
14341 return DAG.getLoad(ArgVT, dl,
14344 MachinePointerInfo(),
14345 false, false, false, 0);
14348 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14349 SelectionDAG &DAG) {
14350 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14351 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14352 SDValue Chain = Op.getOperand(0);
14353 SDValue DstPtr = Op.getOperand(1);
14354 SDValue SrcPtr = Op.getOperand(2);
14355 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14356 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14359 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14360 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14362 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14365 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14366 // amount is a constant. Takes immediate version of shift as input.
14367 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14368 SDValue SrcOp, uint64_t ShiftAmt,
14369 SelectionDAG &DAG) {
14370 MVT ElementType = VT.getVectorElementType();
14372 // Fold this packed shift into its first operand if ShiftAmt is 0.
14376 // Check for ShiftAmt >= element width
14377 if (ShiftAmt >= ElementType.getSizeInBits()) {
14378 if (Opc == X86ISD::VSRAI)
14379 ShiftAmt = ElementType.getSizeInBits() - 1;
14381 return DAG.getConstant(0, VT);
14384 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14385 && "Unknown target vector shift-by-constant node");
14387 // Fold this packed vector shift into a build vector if SrcOp is a
14388 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14389 if (VT == SrcOp.getSimpleValueType() &&
14390 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14391 SmallVector<SDValue, 8> Elts;
14392 unsigned NumElts = SrcOp->getNumOperands();
14393 ConstantSDNode *ND;
14396 default: llvm_unreachable(nullptr);
14397 case X86ISD::VSHLI:
14398 for (unsigned i=0; i!=NumElts; ++i) {
14399 SDValue CurrentOp = SrcOp->getOperand(i);
14400 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14401 Elts.push_back(CurrentOp);
14404 ND = cast<ConstantSDNode>(CurrentOp);
14405 const APInt &C = ND->getAPIntValue();
14406 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14409 case X86ISD::VSRLI:
14410 for (unsigned i=0; i!=NumElts; ++i) {
14411 SDValue CurrentOp = SrcOp->getOperand(i);
14412 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14413 Elts.push_back(CurrentOp);
14416 ND = cast<ConstantSDNode>(CurrentOp);
14417 const APInt &C = ND->getAPIntValue();
14418 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14421 case X86ISD::VSRAI:
14422 for (unsigned i=0; i!=NumElts; ++i) {
14423 SDValue CurrentOp = SrcOp->getOperand(i);
14424 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14425 Elts.push_back(CurrentOp);
14428 ND = cast<ConstantSDNode>(CurrentOp);
14429 const APInt &C = ND->getAPIntValue();
14430 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14435 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14438 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14441 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14442 // may or may not be a constant. Takes immediate version of shift as input.
14443 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14444 SDValue SrcOp, SDValue ShAmt,
14445 SelectionDAG &DAG) {
14446 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14448 // Catch shift-by-constant.
14449 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14450 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14451 CShAmt->getZExtValue(), DAG);
14453 // Change opcode to non-immediate version
14455 default: llvm_unreachable("Unknown target vector shift node");
14456 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14457 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14458 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14461 // Need to build a vector containing shift amount
14462 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14465 ShOps[1] = DAG.getConstant(0, MVT::i32);
14466 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14467 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14469 // The return type has to be a 128-bit type with the same element
14470 // type as the input type.
14471 MVT EltVT = VT.getVectorElementType();
14472 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14474 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14475 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14478 /// \brief Return (vselect \p Mask, \p Op, \p PreservedSrc) along with the
14479 /// necessary casting for \p Mask when lowering masking intrinsics.
14480 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14481 SDValue PreservedSrc, SelectionDAG &DAG) {
14482 EVT VT = Op.getValueType();
14483 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14484 MVT::i1, VT.getVectorNumElements());
14487 assert(MaskVT.isSimple() && "invalid mask type");
14488 return DAG.getNode(ISD::VSELECT, dl, VT,
14489 DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask),
14493 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
14495 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14496 case Intrinsic::x86_fma_vfmadd_ps:
14497 case Intrinsic::x86_fma_vfmadd_pd:
14498 case Intrinsic::x86_fma_vfmadd_ps_256:
14499 case Intrinsic::x86_fma_vfmadd_pd_256:
14500 case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14501 case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14502 return X86ISD::FMADD;
14503 case Intrinsic::x86_fma_vfmsub_ps:
14504 case Intrinsic::x86_fma_vfmsub_pd:
14505 case Intrinsic::x86_fma_vfmsub_ps_256:
14506 case Intrinsic::x86_fma_vfmsub_pd_256:
14507 case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14508 case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14509 return X86ISD::FMSUB;
14510 case Intrinsic::x86_fma_vfnmadd_ps:
14511 case Intrinsic::x86_fma_vfnmadd_pd:
14512 case Intrinsic::x86_fma_vfnmadd_ps_256:
14513 case Intrinsic::x86_fma_vfnmadd_pd_256:
14514 case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14515 case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14516 return X86ISD::FNMADD;
14517 case Intrinsic::x86_fma_vfnmsub_ps:
14518 case Intrinsic::x86_fma_vfnmsub_pd:
14519 case Intrinsic::x86_fma_vfnmsub_ps_256:
14520 case Intrinsic::x86_fma_vfnmsub_pd_256:
14521 case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14522 case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14523 return X86ISD::FNMSUB;
14524 case Intrinsic::x86_fma_vfmaddsub_ps:
14525 case Intrinsic::x86_fma_vfmaddsub_pd:
14526 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14527 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14528 case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14529 case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14530 return X86ISD::FMADDSUB;
14531 case Intrinsic::x86_fma_vfmsubadd_ps:
14532 case Intrinsic::x86_fma_vfmsubadd_pd:
14533 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14534 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14535 case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14536 case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
14537 return X86ISD::FMSUBADD;
14541 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14543 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14545 const IntrinsicData* IntrData = GetIntrinsicWithoutChain(IntNo);
14547 switch(IntrData->Type) {
14548 case INTR_TYPE_1OP:
14549 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14550 case INTR_TYPE_2OP:
14551 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14553 case INTR_TYPE_3OP:
14554 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14555 Op.getOperand(2), Op.getOperand(3));
14556 case COMI: { // Comparison intrinsics
14557 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14558 SDValue LHS = Op.getOperand(1);
14559 SDValue RHS = Op.getOperand(2);
14560 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14561 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14562 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14563 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14564 DAG.getConstant(X86CC, MVT::i8), Cond);
14565 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14568 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14569 Op.getOperand(1), Op.getOperand(2), DAG);
14576 default: return SDValue(); // Don't custom lower most intrinsics.
14578 // Arithmetic intrinsics.
14579 case Intrinsic::x86_sse2_pmulu_dq:
14580 case Intrinsic::x86_avx2_pmulu_dq:
14581 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14582 Op.getOperand(1), Op.getOperand(2));
14584 case Intrinsic::x86_sse41_pmuldq:
14585 case Intrinsic::x86_avx2_pmul_dq:
14586 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14587 Op.getOperand(1), Op.getOperand(2));
14589 case Intrinsic::x86_sse2_pmulhu_w:
14590 case Intrinsic::x86_avx2_pmulhu_w:
14591 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14592 Op.getOperand(1), Op.getOperand(2));
14594 case Intrinsic::x86_sse2_pmulh_w:
14595 case Intrinsic::x86_avx2_pmulh_w:
14596 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14597 Op.getOperand(1), Op.getOperand(2));
14599 // SSE/SSE2/AVX floating point max/min intrinsics.
14600 case Intrinsic::x86_sse_max_ps:
14601 case Intrinsic::x86_sse2_max_pd:
14602 case Intrinsic::x86_avx_max_ps_256:
14603 case Intrinsic::x86_avx_max_pd_256:
14604 case Intrinsic::x86_sse_min_ps:
14605 case Intrinsic::x86_sse2_min_pd:
14606 case Intrinsic::x86_avx_min_ps_256:
14607 case Intrinsic::x86_avx_min_pd_256: {
14610 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14611 case Intrinsic::x86_sse_max_ps:
14612 case Intrinsic::x86_sse2_max_pd:
14613 case Intrinsic::x86_avx_max_ps_256:
14614 case Intrinsic::x86_avx_max_pd_256:
14615 Opcode = X86ISD::FMAX;
14617 case Intrinsic::x86_sse_min_ps:
14618 case Intrinsic::x86_sse2_min_pd:
14619 case Intrinsic::x86_avx_min_ps_256:
14620 case Intrinsic::x86_avx_min_pd_256:
14621 Opcode = X86ISD::FMIN;
14624 return DAG.getNode(Opcode, dl, Op.getValueType(),
14625 Op.getOperand(1), Op.getOperand(2));
14628 // AVX2 variable shift intrinsics
14629 case Intrinsic::x86_avx2_psllv_d:
14630 case Intrinsic::x86_avx2_psllv_q:
14631 case Intrinsic::x86_avx2_psllv_d_256:
14632 case Intrinsic::x86_avx2_psllv_q_256:
14633 case Intrinsic::x86_avx2_psrlv_d:
14634 case Intrinsic::x86_avx2_psrlv_q:
14635 case Intrinsic::x86_avx2_psrlv_d_256:
14636 case Intrinsic::x86_avx2_psrlv_q_256:
14637 case Intrinsic::x86_avx2_psrav_d:
14638 case Intrinsic::x86_avx2_psrav_d_256: {
14641 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14642 case Intrinsic::x86_avx2_psllv_d:
14643 case Intrinsic::x86_avx2_psllv_q:
14644 case Intrinsic::x86_avx2_psllv_d_256:
14645 case Intrinsic::x86_avx2_psllv_q_256:
14648 case Intrinsic::x86_avx2_psrlv_d:
14649 case Intrinsic::x86_avx2_psrlv_q:
14650 case Intrinsic::x86_avx2_psrlv_d_256:
14651 case Intrinsic::x86_avx2_psrlv_q_256:
14654 case Intrinsic::x86_avx2_psrav_d:
14655 case Intrinsic::x86_avx2_psrav_d_256:
14659 return DAG.getNode(Opcode, dl, Op.getValueType(),
14660 Op.getOperand(1), Op.getOperand(2));
14663 case Intrinsic::x86_sse2_packssdw_128:
14664 case Intrinsic::x86_sse2_packsswb_128:
14665 case Intrinsic::x86_avx2_packssdw:
14666 case Intrinsic::x86_avx2_packsswb:
14667 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14668 Op.getOperand(1), Op.getOperand(2));
14670 case Intrinsic::x86_sse2_packuswb_128:
14671 case Intrinsic::x86_sse41_packusdw:
14672 case Intrinsic::x86_avx2_packuswb:
14673 case Intrinsic::x86_avx2_packusdw:
14674 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14675 Op.getOperand(1), Op.getOperand(2));
14677 case Intrinsic::x86_ssse3_pshuf_b_128:
14678 case Intrinsic::x86_avx2_pshuf_b:
14679 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14680 Op.getOperand(1), Op.getOperand(2));
14682 case Intrinsic::x86_sse2_pshuf_d:
14683 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14684 Op.getOperand(1), Op.getOperand(2));
14686 case Intrinsic::x86_sse2_pshufl_w:
14687 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14688 Op.getOperand(1), Op.getOperand(2));
14690 case Intrinsic::x86_sse2_pshufh_w:
14691 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14692 Op.getOperand(1), Op.getOperand(2));
14694 case Intrinsic::x86_ssse3_psign_b_128:
14695 case Intrinsic::x86_ssse3_psign_w_128:
14696 case Intrinsic::x86_ssse3_psign_d_128:
14697 case Intrinsic::x86_avx2_psign_b:
14698 case Intrinsic::x86_avx2_psign_w:
14699 case Intrinsic::x86_avx2_psign_d:
14700 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14701 Op.getOperand(1), Op.getOperand(2));
14703 case Intrinsic::x86_avx2_permd:
14704 case Intrinsic::x86_avx2_permps:
14705 // Operands intentionally swapped. Mask is last operand to intrinsic,
14706 // but second operand for node/instruction.
14707 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14708 Op.getOperand(2), Op.getOperand(1));
14710 case Intrinsic::x86_avx512_mask_valign_q_512:
14711 case Intrinsic::x86_avx512_mask_valign_d_512:
14712 // Vector source operands are swapped.
14713 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14714 Op.getValueType(), Op.getOperand(2),
14717 Op.getOperand(5), Op.getOperand(4), DAG);
14719 // ptest and testp intrinsics. The intrinsic these come from are designed to
14720 // return an integer value, not just an instruction so lower it to the ptest
14721 // or testp pattern and a setcc for the result.
14722 case Intrinsic::x86_sse41_ptestz:
14723 case Intrinsic::x86_sse41_ptestc:
14724 case Intrinsic::x86_sse41_ptestnzc:
14725 case Intrinsic::x86_avx_ptestz_256:
14726 case Intrinsic::x86_avx_ptestc_256:
14727 case Intrinsic::x86_avx_ptestnzc_256:
14728 case Intrinsic::x86_avx_vtestz_ps:
14729 case Intrinsic::x86_avx_vtestc_ps:
14730 case Intrinsic::x86_avx_vtestnzc_ps:
14731 case Intrinsic::x86_avx_vtestz_pd:
14732 case Intrinsic::x86_avx_vtestc_pd:
14733 case Intrinsic::x86_avx_vtestnzc_pd:
14734 case Intrinsic::x86_avx_vtestz_ps_256:
14735 case Intrinsic::x86_avx_vtestc_ps_256:
14736 case Intrinsic::x86_avx_vtestnzc_ps_256:
14737 case Intrinsic::x86_avx_vtestz_pd_256:
14738 case Intrinsic::x86_avx_vtestc_pd_256:
14739 case Intrinsic::x86_avx_vtestnzc_pd_256: {
14740 bool IsTestPacked = false;
14743 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14744 case Intrinsic::x86_avx_vtestz_ps:
14745 case Intrinsic::x86_avx_vtestz_pd:
14746 case Intrinsic::x86_avx_vtestz_ps_256:
14747 case Intrinsic::x86_avx_vtestz_pd_256:
14748 IsTestPacked = true; // Fallthrough
14749 case Intrinsic::x86_sse41_ptestz:
14750 case Intrinsic::x86_avx_ptestz_256:
14752 X86CC = X86::COND_E;
14754 case Intrinsic::x86_avx_vtestc_ps:
14755 case Intrinsic::x86_avx_vtestc_pd:
14756 case Intrinsic::x86_avx_vtestc_ps_256:
14757 case Intrinsic::x86_avx_vtestc_pd_256:
14758 IsTestPacked = true; // Fallthrough
14759 case Intrinsic::x86_sse41_ptestc:
14760 case Intrinsic::x86_avx_ptestc_256:
14762 X86CC = X86::COND_B;
14764 case Intrinsic::x86_avx_vtestnzc_ps:
14765 case Intrinsic::x86_avx_vtestnzc_pd:
14766 case Intrinsic::x86_avx_vtestnzc_ps_256:
14767 case Intrinsic::x86_avx_vtestnzc_pd_256:
14768 IsTestPacked = true; // Fallthrough
14769 case Intrinsic::x86_sse41_ptestnzc:
14770 case Intrinsic::x86_avx_ptestnzc_256:
14772 X86CC = X86::COND_A;
14776 SDValue LHS = Op.getOperand(1);
14777 SDValue RHS = Op.getOperand(2);
14778 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14779 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14780 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14781 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14782 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14784 case Intrinsic::x86_avx512_kortestz_w:
14785 case Intrinsic::x86_avx512_kortestc_w: {
14786 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14787 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14788 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14789 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14790 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14791 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14792 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14795 case Intrinsic::x86_sse42_pcmpistria128:
14796 case Intrinsic::x86_sse42_pcmpestria128:
14797 case Intrinsic::x86_sse42_pcmpistric128:
14798 case Intrinsic::x86_sse42_pcmpestric128:
14799 case Intrinsic::x86_sse42_pcmpistrio128:
14800 case Intrinsic::x86_sse42_pcmpestrio128:
14801 case Intrinsic::x86_sse42_pcmpistris128:
14802 case Intrinsic::x86_sse42_pcmpestris128:
14803 case Intrinsic::x86_sse42_pcmpistriz128:
14804 case Intrinsic::x86_sse42_pcmpestriz128: {
14808 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14809 case Intrinsic::x86_sse42_pcmpistria128:
14810 Opcode = X86ISD::PCMPISTRI;
14811 X86CC = X86::COND_A;
14813 case Intrinsic::x86_sse42_pcmpestria128:
14814 Opcode = X86ISD::PCMPESTRI;
14815 X86CC = X86::COND_A;
14817 case Intrinsic::x86_sse42_pcmpistric128:
14818 Opcode = X86ISD::PCMPISTRI;
14819 X86CC = X86::COND_B;
14821 case Intrinsic::x86_sse42_pcmpestric128:
14822 Opcode = X86ISD::PCMPESTRI;
14823 X86CC = X86::COND_B;
14825 case Intrinsic::x86_sse42_pcmpistrio128:
14826 Opcode = X86ISD::PCMPISTRI;
14827 X86CC = X86::COND_O;
14829 case Intrinsic::x86_sse42_pcmpestrio128:
14830 Opcode = X86ISD::PCMPESTRI;
14831 X86CC = X86::COND_O;
14833 case Intrinsic::x86_sse42_pcmpistris128:
14834 Opcode = X86ISD::PCMPISTRI;
14835 X86CC = X86::COND_S;
14837 case Intrinsic::x86_sse42_pcmpestris128:
14838 Opcode = X86ISD::PCMPESTRI;
14839 X86CC = X86::COND_S;
14841 case Intrinsic::x86_sse42_pcmpistriz128:
14842 Opcode = X86ISD::PCMPISTRI;
14843 X86CC = X86::COND_E;
14845 case Intrinsic::x86_sse42_pcmpestriz128:
14846 Opcode = X86ISD::PCMPESTRI;
14847 X86CC = X86::COND_E;
14850 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14851 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14852 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14853 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14854 DAG.getConstant(X86CC, MVT::i8),
14855 SDValue(PCMP.getNode(), 1));
14856 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14859 case Intrinsic::x86_sse42_pcmpistri128:
14860 case Intrinsic::x86_sse42_pcmpestri128: {
14862 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14863 Opcode = X86ISD::PCMPISTRI;
14865 Opcode = X86ISD::PCMPESTRI;
14867 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14868 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14869 return DAG.getNode(Opcode, dl, VTs, NewOps);
14872 case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14873 case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14874 case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14875 case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14876 case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14877 case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14878 case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14879 case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14880 case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14881 case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14882 case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14883 case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
14884 auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
14885 if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
14886 return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
14887 dl, Op.getValueType(),
14891 Op.getOperand(4), Op.getOperand(1), DAG);
14896 case Intrinsic::x86_fma_vfmadd_ps:
14897 case Intrinsic::x86_fma_vfmadd_pd:
14898 case Intrinsic::x86_fma_vfmsub_ps:
14899 case Intrinsic::x86_fma_vfmsub_pd:
14900 case Intrinsic::x86_fma_vfnmadd_ps:
14901 case Intrinsic::x86_fma_vfnmadd_pd:
14902 case Intrinsic::x86_fma_vfnmsub_ps:
14903 case Intrinsic::x86_fma_vfnmsub_pd:
14904 case Intrinsic::x86_fma_vfmaddsub_ps:
14905 case Intrinsic::x86_fma_vfmaddsub_pd:
14906 case Intrinsic::x86_fma_vfmsubadd_ps:
14907 case Intrinsic::x86_fma_vfmsubadd_pd:
14908 case Intrinsic::x86_fma_vfmadd_ps_256:
14909 case Intrinsic::x86_fma_vfmadd_pd_256:
14910 case Intrinsic::x86_fma_vfmsub_ps_256:
14911 case Intrinsic::x86_fma_vfmsub_pd_256:
14912 case Intrinsic::x86_fma_vfnmadd_ps_256:
14913 case Intrinsic::x86_fma_vfnmadd_pd_256:
14914 case Intrinsic::x86_fma_vfnmsub_ps_256:
14915 case Intrinsic::x86_fma_vfnmsub_pd_256:
14916 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14917 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14918 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14919 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14920 return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
14921 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14925 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14926 SDValue Src, SDValue Mask, SDValue Base,
14927 SDValue Index, SDValue ScaleOp, SDValue Chain,
14928 const X86Subtarget * Subtarget) {
14930 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14931 assert(C && "Invalid scale type");
14932 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14933 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14934 Index.getSimpleValueType().getVectorNumElements());
14936 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14938 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14940 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14941 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14942 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14943 SDValue Segment = DAG.getRegister(0, MVT::i32);
14944 if (Src.getOpcode() == ISD::UNDEF)
14945 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14946 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14947 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14948 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14949 return DAG.getMergeValues(RetOps, dl);
14952 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14953 SDValue Src, SDValue Mask, SDValue Base,
14954 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14956 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14957 assert(C && "Invalid scale type");
14958 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14959 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14960 SDValue Segment = DAG.getRegister(0, MVT::i32);
14961 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14962 Index.getSimpleValueType().getVectorNumElements());
14964 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14966 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14968 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14969 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14970 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14971 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14972 return SDValue(Res, 1);
14975 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14976 SDValue Mask, SDValue Base, SDValue Index,
14977 SDValue ScaleOp, SDValue Chain) {
14979 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14980 assert(C && "Invalid scale type");
14981 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14982 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14983 SDValue Segment = DAG.getRegister(0, MVT::i32);
14985 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14987 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14989 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14991 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14992 //SDVTList VTs = DAG.getVTList(MVT::Other);
14993 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14994 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14995 return SDValue(Res, 0);
14998 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14999 // read performance monitor counters (x86_rdpmc).
15000 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15001 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15002 SmallVectorImpl<SDValue> &Results) {
15003 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15004 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15007 // The ECX register is used to select the index of the performance counter
15009 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15011 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15013 // Reads the content of a 64-bit performance counter and returns it in the
15014 // registers EDX:EAX.
15015 if (Subtarget->is64Bit()) {
15016 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15017 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15020 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15021 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15024 Chain = HI.getValue(1);
15026 if (Subtarget->is64Bit()) {
15027 // The EAX register is loaded with the low-order 32 bits. The EDX register
15028 // is loaded with the supported high-order bits of the counter.
15029 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15030 DAG.getConstant(32, MVT::i8));
15031 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15032 Results.push_back(Chain);
15036 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15037 SDValue Ops[] = { LO, HI };
15038 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15039 Results.push_back(Pair);
15040 Results.push_back(Chain);
15043 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15044 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15045 // also used to custom lower READCYCLECOUNTER nodes.
15046 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15047 SelectionDAG &DAG, const X86Subtarget *Subtarget,
15048 SmallVectorImpl<SDValue> &Results) {
15049 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15050 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15053 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15054 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15055 // and the EAX register is loaded with the low-order 32 bits.
15056 if (Subtarget->is64Bit()) {
15057 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15058 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15061 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15062 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15065 SDValue Chain = HI.getValue(1);
15067 if (Opcode == X86ISD::RDTSCP_DAG) {
15068 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15070 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15071 // the ECX register. Add 'ecx' explicitly to the chain.
15072 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15074 // Explicitly store the content of ECX at the location passed in input
15075 // to the 'rdtscp' intrinsic.
15076 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15077 MachinePointerInfo(), false, false, 0);
15080 if (Subtarget->is64Bit()) {
15081 // The EDX register is loaded with the high-order 32 bits of the MSR, and
15082 // the EAX register is loaded with the low-order 32 bits.
15083 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15084 DAG.getConstant(32, MVT::i8));
15085 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15086 Results.push_back(Chain);
15090 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15091 SDValue Ops[] = { LO, HI };
15092 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15093 Results.push_back(Pair);
15094 Results.push_back(Chain);
15097 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15098 SelectionDAG &DAG) {
15099 SmallVector<SDValue, 2> Results;
15101 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15103 return DAG.getMergeValues(Results, DL);
15107 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15108 SelectionDAG &DAG) {
15109 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15111 const IntrinsicData* IntrData = GetIntrinsicWithChain(IntNo);
15116 switch(IntrData->Type) {
15118 llvm_unreachable("Unknown Intrinsic Type");
15122 // Emit the node with the right value type.
15123 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15124 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15126 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15127 // Otherwise return the value from Rand, which is always 0, casted to i32.
15128 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15129 DAG.getConstant(1, Op->getValueType(1)),
15130 DAG.getConstant(X86::COND_B, MVT::i32),
15131 SDValue(Result.getNode(), 1) };
15132 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15133 DAG.getVTList(Op->getValueType(1), MVT::Glue),
15136 // Return { result, isValid, chain }.
15137 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15138 SDValue(Result.getNode(), 2));
15141 //gather(v1, mask, index, base, scale);
15142 SDValue Chain = Op.getOperand(0);
15143 SDValue Src = Op.getOperand(2);
15144 SDValue Base = Op.getOperand(3);
15145 SDValue Index = Op.getOperand(4);
15146 SDValue Mask = Op.getOperand(5);
15147 SDValue Scale = Op.getOperand(6);
15148 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15152 //scatter(base, mask, index, v1, scale);
15153 SDValue Chain = Op.getOperand(0);
15154 SDValue Base = Op.getOperand(2);
15155 SDValue Mask = Op.getOperand(3);
15156 SDValue Index = Op.getOperand(4);
15157 SDValue Src = Op.getOperand(5);
15158 SDValue Scale = Op.getOperand(6);
15159 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15162 SDValue Hint = Op.getOperand(6);
15164 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15165 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15166 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15167 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15168 SDValue Chain = Op.getOperand(0);
15169 SDValue Mask = Op.getOperand(2);
15170 SDValue Index = Op.getOperand(3);
15171 SDValue Base = Op.getOperand(4);
15172 SDValue Scale = Op.getOperand(5);
15173 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15175 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15177 SmallVector<SDValue, 2> Results;
15178 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15179 return DAG.getMergeValues(Results, dl);
15181 // Read Performance Monitoring Counters.
15183 SmallVector<SDValue, 2> Results;
15184 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15185 return DAG.getMergeValues(Results, dl);
15187 // XTEST intrinsics.
15189 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15190 SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15191 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15192 DAG.getConstant(X86::COND_NE, MVT::i8),
15194 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15195 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15196 Ret, SDValue(InTrans.getNode(), 1));
15200 SmallVector<SDValue, 2> Results;
15201 SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15202 SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15203 SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15204 DAG.getConstant(-1, MVT::i8));
15205 SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15206 Op.getOperand(4), GenCF.getValue(1));
15207 SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15208 Op.getOperand(5), MachinePointerInfo(),
15210 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15211 DAG.getConstant(X86::COND_B, MVT::i8),
15213 Results.push_back(SetCC);
15214 Results.push_back(Store);
15215 return DAG.getMergeValues(Results, dl);
15220 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15221 SelectionDAG &DAG) const {
15222 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15223 MFI->setReturnAddressIsTaken(true);
15225 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15228 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15230 EVT PtrVT = getPointerTy();
15233 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15234 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15235 DAG.getSubtarget().getRegisterInfo());
15236 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15237 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15238 DAG.getNode(ISD::ADD, dl, PtrVT,
15239 FrameAddr, Offset),
15240 MachinePointerInfo(), false, false, false, 0);
15243 // Just load the return address.
15244 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15245 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15246 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15249 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15250 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15251 MFI->setFrameAddressIsTaken(true);
15253 EVT VT = Op.getValueType();
15254 SDLoc dl(Op); // FIXME probably not meaningful
15255 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15256 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15257 DAG.getSubtarget().getRegisterInfo());
15258 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15259 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15260 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15261 "Invalid Frame Register!");
15262 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15264 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15265 MachinePointerInfo(),
15266 false, false, false, 0);
15270 // FIXME? Maybe this could be a TableGen attribute on some registers and
15271 // this table could be generated automatically from RegInfo.
15272 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15274 unsigned Reg = StringSwitch<unsigned>(RegName)
15275 .Case("esp", X86::ESP)
15276 .Case("rsp", X86::RSP)
15280 report_fatal_error("Invalid register name global variable");
15283 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15284 SelectionDAG &DAG) const {
15285 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15286 DAG.getSubtarget().getRegisterInfo());
15287 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15290 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15291 SDValue Chain = Op.getOperand(0);
15292 SDValue Offset = Op.getOperand(1);
15293 SDValue Handler = Op.getOperand(2);
15296 EVT PtrVT = getPointerTy();
15297 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15298 DAG.getSubtarget().getRegisterInfo());
15299 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15300 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15301 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15302 "Invalid Frame Register!");
15303 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15304 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15306 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15307 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15308 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15309 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15311 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15313 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15314 DAG.getRegister(StoreAddrReg, PtrVT));
15317 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15318 SelectionDAG &DAG) const {
15320 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15321 DAG.getVTList(MVT::i32, MVT::Other),
15322 Op.getOperand(0), Op.getOperand(1));
15325 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15326 SelectionDAG &DAG) const {
15328 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15329 Op.getOperand(0), Op.getOperand(1));
15332 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15333 return Op.getOperand(0);
15336 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15337 SelectionDAG &DAG) const {
15338 SDValue Root = Op.getOperand(0);
15339 SDValue Trmp = Op.getOperand(1); // trampoline
15340 SDValue FPtr = Op.getOperand(2); // nested function
15341 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15344 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15345 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15347 if (Subtarget->is64Bit()) {
15348 SDValue OutChains[6];
15350 // Large code-model.
15351 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15352 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15354 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15355 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15357 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15359 // Load the pointer to the nested function into R11.
15360 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15361 SDValue Addr = Trmp;
15362 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15363 Addr, MachinePointerInfo(TrmpAddr),
15366 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15367 DAG.getConstant(2, MVT::i64));
15368 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15369 MachinePointerInfo(TrmpAddr, 2),
15372 // Load the 'nest' parameter value into R10.
15373 // R10 is specified in X86CallingConv.td
15374 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15375 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15376 DAG.getConstant(10, MVT::i64));
15377 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15378 Addr, MachinePointerInfo(TrmpAddr, 10),
15381 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15382 DAG.getConstant(12, MVT::i64));
15383 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15384 MachinePointerInfo(TrmpAddr, 12),
15387 // Jump to the nested function.
15388 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15389 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15390 DAG.getConstant(20, MVT::i64));
15391 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15392 Addr, MachinePointerInfo(TrmpAddr, 20),
15395 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15396 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15397 DAG.getConstant(22, MVT::i64));
15398 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15399 MachinePointerInfo(TrmpAddr, 22),
15402 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15404 const Function *Func =
15405 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15406 CallingConv::ID CC = Func->getCallingConv();
15411 llvm_unreachable("Unsupported calling convention");
15412 case CallingConv::C:
15413 case CallingConv::X86_StdCall: {
15414 // Pass 'nest' parameter in ECX.
15415 // Must be kept in sync with X86CallingConv.td
15416 NestReg = X86::ECX;
15418 // Check that ECX wasn't needed by an 'inreg' parameter.
15419 FunctionType *FTy = Func->getFunctionType();
15420 const AttributeSet &Attrs = Func->getAttributes();
15422 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15423 unsigned InRegCount = 0;
15426 for (FunctionType::param_iterator I = FTy->param_begin(),
15427 E = FTy->param_end(); I != E; ++I, ++Idx)
15428 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15429 // FIXME: should only count parameters that are lowered to integers.
15430 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15432 if (InRegCount > 2) {
15433 report_fatal_error("Nest register in use - reduce number of inreg"
15439 case CallingConv::X86_FastCall:
15440 case CallingConv::X86_ThisCall:
15441 case CallingConv::Fast:
15442 // Pass 'nest' parameter in EAX.
15443 // Must be kept in sync with X86CallingConv.td
15444 NestReg = X86::EAX;
15448 SDValue OutChains[4];
15449 SDValue Addr, Disp;
15451 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15452 DAG.getConstant(10, MVT::i32));
15453 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15455 // This is storing the opcode for MOV32ri.
15456 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15457 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15458 OutChains[0] = DAG.getStore(Root, dl,
15459 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15460 Trmp, MachinePointerInfo(TrmpAddr),
15463 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15464 DAG.getConstant(1, MVT::i32));
15465 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15466 MachinePointerInfo(TrmpAddr, 1),
15469 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15470 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15471 DAG.getConstant(5, MVT::i32));
15472 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15473 MachinePointerInfo(TrmpAddr, 5),
15476 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15477 DAG.getConstant(6, MVT::i32));
15478 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15479 MachinePointerInfo(TrmpAddr, 6),
15482 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15486 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15487 SelectionDAG &DAG) const {
15489 The rounding mode is in bits 11:10 of FPSR, and has the following
15491 00 Round to nearest
15496 FLT_ROUNDS, on the other hand, expects the following:
15503 To perform the conversion, we do:
15504 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15507 MachineFunction &MF = DAG.getMachineFunction();
15508 const TargetMachine &TM = MF.getTarget();
15509 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15510 unsigned StackAlignment = TFI.getStackAlignment();
15511 MVT VT = Op.getSimpleValueType();
15514 // Save FP Control Word to stack slot
15515 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15516 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15518 MachineMemOperand *MMO =
15519 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15520 MachineMemOperand::MOStore, 2, 2);
15522 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15523 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15524 DAG.getVTList(MVT::Other),
15525 Ops, MVT::i16, MMO);
15527 // Load FP Control Word from stack slot
15528 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15529 MachinePointerInfo(), false, false, false, 0);
15531 // Transform as necessary
15533 DAG.getNode(ISD::SRL, DL, MVT::i16,
15534 DAG.getNode(ISD::AND, DL, MVT::i16,
15535 CWD, DAG.getConstant(0x800, MVT::i16)),
15536 DAG.getConstant(11, MVT::i8));
15538 DAG.getNode(ISD::SRL, DL, MVT::i16,
15539 DAG.getNode(ISD::AND, DL, MVT::i16,
15540 CWD, DAG.getConstant(0x400, MVT::i16)),
15541 DAG.getConstant(9, MVT::i8));
15544 DAG.getNode(ISD::AND, DL, MVT::i16,
15545 DAG.getNode(ISD::ADD, DL, MVT::i16,
15546 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15547 DAG.getConstant(1, MVT::i16)),
15548 DAG.getConstant(3, MVT::i16));
15550 return DAG.getNode((VT.getSizeInBits() < 16 ?
15551 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15554 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15555 MVT VT = Op.getSimpleValueType();
15557 unsigned NumBits = VT.getSizeInBits();
15560 Op = Op.getOperand(0);
15561 if (VT == MVT::i8) {
15562 // Zero extend to i32 since there is not an i8 bsr.
15564 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15567 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15568 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15569 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15571 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15574 DAG.getConstant(NumBits+NumBits-1, OpVT),
15575 DAG.getConstant(X86::COND_E, MVT::i8),
15578 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15580 // Finally xor with NumBits-1.
15581 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15584 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15588 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15589 MVT VT = Op.getSimpleValueType();
15591 unsigned NumBits = VT.getSizeInBits();
15594 Op = Op.getOperand(0);
15595 if (VT == MVT::i8) {
15596 // Zero extend to i32 since there is not an i8 bsr.
15598 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15601 // Issue a bsr (scan bits in reverse).
15602 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15603 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15605 // And xor with NumBits-1.
15606 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15609 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15613 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15614 MVT VT = Op.getSimpleValueType();
15615 unsigned NumBits = VT.getSizeInBits();
15617 Op = Op.getOperand(0);
15619 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15620 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15621 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15623 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15626 DAG.getConstant(NumBits, VT),
15627 DAG.getConstant(X86::COND_E, MVT::i8),
15630 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15633 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15634 // ones, and then concatenate the result back.
15635 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15636 MVT VT = Op.getSimpleValueType();
15638 assert(VT.is256BitVector() && VT.isInteger() &&
15639 "Unsupported value type for operation");
15641 unsigned NumElems = VT.getVectorNumElements();
15644 // Extract the LHS vectors
15645 SDValue LHS = Op.getOperand(0);
15646 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15647 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15649 // Extract the RHS vectors
15650 SDValue RHS = Op.getOperand(1);
15651 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15652 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15654 MVT EltVT = VT.getVectorElementType();
15655 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15657 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15658 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15659 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15662 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15663 assert(Op.getSimpleValueType().is256BitVector() &&
15664 Op.getSimpleValueType().isInteger() &&
15665 "Only handle AVX 256-bit vector integer operation");
15666 return Lower256IntArith(Op, DAG);
15669 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15670 assert(Op.getSimpleValueType().is256BitVector() &&
15671 Op.getSimpleValueType().isInteger() &&
15672 "Only handle AVX 256-bit vector integer operation");
15673 return Lower256IntArith(Op, DAG);
15676 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15677 SelectionDAG &DAG) {
15679 MVT VT = Op.getSimpleValueType();
15681 // Decompose 256-bit ops into smaller 128-bit ops.
15682 if (VT.is256BitVector() && !Subtarget->hasInt256())
15683 return Lower256IntArith(Op, DAG);
15685 SDValue A = Op.getOperand(0);
15686 SDValue B = Op.getOperand(1);
15688 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15689 if (VT == MVT::v4i32) {
15690 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15691 "Should not custom lower when pmuldq is available!");
15693 // Extract the odd parts.
15694 static const int UnpackMask[] = { 1, -1, 3, -1 };
15695 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15696 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15698 // Multiply the even parts.
15699 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15700 // Now multiply odd parts.
15701 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15703 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15704 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15706 // Merge the two vectors back together with a shuffle. This expands into 2
15708 static const int ShufMask[] = { 0, 4, 2, 6 };
15709 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15712 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15713 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15715 // Ahi = psrlqi(a, 32);
15716 // Bhi = psrlqi(b, 32);
15718 // AloBlo = pmuludq(a, b);
15719 // AloBhi = pmuludq(a, Bhi);
15720 // AhiBlo = pmuludq(Ahi, b);
15722 // AloBhi = psllqi(AloBhi, 32);
15723 // AhiBlo = psllqi(AhiBlo, 32);
15724 // return AloBlo + AloBhi + AhiBlo;
15726 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15727 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15729 // Bit cast to 32-bit vectors for MULUDQ
15730 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15731 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15732 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15733 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15734 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15735 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15737 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15738 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15739 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15741 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15742 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15744 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15745 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15748 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15749 assert(Subtarget->isTargetWin64() && "Unexpected target");
15750 EVT VT = Op.getValueType();
15751 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15752 "Unexpected return type for lowering");
15756 switch (Op->getOpcode()) {
15757 default: llvm_unreachable("Unexpected request for libcall!");
15758 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15759 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15760 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15761 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15762 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15763 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15767 SDValue InChain = DAG.getEntryNode();
15769 TargetLowering::ArgListTy Args;
15770 TargetLowering::ArgListEntry Entry;
15771 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15772 EVT ArgVT = Op->getOperand(i).getValueType();
15773 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15774 "Unexpected argument type for lowering");
15775 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15776 Entry.Node = StackPtr;
15777 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15779 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15780 Entry.Ty = PointerType::get(ArgTy,0);
15781 Entry.isSExt = false;
15782 Entry.isZExt = false;
15783 Args.push_back(Entry);
15786 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15789 TargetLowering::CallLoweringInfo CLI(DAG);
15790 CLI.setDebugLoc(dl).setChain(InChain)
15791 .setCallee(getLibcallCallingConv(LC),
15792 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15793 Callee, std::move(Args), 0)
15794 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15796 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15797 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15800 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15801 SelectionDAG &DAG) {
15802 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15803 EVT VT = Op0.getValueType();
15806 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15807 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15809 // PMULxD operations multiply each even value (starting at 0) of LHS with
15810 // the related value of RHS and produce a widen result.
15811 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15812 // => <2 x i64> <ae|cg>
15814 // In other word, to have all the results, we need to perform two PMULxD:
15815 // 1. one with the even values.
15816 // 2. one with the odd values.
15817 // To achieve #2, with need to place the odd values at an even position.
15819 // Place the odd value at an even position (basically, shift all values 1
15820 // step to the left):
15821 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15822 // <a|b|c|d> => <b|undef|d|undef>
15823 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15824 // <e|f|g|h> => <f|undef|h|undef>
15825 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15827 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15829 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15830 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15832 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15833 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15834 // => <2 x i64> <ae|cg>
15835 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15836 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15837 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15838 // => <2 x i64> <bf|dh>
15839 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15840 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15842 // Shuffle it back into the right order.
15843 SDValue Highs, Lows;
15844 if (VT == MVT::v8i32) {
15845 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15846 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15847 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15848 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15850 const int HighMask[] = {1, 5, 3, 7};
15851 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15852 const int LowMask[] = {0, 4, 2, 6};
15853 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15856 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15857 // unsigned multiply.
15858 if (IsSigned && !Subtarget->hasSSE41()) {
15860 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15861 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15862 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15863 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15864 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15866 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15867 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15870 // The first result of MUL_LOHI is actually the low value, followed by the
15872 SDValue Ops[] = {Lows, Highs};
15873 return DAG.getMergeValues(Ops, dl);
15876 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15877 const X86Subtarget *Subtarget) {
15878 MVT VT = Op.getSimpleValueType();
15880 SDValue R = Op.getOperand(0);
15881 SDValue Amt = Op.getOperand(1);
15883 // Optimize shl/srl/sra with constant shift amount.
15884 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15885 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15886 uint64_t ShiftAmt = ShiftConst->getZExtValue();
15888 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15889 (Subtarget->hasInt256() &&
15890 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15891 (Subtarget->hasAVX512() &&
15892 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15893 if (Op.getOpcode() == ISD::SHL)
15894 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15896 if (Op.getOpcode() == ISD::SRL)
15897 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15899 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15900 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15904 if (VT == MVT::v16i8) {
15905 if (Op.getOpcode() == ISD::SHL) {
15906 // Make a large shift.
15907 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15908 MVT::v8i16, R, ShiftAmt,
15910 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15911 // Zero out the rightmost bits.
15912 SmallVector<SDValue, 16> V(16,
15913 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15915 return DAG.getNode(ISD::AND, dl, VT, SHL,
15916 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15918 if (Op.getOpcode() == ISD::SRL) {
15919 // Make a large shift.
15920 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15921 MVT::v8i16, R, ShiftAmt,
15923 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15924 // Zero out the leftmost bits.
15925 SmallVector<SDValue, 16> V(16,
15926 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15928 return DAG.getNode(ISD::AND, dl, VT, SRL,
15929 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15931 if (Op.getOpcode() == ISD::SRA) {
15932 if (ShiftAmt == 7) {
15933 // R s>> 7 === R s< 0
15934 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15935 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15938 // R s>> a === ((R u>> a) ^ m) - m
15939 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15940 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15942 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15943 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15944 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15947 llvm_unreachable("Unknown shift opcode.");
15950 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15951 if (Op.getOpcode() == ISD::SHL) {
15952 // Make a large shift.
15953 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15954 MVT::v16i16, R, ShiftAmt,
15956 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15957 // Zero out the rightmost bits.
15958 SmallVector<SDValue, 32> V(32,
15959 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15961 return DAG.getNode(ISD::AND, dl, VT, SHL,
15962 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15964 if (Op.getOpcode() == ISD::SRL) {
15965 // Make a large shift.
15966 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15967 MVT::v16i16, R, ShiftAmt,
15969 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15970 // Zero out the leftmost bits.
15971 SmallVector<SDValue, 32> V(32,
15972 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15974 return DAG.getNode(ISD::AND, dl, VT, SRL,
15975 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15977 if (Op.getOpcode() == ISD::SRA) {
15978 if (ShiftAmt == 7) {
15979 // R s>> 7 === R s< 0
15980 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15981 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15984 // R s>> a === ((R u>> a) ^ m) - m
15985 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15986 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15988 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15989 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15990 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15993 llvm_unreachable("Unknown shift opcode.");
15998 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15999 if (!Subtarget->is64Bit() &&
16000 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16001 Amt.getOpcode() == ISD::BITCAST &&
16002 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16003 Amt = Amt.getOperand(0);
16004 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16005 VT.getVectorNumElements();
16006 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16007 uint64_t ShiftAmt = 0;
16008 for (unsigned i = 0; i != Ratio; ++i) {
16009 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16013 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16015 // Check remaining shift amounts.
16016 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16017 uint64_t ShAmt = 0;
16018 for (unsigned j = 0; j != Ratio; ++j) {
16019 ConstantSDNode *C =
16020 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16024 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16026 if (ShAmt != ShiftAmt)
16029 switch (Op.getOpcode()) {
16031 llvm_unreachable("Unknown shift opcode!");
16033 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16036 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16039 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16047 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16048 const X86Subtarget* Subtarget) {
16049 MVT VT = Op.getSimpleValueType();
16051 SDValue R = Op.getOperand(0);
16052 SDValue Amt = Op.getOperand(1);
16054 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16055 VT == MVT::v4i32 || VT == MVT::v8i16 ||
16056 (Subtarget->hasInt256() &&
16057 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16058 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16059 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16061 EVT EltVT = VT.getVectorElementType();
16063 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16064 unsigned NumElts = VT.getVectorNumElements();
16066 for (i = 0; i != NumElts; ++i) {
16067 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
16071 for (j = i; j != NumElts; ++j) {
16072 SDValue Arg = Amt.getOperand(j);
16073 if (Arg.getOpcode() == ISD::UNDEF) continue;
16074 if (Arg != Amt.getOperand(i))
16077 if (i != NumElts && j == NumElts)
16078 BaseShAmt = Amt.getOperand(i);
16080 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16081 Amt = Amt.getOperand(0);
16082 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
16083 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
16084 SDValue InVec = Amt.getOperand(0);
16085 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16086 unsigned NumElts = InVec.getValueType().getVectorNumElements();
16088 for (; i != NumElts; ++i) {
16089 SDValue Arg = InVec.getOperand(i);
16090 if (Arg.getOpcode() == ISD::UNDEF) continue;
16094 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16095 if (ConstantSDNode *C =
16096 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16097 unsigned SplatIdx =
16098 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16099 if (C->getZExtValue() == SplatIdx)
16100 BaseShAmt = InVec.getOperand(1);
16103 if (!BaseShAmt.getNode())
16104 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16105 DAG.getIntPtrConstant(0));
16109 if (BaseShAmt.getNode()) {
16110 if (EltVT.bitsGT(MVT::i32))
16111 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16112 else if (EltVT.bitsLT(MVT::i32))
16113 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16115 switch (Op.getOpcode()) {
16117 llvm_unreachable("Unknown shift opcode!");
16119 switch (VT.SimpleTy) {
16120 default: return SDValue();
16129 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16132 switch (VT.SimpleTy) {
16133 default: return SDValue();
16140 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16143 switch (VT.SimpleTy) {
16144 default: return SDValue();
16153 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16159 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16160 if (!Subtarget->is64Bit() &&
16161 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16162 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16163 Amt.getOpcode() == ISD::BITCAST &&
16164 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16165 Amt = Amt.getOperand(0);
16166 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16167 VT.getVectorNumElements();
16168 std::vector<SDValue> Vals(Ratio);
16169 for (unsigned i = 0; i != Ratio; ++i)
16170 Vals[i] = Amt.getOperand(i);
16171 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16172 for (unsigned j = 0; j != Ratio; ++j)
16173 if (Vals[j] != Amt.getOperand(i + j))
16176 switch (Op.getOpcode()) {
16178 llvm_unreachable("Unknown shift opcode!");
16180 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16182 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16184 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16191 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16192 SelectionDAG &DAG) {
16193 MVT VT = Op.getSimpleValueType();
16195 SDValue R = Op.getOperand(0);
16196 SDValue Amt = Op.getOperand(1);
16199 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16200 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16202 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16206 V = LowerScalarVariableShift(Op, DAG, Subtarget);
16210 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16212 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16213 if (Subtarget->hasInt256()) {
16214 if (Op.getOpcode() == ISD::SRL &&
16215 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16216 VT == MVT::v4i64 || VT == MVT::v8i32))
16218 if (Op.getOpcode() == ISD::SHL &&
16219 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16220 VT == MVT::v4i64 || VT == MVT::v8i32))
16222 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16226 // If possible, lower this packed shift into a vector multiply instead of
16227 // expanding it into a sequence of scalar shifts.
16228 // Do this only if the vector shift count is a constant build_vector.
16229 if (Op.getOpcode() == ISD::SHL &&
16230 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16231 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16232 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16233 SmallVector<SDValue, 8> Elts;
16234 EVT SVT = VT.getScalarType();
16235 unsigned SVTBits = SVT.getSizeInBits();
16236 const APInt &One = APInt(SVTBits, 1);
16237 unsigned NumElems = VT.getVectorNumElements();
16239 for (unsigned i=0; i !=NumElems; ++i) {
16240 SDValue Op = Amt->getOperand(i);
16241 if (Op->getOpcode() == ISD::UNDEF) {
16242 Elts.push_back(Op);
16246 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16247 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16248 uint64_t ShAmt = C.getZExtValue();
16249 if (ShAmt >= SVTBits) {
16250 Elts.push_back(DAG.getUNDEF(SVT));
16253 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16255 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16256 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16259 // Lower SHL with variable shift amount.
16260 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16261 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16263 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16264 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16265 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16266 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16269 // If possible, lower this shift as a sequence of two shifts by
16270 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16272 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16274 // Could be rewritten as:
16275 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16277 // The advantage is that the two shifts from the example would be
16278 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16279 // the vector shift into four scalar shifts plus four pairs of vector
16281 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16282 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16283 unsigned TargetOpcode = X86ISD::MOVSS;
16284 bool CanBeSimplified;
16285 // The splat value for the first packed shift (the 'X' from the example).
16286 SDValue Amt1 = Amt->getOperand(0);
16287 // The splat value for the second packed shift (the 'Y' from the example).
16288 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16289 Amt->getOperand(2);
16291 // See if it is possible to replace this node with a sequence of
16292 // two shifts followed by a MOVSS/MOVSD
16293 if (VT == MVT::v4i32) {
16294 // Check if it is legal to use a MOVSS.
16295 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16296 Amt2 == Amt->getOperand(3);
16297 if (!CanBeSimplified) {
16298 // Otherwise, check if we can still simplify this node using a MOVSD.
16299 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16300 Amt->getOperand(2) == Amt->getOperand(3);
16301 TargetOpcode = X86ISD::MOVSD;
16302 Amt2 = Amt->getOperand(2);
16305 // Do similar checks for the case where the machine value type
16307 CanBeSimplified = Amt1 == Amt->getOperand(1);
16308 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16309 CanBeSimplified = Amt2 == Amt->getOperand(i);
16311 if (!CanBeSimplified) {
16312 TargetOpcode = X86ISD::MOVSD;
16313 CanBeSimplified = true;
16314 Amt2 = Amt->getOperand(4);
16315 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16316 CanBeSimplified = Amt1 == Amt->getOperand(i);
16317 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16318 CanBeSimplified = Amt2 == Amt->getOperand(j);
16322 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16323 isa<ConstantSDNode>(Amt2)) {
16324 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16325 EVT CastVT = MVT::v4i32;
16327 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16328 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16330 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16331 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16332 if (TargetOpcode == X86ISD::MOVSD)
16333 CastVT = MVT::v2i64;
16334 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16335 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16336 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16338 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16342 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16343 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16346 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16347 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16349 // Turn 'a' into a mask suitable for VSELECT
16350 SDValue VSelM = DAG.getConstant(0x80, VT);
16351 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16352 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16354 SDValue CM1 = DAG.getConstant(0x0f, VT);
16355 SDValue CM2 = DAG.getConstant(0x3f, VT);
16357 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16358 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16359 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16360 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16361 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16364 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16365 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16366 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16368 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16369 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16370 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16371 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16372 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16375 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16376 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16377 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16379 // return VSELECT(r, r+r, a);
16380 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16381 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16385 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16386 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16387 // solution better.
16388 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16389 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16391 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16392 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16393 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16394 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16395 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16398 // Decompose 256-bit shifts into smaller 128-bit shifts.
16399 if (VT.is256BitVector()) {
16400 unsigned NumElems = VT.getVectorNumElements();
16401 MVT EltVT = VT.getVectorElementType();
16402 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16404 // Extract the two vectors
16405 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16406 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16408 // Recreate the shift amount vectors
16409 SDValue Amt1, Amt2;
16410 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16411 // Constant shift amount
16412 SmallVector<SDValue, 4> Amt1Csts;
16413 SmallVector<SDValue, 4> Amt2Csts;
16414 for (unsigned i = 0; i != NumElems/2; ++i)
16415 Amt1Csts.push_back(Amt->getOperand(i));
16416 for (unsigned i = NumElems/2; i != NumElems; ++i)
16417 Amt2Csts.push_back(Amt->getOperand(i));
16419 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16420 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16422 // Variable shift amount
16423 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16424 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16427 // Issue new vector shifts for the smaller types
16428 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16429 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16431 // Concatenate the result back
16432 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16438 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16439 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16440 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16441 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16442 // has only one use.
16443 SDNode *N = Op.getNode();
16444 SDValue LHS = N->getOperand(0);
16445 SDValue RHS = N->getOperand(1);
16446 unsigned BaseOp = 0;
16449 switch (Op.getOpcode()) {
16450 default: llvm_unreachable("Unknown ovf instruction!");
16452 // A subtract of one will be selected as a INC. Note that INC doesn't
16453 // set CF, so we can't do this for UADDO.
16454 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16456 BaseOp = X86ISD::INC;
16457 Cond = X86::COND_O;
16460 BaseOp = X86ISD::ADD;
16461 Cond = X86::COND_O;
16464 BaseOp = X86ISD::ADD;
16465 Cond = X86::COND_B;
16468 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16469 // set CF, so we can't do this for USUBO.
16470 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16472 BaseOp = X86ISD::DEC;
16473 Cond = X86::COND_O;
16476 BaseOp = X86ISD::SUB;
16477 Cond = X86::COND_O;
16480 BaseOp = X86ISD::SUB;
16481 Cond = X86::COND_B;
16484 BaseOp = X86ISD::SMUL;
16485 Cond = X86::COND_O;
16487 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16488 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16490 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16493 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16494 DAG.getConstant(X86::COND_O, MVT::i32),
16495 SDValue(Sum.getNode(), 2));
16497 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16501 // Also sets EFLAGS.
16502 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16503 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16506 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16507 DAG.getConstant(Cond, MVT::i32),
16508 SDValue(Sum.getNode(), 1));
16510 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16513 // Sign extension of the low part of vector elements. This may be used either
16514 // when sign extend instructions are not available or if the vector element
16515 // sizes already match the sign-extended size. If the vector elements are in
16516 // their pre-extended size and sign extend instructions are available, that will
16517 // be handled by LowerSIGN_EXTEND.
16518 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16519 SelectionDAG &DAG) const {
16521 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16522 MVT VT = Op.getSimpleValueType();
16524 if (!Subtarget->hasSSE2() || !VT.isVector())
16527 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16528 ExtraVT.getScalarType().getSizeInBits();
16530 switch (VT.SimpleTy) {
16531 default: return SDValue();
16534 if (!Subtarget->hasFp256())
16536 if (!Subtarget->hasInt256()) {
16537 // needs to be split
16538 unsigned NumElems = VT.getVectorNumElements();
16540 // Extract the LHS vectors
16541 SDValue LHS = Op.getOperand(0);
16542 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16543 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16545 MVT EltVT = VT.getVectorElementType();
16546 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16548 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16549 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16550 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16552 SDValue Extra = DAG.getValueType(ExtraVT);
16554 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16555 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16557 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16562 SDValue Op0 = Op.getOperand(0);
16564 // This is a sign extension of some low part of vector elements without
16565 // changing the size of the vector elements themselves:
16566 // Shift-Left + Shift-Right-Algebraic.
16567 SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
16569 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
16575 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16576 SelectionDAG &DAG) {
16578 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16579 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16580 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16581 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16583 // The only fence that needs an instruction is a sequentially-consistent
16584 // cross-thread fence.
16585 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16586 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16587 // no-sse2). There isn't any reason to disable it if the target processor
16589 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16590 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16592 SDValue Chain = Op.getOperand(0);
16593 SDValue Zero = DAG.getConstant(0, MVT::i32);
16595 DAG.getRegister(X86::ESP, MVT::i32), // Base
16596 DAG.getTargetConstant(1, MVT::i8), // Scale
16597 DAG.getRegister(0, MVT::i32), // Index
16598 DAG.getTargetConstant(0, MVT::i32), // Disp
16599 DAG.getRegister(0, MVT::i32), // Segment.
16603 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16604 return SDValue(Res, 0);
16607 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16608 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16611 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16612 SelectionDAG &DAG) {
16613 MVT T = Op.getSimpleValueType();
16617 switch(T.SimpleTy) {
16618 default: llvm_unreachable("Invalid value type!");
16619 case MVT::i8: Reg = X86::AL; size = 1; break;
16620 case MVT::i16: Reg = X86::AX; size = 2; break;
16621 case MVT::i32: Reg = X86::EAX; size = 4; break;
16623 assert(Subtarget->is64Bit() && "Node not type legal!");
16624 Reg = X86::RAX; size = 8;
16627 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16628 Op.getOperand(2), SDValue());
16629 SDValue Ops[] = { cpIn.getValue(0),
16632 DAG.getTargetConstant(size, MVT::i8),
16633 cpIn.getValue(1) };
16634 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16635 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16636 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16640 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16641 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16642 MVT::i32, cpOut.getValue(2));
16643 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16644 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16646 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16647 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16648 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16652 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16653 SelectionDAG &DAG) {
16654 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16655 MVT DstVT = Op.getSimpleValueType();
16657 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16658 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16659 if (DstVT != MVT::f64)
16660 // This conversion needs to be expanded.
16663 SDValue InVec = Op->getOperand(0);
16665 unsigned NumElts = SrcVT.getVectorNumElements();
16666 EVT SVT = SrcVT.getVectorElementType();
16668 // Widen the vector in input in the case of MVT::v2i32.
16669 // Example: from MVT::v2i32 to MVT::v4i32.
16670 SmallVector<SDValue, 16> Elts;
16671 for (unsigned i = 0, e = NumElts; i != e; ++i)
16672 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16673 DAG.getIntPtrConstant(i)));
16675 // Explicitly mark the extra elements as Undef.
16676 SDValue Undef = DAG.getUNDEF(SVT);
16677 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16678 Elts.push_back(Undef);
16680 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16681 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16682 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16683 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16684 DAG.getIntPtrConstant(0));
16687 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16688 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16689 assert((DstVT == MVT::i64 ||
16690 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16691 "Unexpected custom BITCAST");
16692 // i64 <=> MMX conversions are Legal.
16693 if (SrcVT==MVT::i64 && DstVT.isVector())
16695 if (DstVT==MVT::i64 && SrcVT.isVector())
16697 // MMX <=> MMX conversions are Legal.
16698 if (SrcVT.isVector() && DstVT.isVector())
16700 // All other conversions need to be expanded.
16704 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16705 SDNode *Node = Op.getNode();
16707 EVT T = Node->getValueType(0);
16708 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16709 DAG.getConstant(0, T), Node->getOperand(2));
16710 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16711 cast<AtomicSDNode>(Node)->getMemoryVT(),
16712 Node->getOperand(0),
16713 Node->getOperand(1), negOp,
16714 cast<AtomicSDNode>(Node)->getMemOperand(),
16715 cast<AtomicSDNode>(Node)->getOrdering(),
16716 cast<AtomicSDNode>(Node)->getSynchScope());
16719 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16720 SDNode *Node = Op.getNode();
16722 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16724 // Convert seq_cst store -> xchg
16725 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16726 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16727 // (The only way to get a 16-byte store is cmpxchg16b)
16728 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16729 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16730 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16731 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16732 cast<AtomicSDNode>(Node)->getMemoryVT(),
16733 Node->getOperand(0),
16734 Node->getOperand(1), Node->getOperand(2),
16735 cast<AtomicSDNode>(Node)->getMemOperand(),
16736 cast<AtomicSDNode>(Node)->getOrdering(),
16737 cast<AtomicSDNode>(Node)->getSynchScope());
16738 return Swap.getValue(1);
16740 // Other atomic stores have a simple pattern.
16744 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16745 EVT VT = Op.getNode()->getSimpleValueType(0);
16747 // Let legalize expand this if it isn't a legal type yet.
16748 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16751 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16754 bool ExtraOp = false;
16755 switch (Op.getOpcode()) {
16756 default: llvm_unreachable("Invalid code");
16757 case ISD::ADDC: Opc = X86ISD::ADD; break;
16758 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16759 case ISD::SUBC: Opc = X86ISD::SUB; break;
16760 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16764 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16766 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16767 Op.getOperand(1), Op.getOperand(2));
16770 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16771 SelectionDAG &DAG) {
16772 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16774 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16775 // which returns the values as { float, float } (in XMM0) or
16776 // { double, double } (which is returned in XMM0, XMM1).
16778 SDValue Arg = Op.getOperand(0);
16779 EVT ArgVT = Arg.getValueType();
16780 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16782 TargetLowering::ArgListTy Args;
16783 TargetLowering::ArgListEntry Entry;
16787 Entry.isSExt = false;
16788 Entry.isZExt = false;
16789 Args.push_back(Entry);
16791 bool isF64 = ArgVT == MVT::f64;
16792 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16793 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16794 // the results are returned via SRet in memory.
16795 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16796 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16797 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16799 Type *RetTy = isF64
16800 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16801 : (Type*)VectorType::get(ArgTy, 4);
16803 TargetLowering::CallLoweringInfo CLI(DAG);
16804 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16805 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16807 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16810 // Returned in xmm0 and xmm1.
16811 return CallResult.first;
16813 // Returned in bits 0:31 and 32:64 xmm0.
16814 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16815 CallResult.first, DAG.getIntPtrConstant(0));
16816 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16817 CallResult.first, DAG.getIntPtrConstant(1));
16818 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16819 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16822 /// LowerOperation - Provide custom lowering hooks for some operations.
16824 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16825 switch (Op.getOpcode()) {
16826 default: llvm_unreachable("Should not custom lower this!");
16827 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
16828 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16829 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16830 return LowerCMP_SWAP(Op, Subtarget, DAG);
16831 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16832 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16833 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16834 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16835 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
16836 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16837 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16838 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16839 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16840 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16841 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16842 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16843 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16844 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16845 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16846 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16847 case ISD::SHL_PARTS:
16848 case ISD::SRA_PARTS:
16849 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16850 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16851 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16852 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16853 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16854 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16855 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16856 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16857 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16858 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16859 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
16860 case ISD::FABS: return LowerFABS(Op, DAG);
16861 case ISD::FNEG: return LowerFNEG(Op, DAG);
16862 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16863 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16864 case ISD::SETCC: return LowerSETCC(Op, DAG);
16865 case ISD::SELECT: return LowerSELECT(Op, DAG);
16866 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16867 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16868 case ISD::VASTART: return LowerVASTART(Op, DAG);
16869 case ISD::VAARG: return LowerVAARG(Op, DAG);
16870 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16871 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16872 case ISD::INTRINSIC_VOID:
16873 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16874 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16875 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16876 case ISD::FRAME_TO_ARGS_OFFSET:
16877 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16878 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16879 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16880 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16881 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16882 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16883 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16884 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16885 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16886 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16887 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16888 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16889 case ISD::UMUL_LOHI:
16890 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16893 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16899 case ISD::UMULO: return LowerXALUO(Op, DAG);
16900 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16901 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16905 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16906 case ISD::ADD: return LowerADD(Op, DAG);
16907 case ISD::SUB: return LowerSUB(Op, DAG);
16908 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16912 static void ReplaceATOMIC_LOAD(SDNode *Node,
16913 SmallVectorImpl<SDValue> &Results,
16914 SelectionDAG &DAG) {
16916 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16918 // Convert wide load -> cmpxchg8b/cmpxchg16b
16919 // FIXME: On 32-bit, load -> fild or movq would be more efficient
16920 // (The only way to get a 16-byte load is cmpxchg16b)
16921 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16922 SDValue Zero = DAG.getConstant(0, VT);
16923 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16925 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16926 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16927 cast<AtomicSDNode>(Node)->getMemOperand(),
16928 cast<AtomicSDNode>(Node)->getOrdering(),
16929 cast<AtomicSDNode>(Node)->getOrdering(),
16930 cast<AtomicSDNode>(Node)->getSynchScope());
16931 Results.push_back(Swap.getValue(0));
16932 Results.push_back(Swap.getValue(2));
16935 /// ReplaceNodeResults - Replace a node with an illegal result type
16936 /// with a new node built out of custom code.
16937 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16938 SmallVectorImpl<SDValue>&Results,
16939 SelectionDAG &DAG) const {
16941 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16942 switch (N->getOpcode()) {
16944 llvm_unreachable("Do not know how to custom type legalize this operation!");
16945 case ISD::SIGN_EXTEND_INREG:
16950 // We don't want to expand or promote these.
16957 case ISD::UDIVREM: {
16958 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16959 Results.push_back(V);
16962 case ISD::FP_TO_SINT:
16963 case ISD::FP_TO_UINT: {
16964 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16966 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16969 std::pair<SDValue,SDValue> Vals =
16970 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16971 SDValue FIST = Vals.first, StackSlot = Vals.second;
16972 if (FIST.getNode()) {
16973 EVT VT = N->getValueType(0);
16974 // Return a load from the stack slot.
16975 if (StackSlot.getNode())
16976 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16977 MachinePointerInfo(),
16978 false, false, false, 0));
16980 Results.push_back(FIST);
16984 case ISD::UINT_TO_FP: {
16985 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16986 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16987 N->getValueType(0) != MVT::v2f32)
16989 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16991 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16993 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16994 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16995 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16996 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16997 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16998 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17001 case ISD::FP_ROUND: {
17002 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17004 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17005 Results.push_back(V);
17008 case ISD::INTRINSIC_W_CHAIN: {
17009 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17011 default : llvm_unreachable("Do not know how to custom type "
17012 "legalize this intrinsic operation!");
17013 case Intrinsic::x86_rdtsc:
17014 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17016 case Intrinsic::x86_rdtscp:
17017 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17019 case Intrinsic::x86_rdpmc:
17020 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17023 case ISD::READCYCLECOUNTER: {
17024 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17027 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17028 EVT T = N->getValueType(0);
17029 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17030 bool Regs64bit = T == MVT::i128;
17031 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17032 SDValue cpInL, cpInH;
17033 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17034 DAG.getConstant(0, HalfT));
17035 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17036 DAG.getConstant(1, HalfT));
17037 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17038 Regs64bit ? X86::RAX : X86::EAX,
17040 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17041 Regs64bit ? X86::RDX : X86::EDX,
17042 cpInH, cpInL.getValue(1));
17043 SDValue swapInL, swapInH;
17044 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17045 DAG.getConstant(0, HalfT));
17046 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17047 DAG.getConstant(1, HalfT));
17048 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17049 Regs64bit ? X86::RBX : X86::EBX,
17050 swapInL, cpInH.getValue(1));
17051 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17052 Regs64bit ? X86::RCX : X86::ECX,
17053 swapInH, swapInL.getValue(1));
17054 SDValue Ops[] = { swapInH.getValue(0),
17056 swapInH.getValue(1) };
17057 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17058 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17059 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17060 X86ISD::LCMPXCHG8_DAG;
17061 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17062 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17063 Regs64bit ? X86::RAX : X86::EAX,
17064 HalfT, Result.getValue(1));
17065 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17066 Regs64bit ? X86::RDX : X86::EDX,
17067 HalfT, cpOutL.getValue(2));
17068 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17070 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17071 MVT::i32, cpOutH.getValue(2));
17073 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17074 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17075 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17077 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17078 Results.push_back(Success);
17079 Results.push_back(EFLAGS.getValue(1));
17082 case ISD::ATOMIC_SWAP:
17083 case ISD::ATOMIC_LOAD_ADD:
17084 case ISD::ATOMIC_LOAD_SUB:
17085 case ISD::ATOMIC_LOAD_AND:
17086 case ISD::ATOMIC_LOAD_OR:
17087 case ISD::ATOMIC_LOAD_XOR:
17088 case ISD::ATOMIC_LOAD_NAND:
17089 case ISD::ATOMIC_LOAD_MIN:
17090 case ISD::ATOMIC_LOAD_MAX:
17091 case ISD::ATOMIC_LOAD_UMIN:
17092 case ISD::ATOMIC_LOAD_UMAX:
17093 // Delegate to generic TypeLegalization. Situations we can really handle
17094 // should have already been dealt with by X86AtomicExpandPass.cpp.
17096 case ISD::ATOMIC_LOAD: {
17097 ReplaceATOMIC_LOAD(N, Results, DAG);
17100 case ISD::BITCAST: {
17101 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17102 EVT DstVT = N->getValueType(0);
17103 EVT SrcVT = N->getOperand(0)->getValueType(0);
17105 if (SrcVT != MVT::f64 ||
17106 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17109 unsigned NumElts = DstVT.getVectorNumElements();
17110 EVT SVT = DstVT.getVectorElementType();
17111 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17112 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17113 MVT::v2f64, N->getOperand(0));
17114 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17116 if (ExperimentalVectorWideningLegalization) {
17117 // If we are legalizing vectors by widening, we already have the desired
17118 // legal vector type, just return it.
17119 Results.push_back(ToVecInt);
17123 SmallVector<SDValue, 8> Elts;
17124 for (unsigned i = 0, e = NumElts; i != e; ++i)
17125 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17126 ToVecInt, DAG.getIntPtrConstant(i)));
17128 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17133 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17135 default: return nullptr;
17136 case X86ISD::BSF: return "X86ISD::BSF";
17137 case X86ISD::BSR: return "X86ISD::BSR";
17138 case X86ISD::SHLD: return "X86ISD::SHLD";
17139 case X86ISD::SHRD: return "X86ISD::SHRD";
17140 case X86ISD::FAND: return "X86ISD::FAND";
17141 case X86ISD::FANDN: return "X86ISD::FANDN";
17142 case X86ISD::FOR: return "X86ISD::FOR";
17143 case X86ISD::FXOR: return "X86ISD::FXOR";
17144 case X86ISD::FSRL: return "X86ISD::FSRL";
17145 case X86ISD::FILD: return "X86ISD::FILD";
17146 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17147 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17148 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17149 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17150 case X86ISD::FLD: return "X86ISD::FLD";
17151 case X86ISD::FST: return "X86ISD::FST";
17152 case X86ISD::CALL: return "X86ISD::CALL";
17153 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17154 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17155 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17156 case X86ISD::BT: return "X86ISD::BT";
17157 case X86ISD::CMP: return "X86ISD::CMP";
17158 case X86ISD::COMI: return "X86ISD::COMI";
17159 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17160 case X86ISD::CMPM: return "X86ISD::CMPM";
17161 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17162 case X86ISD::SETCC: return "X86ISD::SETCC";
17163 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17164 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17165 case X86ISD::CMOV: return "X86ISD::CMOV";
17166 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17167 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17168 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17169 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17170 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17171 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17172 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17173 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17174 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17175 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17176 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17177 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17178 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17179 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17180 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17181 case X86ISD::BLENDV: return "X86ISD::BLENDV";
17182 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17183 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17184 case X86ISD::HADD: return "X86ISD::HADD";
17185 case X86ISD::HSUB: return "X86ISD::HSUB";
17186 case X86ISD::FHADD: return "X86ISD::FHADD";
17187 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17188 case X86ISD::UMAX: return "X86ISD::UMAX";
17189 case X86ISD::UMIN: return "X86ISD::UMIN";
17190 case X86ISD::SMAX: return "X86ISD::SMAX";
17191 case X86ISD::SMIN: return "X86ISD::SMIN";
17192 case X86ISD::FMAX: return "X86ISD::FMAX";
17193 case X86ISD::FMIN: return "X86ISD::FMIN";
17194 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17195 case X86ISD::FMINC: return "X86ISD::FMINC";
17196 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17197 case X86ISD::FRCP: return "X86ISD::FRCP";
17198 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17199 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17200 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17201 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17202 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17203 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17204 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17205 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17206 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17207 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17208 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17209 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17210 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17211 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17212 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17213 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17214 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17215 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17216 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17217 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17218 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17219 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17220 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17221 case X86ISD::VSHL: return "X86ISD::VSHL";
17222 case X86ISD::VSRL: return "X86ISD::VSRL";
17223 case X86ISD::VSRA: return "X86ISD::VSRA";
17224 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17225 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17226 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17227 case X86ISD::CMPP: return "X86ISD::CMPP";
17228 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17229 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17230 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17231 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17232 case X86ISD::ADD: return "X86ISD::ADD";
17233 case X86ISD::SUB: return "X86ISD::SUB";
17234 case X86ISD::ADC: return "X86ISD::ADC";
17235 case X86ISD::SBB: return "X86ISD::SBB";
17236 case X86ISD::SMUL: return "X86ISD::SMUL";
17237 case X86ISD::UMUL: return "X86ISD::UMUL";
17238 case X86ISD::INC: return "X86ISD::INC";
17239 case X86ISD::DEC: return "X86ISD::DEC";
17240 case X86ISD::OR: return "X86ISD::OR";
17241 case X86ISD::XOR: return "X86ISD::XOR";
17242 case X86ISD::AND: return "X86ISD::AND";
17243 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17244 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17245 case X86ISD::PTEST: return "X86ISD::PTEST";
17246 case X86ISD::TESTP: return "X86ISD::TESTP";
17247 case X86ISD::TESTM: return "X86ISD::TESTM";
17248 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17249 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17250 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17251 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17252 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17253 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17254 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17255 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17256 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17257 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17258 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17259 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17260 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17261 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17262 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17263 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17264 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17265 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17266 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17267 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17268 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17269 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17270 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17271 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
17272 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17273 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
17274 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17275 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17276 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17277 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17278 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17279 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17280 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17281 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17282 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17283 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17284 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17285 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17286 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17287 case X86ISD::SAHF: return "X86ISD::SAHF";
17288 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17289 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17290 case X86ISD::FMADD: return "X86ISD::FMADD";
17291 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17292 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17293 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17294 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17295 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17296 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
17297 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
17298 case X86ISD::XTEST: return "X86ISD::XTEST";
17302 // isLegalAddressingMode - Return true if the addressing mode represented
17303 // by AM is legal for this target, for a load/store of the specified type.
17304 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17306 // X86 supports extremely general addressing modes.
17307 CodeModel::Model M = getTargetMachine().getCodeModel();
17308 Reloc::Model R = getTargetMachine().getRelocationModel();
17310 // X86 allows a sign-extended 32-bit immediate field as a displacement.
17311 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17316 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17318 // If a reference to this global requires an extra load, we can't fold it.
17319 if (isGlobalStubReference(GVFlags))
17322 // If BaseGV requires a register for the PIC base, we cannot also have a
17323 // BaseReg specified.
17324 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17327 // If lower 4G is not available, then we must use rip-relative addressing.
17328 if ((M != CodeModel::Small || R != Reloc::Static) &&
17329 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17333 switch (AM.Scale) {
17339 // These scales always work.
17344 // These scales are formed with basereg+scalereg. Only accept if there is
17349 default: // Other stuff never works.
17356 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17357 unsigned Bits = Ty->getScalarSizeInBits();
17359 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17360 // particularly cheaper than those without.
17364 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17365 // variable shifts just as cheap as scalar ones.
17366 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17369 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17370 // fully general vector.
17374 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17375 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17377 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17378 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17379 return NumBits1 > NumBits2;
17382 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17383 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17386 if (!isTypeLegal(EVT::getEVT(Ty1)))
17389 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17391 // Assuming the caller doesn't have a zeroext or signext return parameter,
17392 // truncation all the way down to i1 is valid.
17396 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17397 return isInt<32>(Imm);
17400 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17401 // Can also use sub to handle negated immediates.
17402 return isInt<32>(Imm);
17405 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17406 if (!VT1.isInteger() || !VT2.isInteger())
17408 unsigned NumBits1 = VT1.getSizeInBits();
17409 unsigned NumBits2 = VT2.getSizeInBits();
17410 return NumBits1 > NumBits2;
17413 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17414 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17415 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17418 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17419 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17420 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17423 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17424 EVT VT1 = Val.getValueType();
17425 if (isZExtFree(VT1, VT2))
17428 if (Val.getOpcode() != ISD::LOAD)
17431 if (!VT1.isSimple() || !VT1.isInteger() ||
17432 !VT2.isSimple() || !VT2.isInteger())
17435 switch (VT1.getSimpleVT().SimpleTy) {
17440 // X86 has 8, 16, and 32-bit zero-extending loads.
17448 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17449 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17452 VT = VT.getScalarType();
17454 if (!VT.isSimple())
17457 switch (VT.getSimpleVT().SimpleTy) {
17468 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17469 // i16 instructions are longer (0x66 prefix) and potentially slower.
17470 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17473 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17474 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17475 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17476 /// are assumed to be legal.
17478 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17480 if (!VT.isSimple())
17483 MVT SVT = VT.getSimpleVT();
17485 // Very little shuffling can be done for 64-bit vectors right now.
17486 if (VT.getSizeInBits() == 64)
17489 // If this is a single-input shuffle with no 128 bit lane crossings we can
17490 // lower it into pshufb.
17491 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17492 (SVT.is256BitVector() && Subtarget->hasInt256())) {
17493 bool isLegal = true;
17494 for (unsigned I = 0, E = M.size(); I != E; ++I) {
17495 if (M[I] >= (int)SVT.getVectorNumElements() ||
17496 ShuffleCrosses128bitLane(SVT, I, M[I])) {
17505 // FIXME: blends, shifts.
17506 return (SVT.getVectorNumElements() == 2 ||
17507 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17508 isMOVLMask(M, SVT) ||
17509 isMOVHLPSMask(M, SVT) ||
17510 isSHUFPMask(M, SVT) ||
17511 isPSHUFDMask(M, SVT) ||
17512 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17513 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17514 isPALIGNRMask(M, SVT, Subtarget) ||
17515 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17516 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17517 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17518 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17519 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17523 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17525 if (!VT.isSimple())
17528 MVT SVT = VT.getSimpleVT();
17529 unsigned NumElts = SVT.getVectorNumElements();
17530 // FIXME: This collection of masks seems suspect.
17533 if (NumElts == 4 && SVT.is128BitVector()) {
17534 return (isMOVLMask(Mask, SVT) ||
17535 isCommutedMOVLMask(Mask, SVT, true) ||
17536 isSHUFPMask(Mask, SVT) ||
17537 isSHUFPMask(Mask, SVT, /* Commuted */ true));
17542 //===----------------------------------------------------------------------===//
17543 // X86 Scheduler Hooks
17544 //===----------------------------------------------------------------------===//
17546 /// Utility function to emit xbegin specifying the start of an RTM region.
17547 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17548 const TargetInstrInfo *TII) {
17549 DebugLoc DL = MI->getDebugLoc();
17551 const BasicBlock *BB = MBB->getBasicBlock();
17552 MachineFunction::iterator I = MBB;
17555 // For the v = xbegin(), we generate
17566 MachineBasicBlock *thisMBB = MBB;
17567 MachineFunction *MF = MBB->getParent();
17568 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17569 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17570 MF->insert(I, mainMBB);
17571 MF->insert(I, sinkMBB);
17573 // Transfer the remainder of BB and its successor edges to sinkMBB.
17574 sinkMBB->splice(sinkMBB->begin(), MBB,
17575 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17576 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17580 // # fallthrough to mainMBB
17581 // # abortion to sinkMBB
17582 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17583 thisMBB->addSuccessor(mainMBB);
17584 thisMBB->addSuccessor(sinkMBB);
17588 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17589 mainMBB->addSuccessor(sinkMBB);
17592 // EAX is live into the sinkMBB
17593 sinkMBB->addLiveIn(X86::EAX);
17594 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17595 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17598 MI->eraseFromParent();
17602 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17603 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17604 // in the .td file.
17605 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17606 const TargetInstrInfo *TII) {
17608 switch (MI->getOpcode()) {
17609 default: llvm_unreachable("illegal opcode!");
17610 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17611 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17612 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17613 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17614 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17615 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17616 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17617 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17620 DebugLoc dl = MI->getDebugLoc();
17621 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17623 unsigned NumArgs = MI->getNumOperands();
17624 for (unsigned i = 1; i < NumArgs; ++i) {
17625 MachineOperand &Op = MI->getOperand(i);
17626 if (!(Op.isReg() && Op.isImplicit()))
17627 MIB.addOperand(Op);
17629 if (MI->hasOneMemOperand())
17630 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17632 BuildMI(*BB, MI, dl,
17633 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17634 .addReg(X86::XMM0);
17636 MI->eraseFromParent();
17640 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17641 // defs in an instruction pattern
17642 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17643 const TargetInstrInfo *TII) {
17645 switch (MI->getOpcode()) {
17646 default: llvm_unreachable("illegal opcode!");
17647 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17648 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17649 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17650 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17651 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17652 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17653 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17654 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17657 DebugLoc dl = MI->getDebugLoc();
17658 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17660 unsigned NumArgs = MI->getNumOperands(); // remove the results
17661 for (unsigned i = 1; i < NumArgs; ++i) {
17662 MachineOperand &Op = MI->getOperand(i);
17663 if (!(Op.isReg() && Op.isImplicit()))
17664 MIB.addOperand(Op);
17666 if (MI->hasOneMemOperand())
17667 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17669 BuildMI(*BB, MI, dl,
17670 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17673 MI->eraseFromParent();
17677 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17678 const TargetInstrInfo *TII,
17679 const X86Subtarget* Subtarget) {
17680 DebugLoc dl = MI->getDebugLoc();
17682 // Address into RAX/EAX, other two args into ECX, EDX.
17683 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17684 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17685 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17686 for (int i = 0; i < X86::AddrNumOperands; ++i)
17687 MIB.addOperand(MI->getOperand(i));
17689 unsigned ValOps = X86::AddrNumOperands;
17690 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17691 .addReg(MI->getOperand(ValOps).getReg());
17692 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17693 .addReg(MI->getOperand(ValOps+1).getReg());
17695 // The instruction doesn't actually take any operands though.
17696 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17698 MI->eraseFromParent(); // The pseudo is gone now.
17702 MachineBasicBlock *
17703 X86TargetLowering::EmitVAARG64WithCustomInserter(
17705 MachineBasicBlock *MBB) const {
17706 // Emit va_arg instruction on X86-64.
17708 // Operands to this pseudo-instruction:
17709 // 0 ) Output : destination address (reg)
17710 // 1-5) Input : va_list address (addr, i64mem)
17711 // 6 ) ArgSize : Size (in bytes) of vararg type
17712 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17713 // 8 ) Align : Alignment of type
17714 // 9 ) EFLAGS (implicit-def)
17716 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17717 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17719 unsigned DestReg = MI->getOperand(0).getReg();
17720 MachineOperand &Base = MI->getOperand(1);
17721 MachineOperand &Scale = MI->getOperand(2);
17722 MachineOperand &Index = MI->getOperand(3);
17723 MachineOperand &Disp = MI->getOperand(4);
17724 MachineOperand &Segment = MI->getOperand(5);
17725 unsigned ArgSize = MI->getOperand(6).getImm();
17726 unsigned ArgMode = MI->getOperand(7).getImm();
17727 unsigned Align = MI->getOperand(8).getImm();
17729 // Memory Reference
17730 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17731 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17732 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17734 // Machine Information
17735 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17736 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17737 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17738 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17739 DebugLoc DL = MI->getDebugLoc();
17741 // struct va_list {
17744 // i64 overflow_area (address)
17745 // i64 reg_save_area (address)
17747 // sizeof(va_list) = 24
17748 // alignment(va_list) = 8
17750 unsigned TotalNumIntRegs = 6;
17751 unsigned TotalNumXMMRegs = 8;
17752 bool UseGPOffset = (ArgMode == 1);
17753 bool UseFPOffset = (ArgMode == 2);
17754 unsigned MaxOffset = TotalNumIntRegs * 8 +
17755 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17757 /* Align ArgSize to a multiple of 8 */
17758 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17759 bool NeedsAlign = (Align > 8);
17761 MachineBasicBlock *thisMBB = MBB;
17762 MachineBasicBlock *overflowMBB;
17763 MachineBasicBlock *offsetMBB;
17764 MachineBasicBlock *endMBB;
17766 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17767 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17768 unsigned OffsetReg = 0;
17770 if (!UseGPOffset && !UseFPOffset) {
17771 // If we only pull from the overflow region, we don't create a branch.
17772 // We don't need to alter control flow.
17773 OffsetDestReg = 0; // unused
17774 OverflowDestReg = DestReg;
17776 offsetMBB = nullptr;
17777 overflowMBB = thisMBB;
17780 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17781 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17782 // If not, pull from overflow_area. (branch to overflowMBB)
17787 // offsetMBB overflowMBB
17792 // Registers for the PHI in endMBB
17793 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17794 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17796 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17797 MachineFunction *MF = MBB->getParent();
17798 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17799 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17800 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17802 MachineFunction::iterator MBBIter = MBB;
17805 // Insert the new basic blocks
17806 MF->insert(MBBIter, offsetMBB);
17807 MF->insert(MBBIter, overflowMBB);
17808 MF->insert(MBBIter, endMBB);
17810 // Transfer the remainder of MBB and its successor edges to endMBB.
17811 endMBB->splice(endMBB->begin(), thisMBB,
17812 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17813 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17815 // Make offsetMBB and overflowMBB successors of thisMBB
17816 thisMBB->addSuccessor(offsetMBB);
17817 thisMBB->addSuccessor(overflowMBB);
17819 // endMBB is a successor of both offsetMBB and overflowMBB
17820 offsetMBB->addSuccessor(endMBB);
17821 overflowMBB->addSuccessor(endMBB);
17823 // Load the offset value into a register
17824 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17825 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17829 .addDisp(Disp, UseFPOffset ? 4 : 0)
17830 .addOperand(Segment)
17831 .setMemRefs(MMOBegin, MMOEnd);
17833 // Check if there is enough room left to pull this argument.
17834 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17836 .addImm(MaxOffset + 8 - ArgSizeA8);
17838 // Branch to "overflowMBB" if offset >= max
17839 // Fall through to "offsetMBB" otherwise
17840 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17841 .addMBB(overflowMBB);
17844 // In offsetMBB, emit code to use the reg_save_area.
17846 assert(OffsetReg != 0);
17848 // Read the reg_save_area address.
17849 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17850 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17855 .addOperand(Segment)
17856 .setMemRefs(MMOBegin, MMOEnd);
17858 // Zero-extend the offset
17859 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17860 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17863 .addImm(X86::sub_32bit);
17865 // Add the offset to the reg_save_area to get the final address.
17866 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17867 .addReg(OffsetReg64)
17868 .addReg(RegSaveReg);
17870 // Compute the offset for the next argument
17871 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17872 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17874 .addImm(UseFPOffset ? 16 : 8);
17876 // Store it back into the va_list.
17877 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17881 .addDisp(Disp, UseFPOffset ? 4 : 0)
17882 .addOperand(Segment)
17883 .addReg(NextOffsetReg)
17884 .setMemRefs(MMOBegin, MMOEnd);
17887 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17892 // Emit code to use overflow area
17895 // Load the overflow_area address into a register.
17896 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17897 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17902 .addOperand(Segment)
17903 .setMemRefs(MMOBegin, MMOEnd);
17905 // If we need to align it, do so. Otherwise, just copy the address
17906 // to OverflowDestReg.
17908 // Align the overflow address
17909 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17910 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17912 // aligned_addr = (addr + (align-1)) & ~(align-1)
17913 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17914 .addReg(OverflowAddrReg)
17917 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17919 .addImm(~(uint64_t)(Align-1));
17921 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17922 .addReg(OverflowAddrReg);
17925 // Compute the next overflow address after this argument.
17926 // (the overflow address should be kept 8-byte aligned)
17927 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17928 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17929 .addReg(OverflowDestReg)
17930 .addImm(ArgSizeA8);
17932 // Store the new overflow address.
17933 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17938 .addOperand(Segment)
17939 .addReg(NextAddrReg)
17940 .setMemRefs(MMOBegin, MMOEnd);
17942 // If we branched, emit the PHI to the front of endMBB.
17944 BuildMI(*endMBB, endMBB->begin(), DL,
17945 TII->get(X86::PHI), DestReg)
17946 .addReg(OffsetDestReg).addMBB(offsetMBB)
17947 .addReg(OverflowDestReg).addMBB(overflowMBB);
17950 // Erase the pseudo instruction
17951 MI->eraseFromParent();
17956 MachineBasicBlock *
17957 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17959 MachineBasicBlock *MBB) const {
17960 // Emit code to save XMM registers to the stack. The ABI says that the
17961 // number of registers to save is given in %al, so it's theoretically
17962 // possible to do an indirect jump trick to avoid saving all of them,
17963 // however this code takes a simpler approach and just executes all
17964 // of the stores if %al is non-zero. It's less code, and it's probably
17965 // easier on the hardware branch predictor, and stores aren't all that
17966 // expensive anyway.
17968 // Create the new basic blocks. One block contains all the XMM stores,
17969 // and one block is the final destination regardless of whether any
17970 // stores were performed.
17971 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17972 MachineFunction *F = MBB->getParent();
17973 MachineFunction::iterator MBBIter = MBB;
17975 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17976 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17977 F->insert(MBBIter, XMMSaveMBB);
17978 F->insert(MBBIter, EndMBB);
17980 // Transfer the remainder of MBB and its successor edges to EndMBB.
17981 EndMBB->splice(EndMBB->begin(), MBB,
17982 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17983 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17985 // The original block will now fall through to the XMM save block.
17986 MBB->addSuccessor(XMMSaveMBB);
17987 // The XMMSaveMBB will fall through to the end block.
17988 XMMSaveMBB->addSuccessor(EndMBB);
17990 // Now add the instructions.
17991 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17992 DebugLoc DL = MI->getDebugLoc();
17994 unsigned CountReg = MI->getOperand(0).getReg();
17995 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17996 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17998 if (!Subtarget->isTargetWin64()) {
17999 // If %al is 0, branch around the XMM save block.
18000 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18001 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
18002 MBB->addSuccessor(EndMBB);
18005 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18006 // that was just emitted, but clearly shouldn't be "saved".
18007 assert((MI->getNumOperands() <= 3 ||
18008 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18009 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18010 && "Expected last argument to be EFLAGS");
18011 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18012 // In the XMM save block, save all the XMM argument registers.
18013 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18014 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18015 MachineMemOperand *MMO =
18016 F->getMachineMemOperand(
18017 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18018 MachineMemOperand::MOStore,
18019 /*Size=*/16, /*Align=*/16);
18020 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18021 .addFrameIndex(RegSaveFrameIndex)
18022 .addImm(/*Scale=*/1)
18023 .addReg(/*IndexReg=*/0)
18024 .addImm(/*Disp=*/Offset)
18025 .addReg(/*Segment=*/0)
18026 .addReg(MI->getOperand(i).getReg())
18027 .addMemOperand(MMO);
18030 MI->eraseFromParent(); // The pseudo instruction is gone now.
18035 // The EFLAGS operand of SelectItr might be missing a kill marker
18036 // because there were multiple uses of EFLAGS, and ISel didn't know
18037 // which to mark. Figure out whether SelectItr should have had a
18038 // kill marker, and set it if it should. Returns the correct kill
18040 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18041 MachineBasicBlock* BB,
18042 const TargetRegisterInfo* TRI) {
18043 // Scan forward through BB for a use/def of EFLAGS.
18044 MachineBasicBlock::iterator miI(std::next(SelectItr));
18045 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18046 const MachineInstr& mi = *miI;
18047 if (mi.readsRegister(X86::EFLAGS))
18049 if (mi.definesRegister(X86::EFLAGS))
18050 break; // Should have kill-flag - update below.
18053 // If we hit the end of the block, check whether EFLAGS is live into a
18055 if (miI == BB->end()) {
18056 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18057 sEnd = BB->succ_end();
18058 sItr != sEnd; ++sItr) {
18059 MachineBasicBlock* succ = *sItr;
18060 if (succ->isLiveIn(X86::EFLAGS))
18065 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18066 // out. SelectMI should have a kill flag on EFLAGS.
18067 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18071 MachineBasicBlock *
18072 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18073 MachineBasicBlock *BB) const {
18074 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18075 DebugLoc DL = MI->getDebugLoc();
18077 // To "insert" a SELECT_CC instruction, we actually have to insert the
18078 // diamond control-flow pattern. The incoming instruction knows the
18079 // destination vreg to set, the condition code register to branch on, the
18080 // true/false values to select between, and a branch opcode to use.
18081 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18082 MachineFunction::iterator It = BB;
18088 // cmpTY ccX, r1, r2
18090 // fallthrough --> copy0MBB
18091 MachineBasicBlock *thisMBB = BB;
18092 MachineFunction *F = BB->getParent();
18093 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18094 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18095 F->insert(It, copy0MBB);
18096 F->insert(It, sinkMBB);
18098 // If the EFLAGS register isn't dead in the terminator, then claim that it's
18099 // live into the sink and copy blocks.
18100 const TargetRegisterInfo *TRI =
18101 BB->getParent()->getSubtarget().getRegisterInfo();
18102 if (!MI->killsRegister(X86::EFLAGS) &&
18103 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18104 copy0MBB->addLiveIn(X86::EFLAGS);
18105 sinkMBB->addLiveIn(X86::EFLAGS);
18108 // Transfer the remainder of BB and its successor edges to sinkMBB.
18109 sinkMBB->splice(sinkMBB->begin(), BB,
18110 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18111 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18113 // Add the true and fallthrough blocks as its successors.
18114 BB->addSuccessor(copy0MBB);
18115 BB->addSuccessor(sinkMBB);
18117 // Create the conditional branch instruction.
18119 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18120 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18123 // %FalseValue = ...
18124 // # fallthrough to sinkMBB
18125 copy0MBB->addSuccessor(sinkMBB);
18128 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18130 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18131 TII->get(X86::PHI), MI->getOperand(0).getReg())
18132 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18133 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18135 MI->eraseFromParent(); // The pseudo instruction is gone now.
18139 MachineBasicBlock *
18140 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18141 bool Is64Bit) const {
18142 MachineFunction *MF = BB->getParent();
18143 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18144 DebugLoc DL = MI->getDebugLoc();
18145 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18147 assert(MF->shouldSplitStack());
18149 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18150 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18153 // ... [Till the alloca]
18154 // If stacklet is not large enough, jump to mallocMBB
18157 // Allocate by subtracting from RSP
18158 // Jump to continueMBB
18161 // Allocate by call to runtime
18165 // [rest of original BB]
18168 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18169 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18170 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18172 MachineRegisterInfo &MRI = MF->getRegInfo();
18173 const TargetRegisterClass *AddrRegClass =
18174 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18176 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18177 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18178 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18179 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18180 sizeVReg = MI->getOperand(1).getReg(),
18181 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18183 MachineFunction::iterator MBBIter = BB;
18186 MF->insert(MBBIter, bumpMBB);
18187 MF->insert(MBBIter, mallocMBB);
18188 MF->insert(MBBIter, continueMBB);
18190 continueMBB->splice(continueMBB->begin(), BB,
18191 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18192 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18194 // Add code to the main basic block to check if the stack limit has been hit,
18195 // and if so, jump to mallocMBB otherwise to bumpMBB.
18196 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18197 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18198 .addReg(tmpSPVReg).addReg(sizeVReg);
18199 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18200 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18201 .addReg(SPLimitVReg);
18202 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18204 // bumpMBB simply decreases the stack pointer, since we know the current
18205 // stacklet has enough space.
18206 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18207 .addReg(SPLimitVReg);
18208 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18209 .addReg(SPLimitVReg);
18210 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18212 // Calls into a routine in libgcc to allocate more space from the heap.
18213 const uint32_t *RegMask = MF->getTarget()
18214 .getSubtargetImpl()
18215 ->getRegisterInfo()
18216 ->getCallPreservedMask(CallingConv::C);
18218 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18220 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18221 .addExternalSymbol("__morestack_allocate_stack_space")
18222 .addRegMask(RegMask)
18223 .addReg(X86::RDI, RegState::Implicit)
18224 .addReg(X86::RAX, RegState::ImplicitDefine);
18226 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18228 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18229 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18230 .addExternalSymbol("__morestack_allocate_stack_space")
18231 .addRegMask(RegMask)
18232 .addReg(X86::EAX, RegState::ImplicitDefine);
18236 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18239 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18240 .addReg(Is64Bit ? X86::RAX : X86::EAX);
18241 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18243 // Set up the CFG correctly.
18244 BB->addSuccessor(bumpMBB);
18245 BB->addSuccessor(mallocMBB);
18246 mallocMBB->addSuccessor(continueMBB);
18247 bumpMBB->addSuccessor(continueMBB);
18249 // Take care of the PHI nodes.
18250 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18251 MI->getOperand(0).getReg())
18252 .addReg(mallocPtrVReg).addMBB(mallocMBB)
18253 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18255 // Delete the original pseudo instruction.
18256 MI->eraseFromParent();
18259 return continueMBB;
18262 MachineBasicBlock *
18263 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18264 MachineBasicBlock *BB) const {
18265 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18266 DebugLoc DL = MI->getDebugLoc();
18268 assert(!Subtarget->isTargetMacho());
18270 // The lowering is pretty easy: we're just emitting the call to _alloca. The
18271 // non-trivial part is impdef of ESP.
18273 if (Subtarget->isTargetWin64()) {
18274 if (Subtarget->isTargetCygMing()) {
18275 // ___chkstk(Mingw64):
18276 // Clobbers R10, R11, RAX and EFLAGS.
18278 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18279 .addExternalSymbol("___chkstk")
18280 .addReg(X86::RAX, RegState::Implicit)
18281 .addReg(X86::RSP, RegState::Implicit)
18282 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18283 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18284 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18286 // __chkstk(MSVCRT): does not update stack pointer.
18287 // Clobbers R10, R11 and EFLAGS.
18288 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18289 .addExternalSymbol("__chkstk")
18290 .addReg(X86::RAX, RegState::Implicit)
18291 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18292 // RAX has the offset to be subtracted from RSP.
18293 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18298 const char *StackProbeSymbol =
18299 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18301 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18302 .addExternalSymbol(StackProbeSymbol)
18303 .addReg(X86::EAX, RegState::Implicit)
18304 .addReg(X86::ESP, RegState::Implicit)
18305 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18306 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18307 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18310 MI->eraseFromParent(); // The pseudo instruction is gone now.
18314 MachineBasicBlock *
18315 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18316 MachineBasicBlock *BB) const {
18317 // This is pretty easy. We're taking the value that we received from
18318 // our load from the relocation, sticking it in either RDI (x86-64)
18319 // or EAX and doing an indirect call. The return value will then
18320 // be in the normal return register.
18321 MachineFunction *F = BB->getParent();
18322 const X86InstrInfo *TII =
18323 static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18324 DebugLoc DL = MI->getDebugLoc();
18326 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18327 assert(MI->getOperand(3).isGlobal() && "This should be a global");
18329 // Get a register mask for the lowered call.
18330 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18331 // proper register mask.
18332 const uint32_t *RegMask = F->getTarget()
18333 .getSubtargetImpl()
18334 ->getRegisterInfo()
18335 ->getCallPreservedMask(CallingConv::C);
18336 if (Subtarget->is64Bit()) {
18337 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18338 TII->get(X86::MOV64rm), X86::RDI)
18340 .addImm(0).addReg(0)
18341 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18342 MI->getOperand(3).getTargetFlags())
18344 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18345 addDirectMem(MIB, X86::RDI);
18346 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18347 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18348 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18349 TII->get(X86::MOV32rm), X86::EAX)
18351 .addImm(0).addReg(0)
18352 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18353 MI->getOperand(3).getTargetFlags())
18355 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18356 addDirectMem(MIB, X86::EAX);
18357 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18359 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18360 TII->get(X86::MOV32rm), X86::EAX)
18361 .addReg(TII->getGlobalBaseReg(F))
18362 .addImm(0).addReg(0)
18363 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18364 MI->getOperand(3).getTargetFlags())
18366 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18367 addDirectMem(MIB, X86::EAX);
18368 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18371 MI->eraseFromParent(); // The pseudo instruction is gone now.
18375 MachineBasicBlock *
18376 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18377 MachineBasicBlock *MBB) const {
18378 DebugLoc DL = MI->getDebugLoc();
18379 MachineFunction *MF = MBB->getParent();
18380 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18381 MachineRegisterInfo &MRI = MF->getRegInfo();
18383 const BasicBlock *BB = MBB->getBasicBlock();
18384 MachineFunction::iterator I = MBB;
18387 // Memory Reference
18388 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18389 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18392 unsigned MemOpndSlot = 0;
18394 unsigned CurOp = 0;
18396 DstReg = MI->getOperand(CurOp++).getReg();
18397 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18398 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18399 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18400 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18402 MemOpndSlot = CurOp;
18404 MVT PVT = getPointerTy();
18405 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18406 "Invalid Pointer Size!");
18408 // For v = setjmp(buf), we generate
18411 // buf[LabelOffset] = restoreMBB
18412 // SjLjSetup restoreMBB
18418 // v = phi(main, restore)
18423 MachineBasicBlock *thisMBB = MBB;
18424 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18425 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18426 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18427 MF->insert(I, mainMBB);
18428 MF->insert(I, sinkMBB);
18429 MF->push_back(restoreMBB);
18431 MachineInstrBuilder MIB;
18433 // Transfer the remainder of BB and its successor edges to sinkMBB.
18434 sinkMBB->splice(sinkMBB->begin(), MBB,
18435 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18436 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18439 unsigned PtrStoreOpc = 0;
18440 unsigned LabelReg = 0;
18441 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18442 Reloc::Model RM = MF->getTarget().getRelocationModel();
18443 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18444 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18446 // Prepare IP either in reg or imm.
18447 if (!UseImmLabel) {
18448 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18449 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18450 LabelReg = MRI.createVirtualRegister(PtrRC);
18451 if (Subtarget->is64Bit()) {
18452 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18456 .addMBB(restoreMBB)
18459 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18460 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18461 .addReg(XII->getGlobalBaseReg(MF))
18464 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18468 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18470 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18471 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18472 if (i == X86::AddrDisp)
18473 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18475 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18478 MIB.addReg(LabelReg);
18480 MIB.addMBB(restoreMBB);
18481 MIB.setMemRefs(MMOBegin, MMOEnd);
18483 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18484 .addMBB(restoreMBB);
18486 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18487 MF->getSubtarget().getRegisterInfo());
18488 MIB.addRegMask(RegInfo->getNoPreservedMask());
18489 thisMBB->addSuccessor(mainMBB);
18490 thisMBB->addSuccessor(restoreMBB);
18494 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18495 mainMBB->addSuccessor(sinkMBB);
18498 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18499 TII->get(X86::PHI), DstReg)
18500 .addReg(mainDstReg).addMBB(mainMBB)
18501 .addReg(restoreDstReg).addMBB(restoreMBB);
18504 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18505 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18506 restoreMBB->addSuccessor(sinkMBB);
18508 MI->eraseFromParent();
18512 MachineBasicBlock *
18513 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18514 MachineBasicBlock *MBB) const {
18515 DebugLoc DL = MI->getDebugLoc();
18516 MachineFunction *MF = MBB->getParent();
18517 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18518 MachineRegisterInfo &MRI = MF->getRegInfo();
18520 // Memory Reference
18521 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18522 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18524 MVT PVT = getPointerTy();
18525 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18526 "Invalid Pointer Size!");
18528 const TargetRegisterClass *RC =
18529 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18530 unsigned Tmp = MRI.createVirtualRegister(RC);
18531 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18532 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18533 MF->getSubtarget().getRegisterInfo());
18534 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18535 unsigned SP = RegInfo->getStackRegister();
18537 MachineInstrBuilder MIB;
18539 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18540 const int64_t SPOffset = 2 * PVT.getStoreSize();
18542 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18543 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18546 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18547 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18548 MIB.addOperand(MI->getOperand(i));
18549 MIB.setMemRefs(MMOBegin, MMOEnd);
18551 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18552 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18553 if (i == X86::AddrDisp)
18554 MIB.addDisp(MI->getOperand(i), LabelOffset);
18556 MIB.addOperand(MI->getOperand(i));
18558 MIB.setMemRefs(MMOBegin, MMOEnd);
18560 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18561 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18562 if (i == X86::AddrDisp)
18563 MIB.addDisp(MI->getOperand(i), SPOffset);
18565 MIB.addOperand(MI->getOperand(i));
18567 MIB.setMemRefs(MMOBegin, MMOEnd);
18569 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18571 MI->eraseFromParent();
18575 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18576 // accumulator loops. Writing back to the accumulator allows the coalescer
18577 // to remove extra copies in the loop.
18578 MachineBasicBlock *
18579 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18580 MachineBasicBlock *MBB) const {
18581 MachineOperand &AddendOp = MI->getOperand(3);
18583 // Bail out early if the addend isn't a register - we can't switch these.
18584 if (!AddendOp.isReg())
18587 MachineFunction &MF = *MBB->getParent();
18588 MachineRegisterInfo &MRI = MF.getRegInfo();
18590 // Check whether the addend is defined by a PHI:
18591 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18592 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18593 if (!AddendDef.isPHI())
18596 // Look for the following pattern:
18598 // %addend = phi [%entry, 0], [%loop, %result]
18600 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18604 // %addend = phi [%entry, 0], [%loop, %result]
18606 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18608 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18609 assert(AddendDef.getOperand(i).isReg());
18610 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18611 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18612 if (&PHISrcInst == MI) {
18613 // Found a matching instruction.
18614 unsigned NewFMAOpc = 0;
18615 switch (MI->getOpcode()) {
18616 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18617 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18618 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18619 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18620 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18621 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18622 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18623 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18624 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18625 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18626 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18627 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18628 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18629 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18630 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18631 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18632 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18633 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18634 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18635 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18636 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18637 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18638 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18639 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18640 default: llvm_unreachable("Unrecognized FMA variant.");
18643 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18644 MachineInstrBuilder MIB =
18645 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18646 .addOperand(MI->getOperand(0))
18647 .addOperand(MI->getOperand(3))
18648 .addOperand(MI->getOperand(2))
18649 .addOperand(MI->getOperand(1));
18650 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18651 MI->eraseFromParent();
18658 MachineBasicBlock *
18659 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18660 MachineBasicBlock *BB) const {
18661 switch (MI->getOpcode()) {
18662 default: llvm_unreachable("Unexpected instr type to insert");
18663 case X86::TAILJMPd64:
18664 case X86::TAILJMPr64:
18665 case X86::TAILJMPm64:
18666 llvm_unreachable("TAILJMP64 would not be touched here.");
18667 case X86::TCRETURNdi64:
18668 case X86::TCRETURNri64:
18669 case X86::TCRETURNmi64:
18671 case X86::WIN_ALLOCA:
18672 return EmitLoweredWinAlloca(MI, BB);
18673 case X86::SEG_ALLOCA_32:
18674 return EmitLoweredSegAlloca(MI, BB, false);
18675 case X86::SEG_ALLOCA_64:
18676 return EmitLoweredSegAlloca(MI, BB, true);
18677 case X86::TLSCall_32:
18678 case X86::TLSCall_64:
18679 return EmitLoweredTLSCall(MI, BB);
18680 case X86::CMOV_GR8:
18681 case X86::CMOV_FR32:
18682 case X86::CMOV_FR64:
18683 case X86::CMOV_V4F32:
18684 case X86::CMOV_V2F64:
18685 case X86::CMOV_V2I64:
18686 case X86::CMOV_V8F32:
18687 case X86::CMOV_V4F64:
18688 case X86::CMOV_V4I64:
18689 case X86::CMOV_V16F32:
18690 case X86::CMOV_V8F64:
18691 case X86::CMOV_V8I64:
18692 case X86::CMOV_GR16:
18693 case X86::CMOV_GR32:
18694 case X86::CMOV_RFP32:
18695 case X86::CMOV_RFP64:
18696 case X86::CMOV_RFP80:
18697 return EmitLoweredSelect(MI, BB);
18699 case X86::FP32_TO_INT16_IN_MEM:
18700 case X86::FP32_TO_INT32_IN_MEM:
18701 case X86::FP32_TO_INT64_IN_MEM:
18702 case X86::FP64_TO_INT16_IN_MEM:
18703 case X86::FP64_TO_INT32_IN_MEM:
18704 case X86::FP64_TO_INT64_IN_MEM:
18705 case X86::FP80_TO_INT16_IN_MEM:
18706 case X86::FP80_TO_INT32_IN_MEM:
18707 case X86::FP80_TO_INT64_IN_MEM: {
18708 MachineFunction *F = BB->getParent();
18709 const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
18710 DebugLoc DL = MI->getDebugLoc();
18712 // Change the floating point control register to use "round towards zero"
18713 // mode when truncating to an integer value.
18714 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18715 addFrameReference(BuildMI(*BB, MI, DL,
18716 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18718 // Load the old value of the high byte of the control word...
18720 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18721 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18724 // Set the high part to be round to zero...
18725 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18728 // Reload the modified control word now...
18729 addFrameReference(BuildMI(*BB, MI, DL,
18730 TII->get(X86::FLDCW16m)), CWFrameIdx);
18732 // Restore the memory image of control word to original value
18733 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18736 // Get the X86 opcode to use.
18738 switch (MI->getOpcode()) {
18739 default: llvm_unreachable("illegal opcode!");
18740 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18741 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18742 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18743 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18744 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18745 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18746 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18747 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18748 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18752 MachineOperand &Op = MI->getOperand(0);
18754 AM.BaseType = X86AddressMode::RegBase;
18755 AM.Base.Reg = Op.getReg();
18757 AM.BaseType = X86AddressMode::FrameIndexBase;
18758 AM.Base.FrameIndex = Op.getIndex();
18760 Op = MI->getOperand(1);
18762 AM.Scale = Op.getImm();
18763 Op = MI->getOperand(2);
18765 AM.IndexReg = Op.getImm();
18766 Op = MI->getOperand(3);
18767 if (Op.isGlobal()) {
18768 AM.GV = Op.getGlobal();
18770 AM.Disp = Op.getImm();
18772 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18773 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18775 // Reload the original control word now.
18776 addFrameReference(BuildMI(*BB, MI, DL,
18777 TII->get(X86::FLDCW16m)), CWFrameIdx);
18779 MI->eraseFromParent(); // The pseudo instruction is gone now.
18782 // String/text processing lowering.
18783 case X86::PCMPISTRM128REG:
18784 case X86::VPCMPISTRM128REG:
18785 case X86::PCMPISTRM128MEM:
18786 case X86::VPCMPISTRM128MEM:
18787 case X86::PCMPESTRM128REG:
18788 case X86::VPCMPESTRM128REG:
18789 case X86::PCMPESTRM128MEM:
18790 case X86::VPCMPESTRM128MEM:
18791 assert(Subtarget->hasSSE42() &&
18792 "Target must have SSE4.2 or AVX features enabled");
18793 return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18795 // String/text processing lowering.
18796 case X86::PCMPISTRIREG:
18797 case X86::VPCMPISTRIREG:
18798 case X86::PCMPISTRIMEM:
18799 case X86::VPCMPISTRIMEM:
18800 case X86::PCMPESTRIREG:
18801 case X86::VPCMPESTRIREG:
18802 case X86::PCMPESTRIMEM:
18803 case X86::VPCMPESTRIMEM:
18804 assert(Subtarget->hasSSE42() &&
18805 "Target must have SSE4.2 or AVX features enabled");
18806 return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18808 // Thread synchronization.
18810 return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
18815 return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18817 case X86::VASTART_SAVE_XMM_REGS:
18818 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18820 case X86::VAARG_64:
18821 return EmitVAARG64WithCustomInserter(MI, BB);
18823 case X86::EH_SjLj_SetJmp32:
18824 case X86::EH_SjLj_SetJmp64:
18825 return emitEHSjLjSetJmp(MI, BB);
18827 case X86::EH_SjLj_LongJmp32:
18828 case X86::EH_SjLj_LongJmp64:
18829 return emitEHSjLjLongJmp(MI, BB);
18831 case TargetOpcode::STACKMAP:
18832 case TargetOpcode::PATCHPOINT:
18833 return emitPatchPoint(MI, BB);
18835 case X86::VFMADDPDr213r:
18836 case X86::VFMADDPSr213r:
18837 case X86::VFMADDSDr213r:
18838 case X86::VFMADDSSr213r:
18839 case X86::VFMSUBPDr213r:
18840 case X86::VFMSUBPSr213r:
18841 case X86::VFMSUBSDr213r:
18842 case X86::VFMSUBSSr213r:
18843 case X86::VFNMADDPDr213r:
18844 case X86::VFNMADDPSr213r:
18845 case X86::VFNMADDSDr213r:
18846 case X86::VFNMADDSSr213r:
18847 case X86::VFNMSUBPDr213r:
18848 case X86::VFNMSUBPSr213r:
18849 case X86::VFNMSUBSDr213r:
18850 case X86::VFNMSUBSSr213r:
18851 case X86::VFMADDPDr213rY:
18852 case X86::VFMADDPSr213rY:
18853 case X86::VFMSUBPDr213rY:
18854 case X86::VFMSUBPSr213rY:
18855 case X86::VFNMADDPDr213rY:
18856 case X86::VFNMADDPSr213rY:
18857 case X86::VFNMSUBPDr213rY:
18858 case X86::VFNMSUBPSr213rY:
18859 return emitFMA3Instr(MI, BB);
18863 //===----------------------------------------------------------------------===//
18864 // X86 Optimization Hooks
18865 //===----------------------------------------------------------------------===//
18867 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18870 const SelectionDAG &DAG,
18871 unsigned Depth) const {
18872 unsigned BitWidth = KnownZero.getBitWidth();
18873 unsigned Opc = Op.getOpcode();
18874 assert((Opc >= ISD::BUILTIN_OP_END ||
18875 Opc == ISD::INTRINSIC_WO_CHAIN ||
18876 Opc == ISD::INTRINSIC_W_CHAIN ||
18877 Opc == ISD::INTRINSIC_VOID) &&
18878 "Should use MaskedValueIsZero if you don't know whether Op"
18879 " is a target node!");
18881 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
18895 // These nodes' second result is a boolean.
18896 if (Op.getResNo() == 0)
18899 case X86ISD::SETCC:
18900 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18902 case ISD::INTRINSIC_WO_CHAIN: {
18903 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18904 unsigned NumLoBits = 0;
18907 case Intrinsic::x86_sse_movmsk_ps:
18908 case Intrinsic::x86_avx_movmsk_ps_256:
18909 case Intrinsic::x86_sse2_movmsk_pd:
18910 case Intrinsic::x86_avx_movmsk_pd_256:
18911 case Intrinsic::x86_mmx_pmovmskb:
18912 case Intrinsic::x86_sse2_pmovmskb_128:
18913 case Intrinsic::x86_avx2_pmovmskb: {
18914 // High bits of movmskp{s|d}, pmovmskb are known zero.
18916 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18917 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
18918 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
18919 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
18920 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
18921 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
18922 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
18923 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
18925 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18934 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18936 const SelectionDAG &,
18937 unsigned Depth) const {
18938 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18939 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18940 return Op.getValueType().getScalarType().getSizeInBits();
18946 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18947 /// node is a GlobalAddress + offset.
18948 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18949 const GlobalValue* &GA,
18950 int64_t &Offset) const {
18951 if (N->getOpcode() == X86ISD::Wrapper) {
18952 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18953 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18954 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18958 return TargetLowering::isGAPlusOffset(N, GA, Offset);
18961 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18962 /// same as extracting the high 128-bit part of 256-bit vector and then
18963 /// inserting the result into the low part of a new 256-bit vector
18964 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18965 EVT VT = SVOp->getValueType(0);
18966 unsigned NumElems = VT.getVectorNumElements();
18968 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18969 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18970 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18971 SVOp->getMaskElt(j) >= 0)
18977 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18978 /// same as extracting the low 128-bit part of 256-bit vector and then
18979 /// inserting the result into the high part of a new 256-bit vector
18980 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18981 EVT VT = SVOp->getValueType(0);
18982 unsigned NumElems = VT.getVectorNumElements();
18984 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18985 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18986 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18987 SVOp->getMaskElt(j) >= 0)
18993 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18994 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18995 TargetLowering::DAGCombinerInfo &DCI,
18996 const X86Subtarget* Subtarget) {
18998 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18999 SDValue V1 = SVOp->getOperand(0);
19000 SDValue V2 = SVOp->getOperand(1);
19001 EVT VT = SVOp->getValueType(0);
19002 unsigned NumElems = VT.getVectorNumElements();
19004 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19005 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19009 // V UNDEF BUILD_VECTOR UNDEF
19011 // CONCAT_VECTOR CONCAT_VECTOR
19014 // RESULT: V + zero extended
19016 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19017 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19018 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19021 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19024 // To match the shuffle mask, the first half of the mask should
19025 // be exactly the first vector, and all the rest a splat with the
19026 // first element of the second one.
19027 for (unsigned i = 0; i != NumElems/2; ++i)
19028 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19029 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19032 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19033 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19034 if (Ld->hasNUsesOfValue(1, 0)) {
19035 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19036 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19038 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19040 Ld->getPointerInfo(),
19041 Ld->getAlignment(),
19042 false/*isVolatile*/, true/*ReadMem*/,
19043 false/*WriteMem*/);
19045 // Make sure the newly-created LOAD is in the same position as Ld in
19046 // terms of dependency. We create a TokenFactor for Ld and ResNode,
19047 // and update uses of Ld's output chain to use the TokenFactor.
19048 if (Ld->hasAnyUseOfValue(1)) {
19049 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19050 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19051 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19052 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19053 SDValue(ResNode.getNode(), 1));
19056 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19060 // Emit a zeroed vector and insert the desired subvector on its
19062 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19063 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19064 return DCI.CombineTo(N, InsV);
19067 //===--------------------------------------------------------------------===//
19068 // Combine some shuffles into subvector extracts and inserts:
19071 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19072 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19073 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19074 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19075 return DCI.CombineTo(N, InsV);
19078 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19079 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19080 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19081 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19082 return DCI.CombineTo(N, InsV);
19088 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19091 /// This is the leaf of the recursive combinine below. When we have found some
19092 /// chain of single-use x86 shuffle instructions and accumulated the combined
19093 /// shuffle mask represented by them, this will try to pattern match that mask
19094 /// into either a single instruction if there is a special purpose instruction
19095 /// for this operation, or into a PSHUFB instruction which is a fully general
19096 /// instruction but should only be used to replace chains over a certain depth.
19097 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19098 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19099 TargetLowering::DAGCombinerInfo &DCI,
19100 const X86Subtarget *Subtarget) {
19101 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19103 // Find the operand that enters the chain. Note that multiple uses are OK
19104 // here, we're not going to remove the operand we find.
19105 SDValue Input = Op.getOperand(0);
19106 while (Input.getOpcode() == ISD::BITCAST)
19107 Input = Input.getOperand(0);
19109 MVT VT = Input.getSimpleValueType();
19110 MVT RootVT = Root.getSimpleValueType();
19113 // Just remove no-op shuffle masks.
19114 if (Mask.size() == 1) {
19115 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19120 // Use the float domain if the operand type is a floating point type.
19121 bool FloatDomain = VT.isFloatingPoint();
19123 // If we don't have access to VEX encodings, the generic PSHUF instructions
19124 // are preferable to some of the specialized forms despite requiring one more
19125 // byte to encode because they can implicitly copy.
19127 // IF we *do* have VEX encodings, than we can use shorter, more specific
19128 // shuffle instructions freely as they can copy due to the extra register
19130 if (Subtarget->hasAVX()) {
19131 // We have both floating point and integer variants of shuffles that dup
19132 // either the low or high half of the vector.
19133 if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19134 bool Lo = Mask.equals(0, 0);
19135 unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
19136 : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19137 if (Depth == 1 && Root->getOpcode() == Shuffle)
19138 return false; // Nothing to do!
19139 MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19140 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19141 DCI.AddToWorklist(Op.getNode());
19142 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19143 DCI.AddToWorklist(Op.getNode());
19144 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19149 // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19151 // For the integer domain we have specialized instructions for duplicating
19152 // any element size from the low or high half.
19153 if (!FloatDomain &&
19154 (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19155 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19156 Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19157 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19158 Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19160 bool Lo = Mask[0] == 0;
19161 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19162 if (Depth == 1 && Root->getOpcode() == Shuffle)
19163 return false; // Nothing to do!
19165 switch (Mask.size()) {
19166 case 4: ShuffleVT = MVT::v4i32; break;
19167 case 8: ShuffleVT = MVT::v8i16; break;
19168 case 16: ShuffleVT = MVT::v16i8; break;
19170 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19171 DCI.AddToWorklist(Op.getNode());
19172 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19173 DCI.AddToWorklist(Op.getNode());
19174 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19180 // Don't try to re-form single instruction chains under any circumstances now
19181 // that we've done encoding canonicalization for them.
19185 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19186 // can replace them with a single PSHUFB instruction profitably. Intel's
19187 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19188 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19189 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19190 SmallVector<SDValue, 16> PSHUFBMask;
19191 assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19192 int Ratio = 16 / Mask.size();
19193 for (unsigned i = 0; i < 16; ++i) {
19194 int M = Mask[i / Ratio] != SM_SentinelZero
19195 ? Ratio * Mask[i / Ratio] + i % Ratio
19197 PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19199 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19200 DCI.AddToWorklist(Op.getNode());
19201 SDValue PSHUFBMaskOp =
19202 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19203 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19204 Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19205 DCI.AddToWorklist(Op.getNode());
19206 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19211 // Failed to find any combines.
19215 /// \brief Fully generic combining of x86 shuffle instructions.
19217 /// This should be the last combine run over the x86 shuffle instructions. Once
19218 /// they have been fully optimized, this will recursively consider all chains
19219 /// of single-use shuffle instructions, build a generic model of the cumulative
19220 /// shuffle operation, and check for simpler instructions which implement this
19221 /// operation. We use this primarily for two purposes:
19223 /// 1) Collapse generic shuffles to specialized single instructions when
19224 /// equivalent. In most cases, this is just an encoding size win, but
19225 /// sometimes we will collapse multiple generic shuffles into a single
19226 /// special-purpose shuffle.
19227 /// 2) Look for sequences of shuffle instructions with 3 or more total
19228 /// instructions, and replace them with the slightly more expensive SSSE3
19229 /// PSHUFB instruction if available. We do this as the last combining step
19230 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
19231 /// a suitable short sequence of other instructions. The PHUFB will either
19232 /// use a register or have to read from memory and so is slightly (but only
19233 /// slightly) more expensive than the other shuffle instructions.
19235 /// Because this is inherently a quadratic operation (for each shuffle in
19236 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19237 /// This should never be an issue in practice as the shuffle lowering doesn't
19238 /// produce sequences of more than 8 instructions.
19240 /// FIXME: We will currently miss some cases where the redundant shuffling
19241 /// would simplify under the threshold for PSHUFB formation because of
19242 /// combine-ordering. To fix this, we should do the redundant instruction
19243 /// combining in this recursive walk.
19244 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19245 ArrayRef<int> RootMask,
19246 int Depth, bool HasPSHUFB,
19248 TargetLowering::DAGCombinerInfo &DCI,
19249 const X86Subtarget *Subtarget) {
19250 // Bound the depth of our recursive combine because this is ultimately
19251 // quadratic in nature.
19255 // Directly rip through bitcasts to find the underlying operand.
19256 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19257 Op = Op.getOperand(0);
19259 MVT VT = Op.getSimpleValueType();
19260 if (!VT.isVector())
19261 return false; // Bail if we hit a non-vector.
19262 // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19263 // version should be added.
19264 if (VT.getSizeInBits() != 128)
19267 assert(Root.getSimpleValueType().isVector() &&
19268 "Shuffles operate on vector types!");
19269 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19270 "Can only combine shuffles of the same vector register size.");
19272 if (!isTargetShuffle(Op.getOpcode()))
19274 SmallVector<int, 16> OpMask;
19276 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19277 // We only can combine unary shuffles which we can decode the mask for.
19278 if (!HaveMask || !IsUnary)
19281 assert(VT.getVectorNumElements() == OpMask.size() &&
19282 "Different mask size from vector size!");
19283 assert(((RootMask.size() > OpMask.size() &&
19284 RootMask.size() % OpMask.size() == 0) ||
19285 (OpMask.size() > RootMask.size() &&
19286 OpMask.size() % RootMask.size() == 0) ||
19287 OpMask.size() == RootMask.size()) &&
19288 "The smaller number of elements must divide the larger.");
19289 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19290 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19291 assert(((RootRatio == 1 && OpRatio == 1) ||
19292 (RootRatio == 1) != (OpRatio == 1)) &&
19293 "Must not have a ratio for both incoming and op masks!");
19295 SmallVector<int, 16> Mask;
19296 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19298 // Merge this shuffle operation's mask into our accumulated mask. Note that
19299 // this shuffle's mask will be the first applied to the input, followed by the
19300 // root mask to get us all the way to the root value arrangement. The reason
19301 // for this order is that we are recursing up the operation chain.
19302 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19303 int RootIdx = i / RootRatio;
19304 if (RootMask[RootIdx] == SM_SentinelZero) {
19305 // This is a zero-ed lane, we're done.
19306 Mask.push_back(SM_SentinelZero);
19310 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19311 int OpIdx = RootMaskedIdx / OpRatio;
19312 if (OpMask[OpIdx] == SM_SentinelZero) {
19313 // The incoming lanes are zero, it doesn't matter which ones we are using.
19314 Mask.push_back(SM_SentinelZero);
19318 // Ok, we have non-zero lanes, map them through.
19319 Mask.push_back(OpMask[OpIdx] * OpRatio +
19320 RootMaskedIdx % OpRatio);
19323 // See if we can recurse into the operand to combine more things.
19324 switch (Op.getOpcode()) {
19325 case X86ISD::PSHUFB:
19327 case X86ISD::PSHUFD:
19328 case X86ISD::PSHUFHW:
19329 case X86ISD::PSHUFLW:
19330 if (Op.getOperand(0).hasOneUse() &&
19331 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19332 HasPSHUFB, DAG, DCI, Subtarget))
19336 case X86ISD::UNPCKL:
19337 case X86ISD::UNPCKH:
19338 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19339 // We can't check for single use, we have to check that this shuffle is the only user.
19340 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19341 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19342 HasPSHUFB, DAG, DCI, Subtarget))
19347 // Minor canonicalization of the accumulated shuffle mask to make it easier
19348 // to match below. All this does is detect masks with squential pairs of
19349 // elements, and shrink them to the half-width mask. It does this in a loop
19350 // so it will reduce the size of the mask to the minimal width mask which
19351 // performs an equivalent shuffle.
19352 while (Mask.size() > 1 && canWidenShuffleElements(Mask)) {
19353 for (int i = 0, e = Mask.size() / 2; i < e; ++i)
19354 Mask[i] = Mask[2 * i] / 2;
19355 Mask.resize(Mask.size() / 2);
19358 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19362 /// \brief Get the PSHUF-style mask from PSHUF node.
19364 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19365 /// PSHUF-style masks that can be reused with such instructions.
19366 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19367 SmallVector<int, 4> Mask;
19369 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19373 switch (N.getOpcode()) {
19374 case X86ISD::PSHUFD:
19376 case X86ISD::PSHUFLW:
19379 case X86ISD::PSHUFHW:
19380 Mask.erase(Mask.begin(), Mask.begin() + 4);
19381 for (int &M : Mask)
19385 llvm_unreachable("No valid shuffle instruction found!");
19389 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19391 /// We walk up the chain and look for a combinable shuffle, skipping over
19392 /// shuffles that we could hoist this shuffle's transformation past without
19393 /// altering anything.
19395 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19397 TargetLowering::DAGCombinerInfo &DCI) {
19398 assert(N.getOpcode() == X86ISD::PSHUFD &&
19399 "Called with something other than an x86 128-bit half shuffle!");
19402 // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19403 // of the shuffles in the chain so that we can form a fresh chain to replace
19405 SmallVector<SDValue, 8> Chain;
19406 SDValue V = N.getOperand(0);
19407 for (; V.hasOneUse(); V = V.getOperand(0)) {
19408 switch (V.getOpcode()) {
19410 return SDValue(); // Nothing combined!
19413 // Skip bitcasts as we always know the type for the target specific
19417 case X86ISD::PSHUFD:
19418 // Found another dword shuffle.
19421 case X86ISD::PSHUFLW:
19422 // Check that the low words (being shuffled) are the identity in the
19423 // dword shuffle, and the high words are self-contained.
19424 if (Mask[0] != 0 || Mask[1] != 1 ||
19425 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19428 Chain.push_back(V);
19431 case X86ISD::PSHUFHW:
19432 // Check that the high words (being shuffled) are the identity in the
19433 // dword shuffle, and the low words are self-contained.
19434 if (Mask[2] != 2 || Mask[3] != 3 ||
19435 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19438 Chain.push_back(V);
19441 case X86ISD::UNPCKL:
19442 case X86ISD::UNPCKH:
19443 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19444 // shuffle into a preceding word shuffle.
19445 if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19448 // Search for a half-shuffle which we can combine with.
19449 unsigned CombineOp =
19450 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19451 if (V.getOperand(0) != V.getOperand(1) ||
19452 !V->isOnlyUserOf(V.getOperand(0).getNode()))
19454 Chain.push_back(V);
19455 V = V.getOperand(0);
19457 switch (V.getOpcode()) {
19459 return SDValue(); // Nothing to combine.
19461 case X86ISD::PSHUFLW:
19462 case X86ISD::PSHUFHW:
19463 if (V.getOpcode() == CombineOp)
19466 Chain.push_back(V);
19470 V = V.getOperand(0);
19474 } while (V.hasOneUse());
19477 // Break out of the loop if we break out of the switch.
19481 if (!V.hasOneUse())
19482 // We fell out of the loop without finding a viable combining instruction.
19485 // Merge this node's mask and our incoming mask.
19486 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19487 for (int &M : Mask)
19489 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19490 getV4X86ShuffleImm8ForMask(Mask, DAG));
19492 // Rebuild the chain around this new shuffle.
19493 while (!Chain.empty()) {
19494 SDValue W = Chain.pop_back_val();
19496 if (V.getValueType() != W.getOperand(0).getValueType())
19497 V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19499 switch (W.getOpcode()) {
19501 llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19503 case X86ISD::UNPCKL:
19504 case X86ISD::UNPCKH:
19505 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19508 case X86ISD::PSHUFD:
19509 case X86ISD::PSHUFLW:
19510 case X86ISD::PSHUFHW:
19511 V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19515 if (V.getValueType() != N.getValueType())
19516 V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19518 // Return the new chain to replace N.
19522 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19524 /// We walk up the chain, skipping shuffles of the other half and looking
19525 /// through shuffles which switch halves trying to find a shuffle of the same
19526 /// pair of dwords.
19527 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19529 TargetLowering::DAGCombinerInfo &DCI) {
19531 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19532 "Called with something other than an x86 128-bit half shuffle!");
19534 unsigned CombineOpcode = N.getOpcode();
19536 // Walk up a single-use chain looking for a combinable shuffle.
19537 SDValue V = N.getOperand(0);
19538 for (; V.hasOneUse(); V = V.getOperand(0)) {
19539 switch (V.getOpcode()) {
19541 return false; // Nothing combined!
19544 // Skip bitcasts as we always know the type for the target specific
19548 case X86ISD::PSHUFLW:
19549 case X86ISD::PSHUFHW:
19550 if (V.getOpcode() == CombineOpcode)
19553 // Other-half shuffles are no-ops.
19556 // Break out of the loop if we break out of the switch.
19560 if (!V.hasOneUse())
19561 // We fell out of the loop without finding a viable combining instruction.
19564 // Combine away the bottom node as its shuffle will be accumulated into
19565 // a preceding shuffle.
19566 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19568 // Record the old value.
19571 // Merge this node's mask and our incoming mask (adjusted to account for all
19572 // the pshufd instructions encountered).
19573 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19574 for (int &M : Mask)
19576 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19577 getV4X86ShuffleImm8ForMask(Mask, DAG));
19579 // Check that the shuffles didn't cancel each other out. If not, we need to
19580 // combine to the new one.
19582 // Replace the combinable shuffle with the combined one, updating all users
19583 // so that we re-evaluate the chain here.
19584 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19589 /// \brief Try to combine x86 target specific shuffles.
19590 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19591 TargetLowering::DAGCombinerInfo &DCI,
19592 const X86Subtarget *Subtarget) {
19594 MVT VT = N.getSimpleValueType();
19595 SmallVector<int, 4> Mask;
19597 switch (N.getOpcode()) {
19598 case X86ISD::PSHUFD:
19599 case X86ISD::PSHUFLW:
19600 case X86ISD::PSHUFHW:
19601 Mask = getPSHUFShuffleMask(N);
19602 assert(Mask.size() == 4);
19608 // Nuke no-op shuffles that show up after combining.
19609 if (isNoopShuffleMask(Mask))
19610 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19612 // Look for simplifications involving one or two shuffle instructions.
19613 SDValue V = N.getOperand(0);
19614 switch (N.getOpcode()) {
19617 case X86ISD::PSHUFLW:
19618 case X86ISD::PSHUFHW:
19619 assert(VT == MVT::v8i16);
19622 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19623 return SDValue(); // We combined away this shuffle, so we're done.
19625 // See if this reduces to a PSHUFD which is no more expensive and can
19626 // combine with more operations.
19627 if (canWidenShuffleElements(Mask)) {
19628 int DMask[] = {-1, -1, -1, -1};
19629 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19630 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19631 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19632 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19633 DCI.AddToWorklist(V.getNode());
19634 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19635 getV4X86ShuffleImm8ForMask(DMask, DAG));
19636 DCI.AddToWorklist(V.getNode());
19637 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19640 // Look for shuffle patterns which can be implemented as a single unpack.
19641 // FIXME: This doesn't handle the location of the PSHUFD generically, and
19642 // only works when we have a PSHUFD followed by two half-shuffles.
19643 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19644 (V.getOpcode() == X86ISD::PSHUFLW ||
19645 V.getOpcode() == X86ISD::PSHUFHW) &&
19646 V.getOpcode() != N.getOpcode() &&
19648 SDValue D = V.getOperand(0);
19649 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19650 D = D.getOperand(0);
19651 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19652 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19653 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19654 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19655 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19657 for (int i = 0; i < 4; ++i) {
19658 WordMask[i + NOffset] = Mask[i] + NOffset;
19659 WordMask[i + VOffset] = VMask[i] + VOffset;
19661 // Map the word mask through the DWord mask.
19663 for (int i = 0; i < 8; ++i)
19664 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19665 const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19666 const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19667 if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19668 std::begin(UnpackLoMask)) ||
19669 std::equal(std::begin(MappedMask), std::end(MappedMask),
19670 std::begin(UnpackHiMask))) {
19671 // We can replace all three shuffles with an unpack.
19672 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19673 DCI.AddToWorklist(V.getNode());
19674 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19676 DL, MVT::v8i16, V, V);
19683 case X86ISD::PSHUFD:
19684 if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19693 /// PerformShuffleCombine - Performs several different shuffle combines.
19694 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19695 TargetLowering::DAGCombinerInfo &DCI,
19696 const X86Subtarget *Subtarget) {
19698 SDValue N0 = N->getOperand(0);
19699 SDValue N1 = N->getOperand(1);
19700 EVT VT = N->getValueType(0);
19702 // Don't create instructions with illegal types after legalize types has run.
19703 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19704 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19707 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19708 if (Subtarget->hasFp256() && VT.is256BitVector() &&
19709 N->getOpcode() == ISD::VECTOR_SHUFFLE)
19710 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19712 // During Type Legalization, when promoting illegal vector types,
19713 // the backend might introduce new shuffle dag nodes and bitcasts.
19715 // This code performs the following transformation:
19716 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19717 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19719 // We do this only if both the bitcast and the BINOP dag nodes have
19720 // one use. Also, perform this transformation only if the new binary
19721 // operation is legal. This is to avoid introducing dag nodes that
19722 // potentially need to be further expanded (or custom lowered) into a
19723 // less optimal sequence of dag nodes.
19724 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19725 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19726 N0.getOpcode() == ISD::BITCAST) {
19727 SDValue BC0 = N0.getOperand(0);
19728 EVT SVT = BC0.getValueType();
19729 unsigned Opcode = BC0.getOpcode();
19730 unsigned NumElts = VT.getVectorNumElements();
19732 if (BC0.hasOneUse() && SVT.isVector() &&
19733 SVT.getVectorNumElements() * 2 == NumElts &&
19734 TLI.isOperationLegal(Opcode, VT)) {
19735 bool CanFold = false;
19747 unsigned SVTNumElts = SVT.getVectorNumElements();
19748 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19749 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19750 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19751 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19752 CanFold = SVOp->getMaskElt(i) < 0;
19755 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19756 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19757 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19758 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19763 // Only handle 128 wide vector from here on.
19764 if (!VT.is128BitVector())
19767 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19768 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19769 // consecutive, non-overlapping, and in the right order.
19770 SmallVector<SDValue, 16> Elts;
19771 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19772 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19774 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19778 if (isTargetShuffle(N->getOpcode())) {
19780 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19781 if (Shuffle.getNode())
19784 // Try recursively combining arbitrary sequences of x86 shuffle
19785 // instructions into higher-order shuffles. We do this after combining
19786 // specific PSHUF instruction sequences into their minimal form so that we
19787 // can evaluate how many specialized shuffle instructions are involved in
19788 // a particular chain.
19789 SmallVector<int, 1> NonceMask; // Just a placeholder.
19790 NonceMask.push_back(0);
19791 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19792 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19794 return SDValue(); // This routine will use CombineTo to replace N.
19800 /// PerformTruncateCombine - Converts truncate operation to
19801 /// a sequence of vector shuffle operations.
19802 /// It is possible when we truncate 256-bit vector to 128-bit vector
19803 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19804 TargetLowering::DAGCombinerInfo &DCI,
19805 const X86Subtarget *Subtarget) {
19809 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19810 /// specific shuffle of a load can be folded into a single element load.
19811 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19812 /// shuffles have been customed lowered so we need to handle those here.
19813 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19814 TargetLowering::DAGCombinerInfo &DCI) {
19815 if (DCI.isBeforeLegalizeOps())
19818 SDValue InVec = N->getOperand(0);
19819 SDValue EltNo = N->getOperand(1);
19821 if (!isa<ConstantSDNode>(EltNo))
19824 EVT VT = InVec.getValueType();
19826 if (InVec.getOpcode() == ISD::BITCAST) {
19827 // Don't duplicate a load with other uses.
19828 if (!InVec.hasOneUse())
19830 EVT BCVT = InVec.getOperand(0).getValueType();
19831 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19833 InVec = InVec.getOperand(0);
19836 if (!isTargetShuffle(InVec.getOpcode()))
19839 // Don't duplicate a load with other uses.
19840 if (!InVec.hasOneUse())
19843 SmallVector<int, 16> ShuffleMask;
19845 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19849 // Select the input vector, guarding against out of range extract vector.
19850 unsigned NumElems = VT.getVectorNumElements();
19851 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19852 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19853 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19854 : InVec.getOperand(1);
19856 // If inputs to shuffle are the same for both ops, then allow 2 uses
19857 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19859 if (LdNode.getOpcode() == ISD::BITCAST) {
19860 // Don't duplicate a load with other uses.
19861 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19864 AllowedUses = 1; // only allow 1 load use if we have a bitcast
19865 LdNode = LdNode.getOperand(0);
19868 if (!ISD::isNormalLoad(LdNode.getNode()))
19871 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19873 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19876 EVT EltVT = N->getValueType(0);
19877 // If there's a bitcast before the shuffle, check if the load type and
19878 // alignment is valid.
19879 unsigned Align = LN0->getAlignment();
19880 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19881 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
19882 EltVT.getTypeForEVT(*DAG.getContext()));
19884 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
19887 // All checks match so transform back to vector_shuffle so that DAG combiner
19888 // can finish the job
19891 // Create shuffle node taking into account the case that its a unary shuffle
19892 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19893 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19894 InVec.getOperand(0), Shuffle,
19896 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19897 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19901 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19902 /// generation and convert it from being a bunch of shuffles and extracts
19903 /// to a simple store and scalar loads to extract the elements.
19904 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19905 TargetLowering::DAGCombinerInfo &DCI) {
19906 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19907 if (NewOp.getNode())
19910 SDValue InputVector = N->getOperand(0);
19912 // Detect whether we are trying to convert from mmx to i32 and the bitcast
19913 // from mmx to v2i32 has a single usage.
19914 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19915 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19916 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19917 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19918 N->getValueType(0),
19919 InputVector.getNode()->getOperand(0));
19921 // Only operate on vectors of 4 elements, where the alternative shuffling
19922 // gets to be more expensive.
19923 if (InputVector.getValueType() != MVT::v4i32)
19926 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19927 // single use which is a sign-extend or zero-extend, and all elements are
19929 SmallVector<SDNode *, 4> Uses;
19930 unsigned ExtractedElements = 0;
19931 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19932 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19933 if (UI.getUse().getResNo() != InputVector.getResNo())
19936 SDNode *Extract = *UI;
19937 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19940 if (Extract->getValueType(0) != MVT::i32)
19942 if (!Extract->hasOneUse())
19944 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19945 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19947 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19950 // Record which element was extracted.
19951 ExtractedElements |=
19952 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19954 Uses.push_back(Extract);
19957 // If not all the elements were used, this may not be worthwhile.
19958 if (ExtractedElements != 15)
19961 // Ok, we've now decided to do the transformation.
19962 SDLoc dl(InputVector);
19964 // Store the value to a temporary stack slot.
19965 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19966 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19967 MachinePointerInfo(), false, false, 0);
19969 // Replace each use (extract) with a load of the appropriate element.
19970 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19971 UE = Uses.end(); UI != UE; ++UI) {
19972 SDNode *Extract = *UI;
19974 // cOMpute the element's address.
19975 SDValue Idx = Extract->getOperand(1);
19977 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19978 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19979 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19980 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19982 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19983 StackPtr, OffsetVal);
19985 // Load the scalar.
19986 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19987 ScalarAddr, MachinePointerInfo(),
19988 false, false, false, 0);
19990 // Replace the exact with the load.
19991 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19994 // The replacement was made in place; don't return anything.
19998 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19999 static std::pair<unsigned, bool>
20000 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20001 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20002 if (!VT.isVector())
20003 return std::make_pair(0, false);
20005 bool NeedSplit = false;
20006 switch (VT.getSimpleVT().SimpleTy) {
20007 default: return std::make_pair(0, false);
20011 if (!Subtarget->hasAVX2())
20013 if (!Subtarget->hasAVX())
20014 return std::make_pair(0, false);
20019 if (!Subtarget->hasSSE2())
20020 return std::make_pair(0, false);
20023 // SSE2 has only a small subset of the operations.
20024 bool hasUnsigned = Subtarget->hasSSE41() ||
20025 (Subtarget->hasSSE2() && VT == MVT::v16i8);
20026 bool hasSigned = Subtarget->hasSSE41() ||
20027 (Subtarget->hasSSE2() && VT == MVT::v8i16);
20029 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20032 // Check for x CC y ? x : y.
20033 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20034 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20039 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20042 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20045 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20048 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20050 // Check for x CC y ? y : x -- a min/max with reversed arms.
20051 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20052 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20057 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20060 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20063 Opc = hasSigned ? X86ISD::SMAX : 0; break;
20066 Opc = hasSigned ? X86ISD::SMIN : 0; break;
20070 return std::make_pair(Opc, NeedSplit);
20074 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20075 const X86Subtarget *Subtarget) {
20077 SDValue Cond = N->getOperand(0);
20078 SDValue LHS = N->getOperand(1);
20079 SDValue RHS = N->getOperand(2);
20081 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20082 SDValue CondSrc = Cond->getOperand(0);
20083 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20084 Cond = CondSrc->getOperand(0);
20087 MVT VT = N->getSimpleValueType(0);
20088 MVT EltVT = VT.getVectorElementType();
20089 unsigned NumElems = VT.getVectorNumElements();
20090 // There is no blend with immediate in AVX-512.
20091 if (VT.is512BitVector())
20094 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
20096 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
20099 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20102 // A vselect where all conditions and data are constants can be optimized into
20103 // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20104 if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20105 ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20108 unsigned MaskValue = 0;
20109 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20112 SmallVector<int, 8> ShuffleMask(NumElems, -1);
20113 for (unsigned i = 0; i < NumElems; ++i) {
20114 // Be sure we emit undef where we can.
20115 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20116 ShuffleMask[i] = -1;
20118 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20121 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20124 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20126 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20127 TargetLowering::DAGCombinerInfo &DCI,
20128 const X86Subtarget *Subtarget) {
20130 SDValue Cond = N->getOperand(0);
20131 // Get the LHS/RHS of the select.
20132 SDValue LHS = N->getOperand(1);
20133 SDValue RHS = N->getOperand(2);
20134 EVT VT = LHS.getValueType();
20135 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20137 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20138 // instructions match the semantics of the common C idiom x<y?x:y but not
20139 // x<=y?x:y, because of how they handle negative zero (which can be
20140 // ignored in unsafe-math mode).
20141 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20142 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20143 (Subtarget->hasSSE2() ||
20144 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20145 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20147 unsigned Opcode = 0;
20148 // Check for x CC y ? x : y.
20149 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20150 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20154 // Converting this to a min would handle NaNs incorrectly, and swapping
20155 // the operands would cause it to handle comparisons between positive
20156 // and negative zero incorrectly.
20157 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20158 if (!DAG.getTarget().Options.UnsafeFPMath &&
20159 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20161 std::swap(LHS, RHS);
20163 Opcode = X86ISD::FMIN;
20166 // Converting this to a min would handle comparisons between positive
20167 // and negative zero incorrectly.
20168 if (!DAG.getTarget().Options.UnsafeFPMath &&
20169 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20171 Opcode = X86ISD::FMIN;
20174 // Converting this to a min would handle both negative zeros and NaNs
20175 // incorrectly, but we can swap the operands to fix both.
20176 std::swap(LHS, RHS);
20180 Opcode = X86ISD::FMIN;
20184 // Converting this to a max would handle comparisons between positive
20185 // and negative zero incorrectly.
20186 if (!DAG.getTarget().Options.UnsafeFPMath &&
20187 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20189 Opcode = X86ISD::FMAX;
20192 // Converting this to a max would handle NaNs incorrectly, and swapping
20193 // the operands would cause it to handle comparisons between positive
20194 // and negative zero incorrectly.
20195 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20196 if (!DAG.getTarget().Options.UnsafeFPMath &&
20197 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20199 std::swap(LHS, RHS);
20201 Opcode = X86ISD::FMAX;
20204 // Converting this to a max would handle both negative zeros and NaNs
20205 // incorrectly, but we can swap the operands to fix both.
20206 std::swap(LHS, RHS);
20210 Opcode = X86ISD::FMAX;
20213 // Check for x CC y ? y : x -- a min/max with reversed arms.
20214 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20215 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20219 // Converting this to a min would handle comparisons between positive
20220 // and negative zero incorrectly, and swapping the operands would
20221 // cause it to handle NaNs incorrectly.
20222 if (!DAG.getTarget().Options.UnsafeFPMath &&
20223 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20224 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20226 std::swap(LHS, RHS);
20228 Opcode = X86ISD::FMIN;
20231 // Converting this to a min would handle NaNs incorrectly.
20232 if (!DAG.getTarget().Options.UnsafeFPMath &&
20233 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20235 Opcode = X86ISD::FMIN;
20238 // Converting this to a min would handle both negative zeros and NaNs
20239 // incorrectly, but we can swap the operands to fix both.
20240 std::swap(LHS, RHS);
20244 Opcode = X86ISD::FMIN;
20248 // Converting this to a max would handle NaNs incorrectly.
20249 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20251 Opcode = X86ISD::FMAX;
20254 // Converting this to a max would handle comparisons between positive
20255 // and negative zero incorrectly, and swapping the operands would
20256 // cause it to handle NaNs incorrectly.
20257 if (!DAG.getTarget().Options.UnsafeFPMath &&
20258 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20259 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20261 std::swap(LHS, RHS);
20263 Opcode = X86ISD::FMAX;
20266 // Converting this to a max would handle both negative zeros and NaNs
20267 // incorrectly, but we can swap the operands to fix both.
20268 std::swap(LHS, RHS);
20272 Opcode = X86ISD::FMAX;
20278 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20281 EVT CondVT = Cond.getValueType();
20282 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20283 CondVT.getVectorElementType() == MVT::i1) {
20284 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20285 // lowering on KNL. In this case we convert it to
20286 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20287 // The same situation for all 128 and 256-bit vectors of i8 and i16.
20288 // Since SKX these selects have a proper lowering.
20289 EVT OpVT = LHS.getValueType();
20290 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20291 (OpVT.getVectorElementType() == MVT::i8 ||
20292 OpVT.getVectorElementType() == MVT::i16) &&
20293 !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20294 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20295 DCI.AddToWorklist(Cond.getNode());
20296 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20299 // If this is a select between two integer constants, try to do some
20301 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20302 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20303 // Don't do this for crazy integer types.
20304 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20305 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20306 // so that TrueC (the true value) is larger than FalseC.
20307 bool NeedsCondInvert = false;
20309 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20310 // Efficiently invertible.
20311 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
20312 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
20313 isa<ConstantSDNode>(Cond.getOperand(1))))) {
20314 NeedsCondInvert = true;
20315 std::swap(TrueC, FalseC);
20318 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
20319 if (FalseC->getAPIntValue() == 0 &&
20320 TrueC->getAPIntValue().isPowerOf2()) {
20321 if (NeedsCondInvert) // Invert the condition if needed.
20322 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20323 DAG.getConstant(1, Cond.getValueType()));
20325 // Zero extend the condition if needed.
20326 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20328 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20329 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20330 DAG.getConstant(ShAmt, MVT::i8));
20333 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20334 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20335 if (NeedsCondInvert) // Invert the condition if needed.
20336 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20337 DAG.getConstant(1, Cond.getValueType()));
20339 // Zero extend the condition if needed.
20340 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20341 FalseC->getValueType(0), Cond);
20342 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20343 SDValue(FalseC, 0));
20346 // Optimize cases that will turn into an LEA instruction. This requires
20347 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20348 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20349 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20350 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20352 bool isFastMultiplier = false;
20354 switch ((unsigned char)Diff) {
20356 case 1: // result = add base, cond
20357 case 2: // result = lea base( , cond*2)
20358 case 3: // result = lea base(cond, cond*2)
20359 case 4: // result = lea base( , cond*4)
20360 case 5: // result = lea base(cond, cond*4)
20361 case 8: // result = lea base( , cond*8)
20362 case 9: // result = lea base(cond, cond*8)
20363 isFastMultiplier = true;
20368 if (isFastMultiplier) {
20369 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20370 if (NeedsCondInvert) // Invert the condition if needed.
20371 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20372 DAG.getConstant(1, Cond.getValueType()));
20374 // Zero extend the condition if needed.
20375 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20377 // Scale the condition by the difference.
20379 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20380 DAG.getConstant(Diff, Cond.getValueType()));
20382 // Add the base if non-zero.
20383 if (FalseC->getAPIntValue() != 0)
20384 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20385 SDValue(FalseC, 0));
20392 // Canonicalize max and min:
20393 // (x > y) ? x : y -> (x >= y) ? x : y
20394 // (x < y) ? x : y -> (x <= y) ? x : y
20395 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20396 // the need for an extra compare
20397 // against zero. e.g.
20398 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20400 // testl %edi, %edi
20402 // cmovgl %edi, %eax
20406 // cmovsl %eax, %edi
20407 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20408 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20409 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20410 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20415 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20416 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20417 Cond.getOperand(0), Cond.getOperand(1), NewCC);
20418 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20423 // Early exit check
20424 if (!TLI.isTypeLegal(VT))
20427 // Match VSELECTs into subs with unsigned saturation.
20428 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20429 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20430 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20431 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20432 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20434 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20435 // left side invert the predicate to simplify logic below.
20437 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20439 CC = ISD::getSetCCInverse(CC, true);
20440 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20444 if (Other.getNode() && Other->getNumOperands() == 2 &&
20445 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20446 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20447 SDValue CondRHS = Cond->getOperand(1);
20449 // Look for a general sub with unsigned saturation first.
20450 // x >= y ? x-y : 0 --> subus x, y
20451 // x > y ? x-y : 0 --> subus x, y
20452 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20453 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20454 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20456 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20457 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20458 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20459 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20460 // If the RHS is a constant we have to reverse the const
20461 // canonicalization.
20462 // x > C-1 ? x+-C : 0 --> subus x, C
20463 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20464 CondRHSConst->getAPIntValue() ==
20465 (-OpRHSConst->getAPIntValue() - 1))
20466 return DAG.getNode(
20467 X86ISD::SUBUS, DL, VT, OpLHS,
20468 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20470 // Another special case: If C was a sign bit, the sub has been
20471 // canonicalized into a xor.
20472 // FIXME: Would it be better to use computeKnownBits to determine
20473 // whether it's safe to decanonicalize the xor?
20474 // x s< 0 ? x^C : 0 --> subus x, C
20475 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20476 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20477 OpRHSConst->getAPIntValue().isSignBit())
20478 // Note that we have to rebuild the RHS constant here to ensure we
20479 // don't rely on particular values of undef lanes.
20480 return DAG.getNode(
20481 X86ISD::SUBUS, DL, VT, OpLHS,
20482 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20487 // Try to match a min/max vector operation.
20488 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20489 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20490 unsigned Opc = ret.first;
20491 bool NeedSplit = ret.second;
20493 if (Opc && NeedSplit) {
20494 unsigned NumElems = VT.getVectorNumElements();
20495 // Extract the LHS vectors
20496 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20497 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20499 // Extract the RHS vectors
20500 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20501 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20503 // Create min/max for each subvector
20504 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20505 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20507 // Merge the result
20508 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20510 return DAG.getNode(Opc, DL, VT, LHS, RHS);
20513 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20514 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20515 // Check if SETCC has already been promoted
20516 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20517 // Check that condition value type matches vselect operand type
20520 assert(Cond.getValueType().isVector() &&
20521 "vector select expects a vector selector!");
20523 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20524 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20526 if (!TValIsAllOnes && !FValIsAllZeros) {
20527 // Try invert the condition if true value is not all 1s and false value
20529 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20530 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20532 if (TValIsAllZeros || FValIsAllOnes) {
20533 SDValue CC = Cond.getOperand(2);
20534 ISD::CondCode NewCC =
20535 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20536 Cond.getOperand(0).getValueType().isInteger());
20537 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20538 std::swap(LHS, RHS);
20539 TValIsAllOnes = FValIsAllOnes;
20540 FValIsAllZeros = TValIsAllZeros;
20544 if (TValIsAllOnes || FValIsAllZeros) {
20547 if (TValIsAllOnes && FValIsAllZeros)
20549 else if (TValIsAllOnes)
20550 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20551 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20552 else if (FValIsAllZeros)
20553 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20554 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20556 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20560 // Try to fold this VSELECT into a MOVSS/MOVSD
20561 if (N->getOpcode() == ISD::VSELECT &&
20562 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20563 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20564 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20565 bool CanFold = false;
20566 unsigned NumElems = Cond.getNumOperands();
20570 if (isZero(Cond.getOperand(0))) {
20573 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20574 // fold (vselect <0,-1> -> (movsd A, B)
20575 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20576 CanFold = isAllOnes(Cond.getOperand(i));
20577 } else if (isAllOnes(Cond.getOperand(0))) {
20581 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20582 // fold (vselect <-1,0> -> (movsd B, A)
20583 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20584 CanFold = isZero(Cond.getOperand(i));
20588 if (VT == MVT::v4i32 || VT == MVT::v4f32)
20589 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20590 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20593 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20594 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20595 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20596 // (v2i64 (bitcast B)))))
20598 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20599 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20600 // (v2f64 (bitcast B)))))
20602 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20603 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20604 // (v2i64 (bitcast A)))))
20606 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20607 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20608 // (v2f64 (bitcast A)))))
20610 CanFold = (isZero(Cond.getOperand(0)) &&
20611 isZero(Cond.getOperand(1)) &&
20612 isAllOnes(Cond.getOperand(2)) &&
20613 isAllOnes(Cond.getOperand(3)));
20615 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20616 isAllOnes(Cond.getOperand(1)) &&
20617 isZero(Cond.getOperand(2)) &&
20618 isZero(Cond.getOperand(3))) {
20620 std::swap(LHS, RHS);
20624 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20625 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20626 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20627 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20629 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20635 // If we know that this node is legal then we know that it is going to be
20636 // matched by one of the SSE/AVX BLEND instructions. These instructions only
20637 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20638 // to simplify previous instructions.
20639 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20640 !DCI.isBeforeLegalize() &&
20641 // We explicitly check against v8i16 and v16i16 because, although
20642 // they're marked as Custom, they might only be legal when Cond is a
20643 // build_vector of constants. This will be taken care in a later
20645 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20646 VT != MVT::v8i16)) {
20647 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20649 // Don't optimize vector selects that map to mask-registers.
20653 // Check all uses of that condition operand to check whether it will be
20654 // consumed by non-BLEND instructions, which may depend on all bits are set
20656 for (SDNode::use_iterator I = Cond->use_begin(),
20657 E = Cond->use_end(); I != E; ++I)
20658 if (I->getOpcode() != ISD::VSELECT)
20659 // TODO: Add other opcodes eventually lowered into BLEND.
20662 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20663 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20665 APInt KnownZero, KnownOne;
20666 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20667 DCI.isBeforeLegalizeOps());
20668 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20669 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20670 DCI.CommitTargetLoweringOpt(TLO);
20673 // We should generate an X86ISD::BLENDI from a vselect if its argument
20674 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20675 // constants. This specific pattern gets generated when we split a
20676 // selector for a 512 bit vector in a machine without AVX512 (but with
20677 // 256-bit vectors), during legalization:
20679 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20681 // Iff we find this pattern and the build_vectors are built from
20682 // constants, we translate the vselect into a shuffle_vector that we
20683 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20684 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20685 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20686 if (Shuffle.getNode())
20693 // Check whether a boolean test is testing a boolean value generated by
20694 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20697 // Simplify the following patterns:
20698 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20699 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20700 // to (Op EFLAGS Cond)
20702 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20703 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20704 // to (Op EFLAGS !Cond)
20706 // where Op could be BRCOND or CMOV.
20708 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20709 // Quit if not CMP and SUB with its value result used.
20710 if (Cmp.getOpcode() != X86ISD::CMP &&
20711 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20714 // Quit if not used as a boolean value.
20715 if (CC != X86::COND_E && CC != X86::COND_NE)
20718 // Check CMP operands. One of them should be 0 or 1 and the other should be
20719 // an SetCC or extended from it.
20720 SDValue Op1 = Cmp.getOperand(0);
20721 SDValue Op2 = Cmp.getOperand(1);
20724 const ConstantSDNode* C = nullptr;
20725 bool needOppositeCond = (CC == X86::COND_E);
20726 bool checkAgainstTrue = false; // Is it a comparison against 1?
20728 if ((C = dyn_cast<ConstantSDNode>(Op1)))
20730 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20732 else // Quit if all operands are not constants.
20735 if (C->getZExtValue() == 1) {
20736 needOppositeCond = !needOppositeCond;
20737 checkAgainstTrue = true;
20738 } else if (C->getZExtValue() != 0)
20739 // Quit if the constant is neither 0 or 1.
20742 bool truncatedToBoolWithAnd = false;
20743 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20744 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20745 SetCC.getOpcode() == ISD::TRUNCATE ||
20746 SetCC.getOpcode() == ISD::AND) {
20747 if (SetCC.getOpcode() == ISD::AND) {
20749 ConstantSDNode *CS;
20750 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20751 CS->getZExtValue() == 1)
20753 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20754 CS->getZExtValue() == 1)
20758 SetCC = SetCC.getOperand(OpIdx);
20759 truncatedToBoolWithAnd = true;
20761 SetCC = SetCC.getOperand(0);
20764 switch (SetCC.getOpcode()) {
20765 case X86ISD::SETCC_CARRY:
20766 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20767 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20768 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20769 // truncated to i1 using 'and'.
20770 if (checkAgainstTrue && !truncatedToBoolWithAnd)
20772 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20773 "Invalid use of SETCC_CARRY!");
20775 case X86ISD::SETCC:
20776 // Set the condition code or opposite one if necessary.
20777 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20778 if (needOppositeCond)
20779 CC = X86::GetOppositeBranchCondition(CC);
20780 return SetCC.getOperand(1);
20781 case X86ISD::CMOV: {
20782 // Check whether false/true value has canonical one, i.e. 0 or 1.
20783 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20784 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20785 // Quit if true value is not a constant.
20788 // Quit if false value is not a constant.
20790 SDValue Op = SetCC.getOperand(0);
20791 // Skip 'zext' or 'trunc' node.
20792 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20793 Op.getOpcode() == ISD::TRUNCATE)
20794 Op = Op.getOperand(0);
20795 // A special case for rdrand/rdseed, where 0 is set if false cond is
20797 if ((Op.getOpcode() != X86ISD::RDRAND &&
20798 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20801 // Quit if false value is not the constant 0 or 1.
20802 bool FValIsFalse = true;
20803 if (FVal && FVal->getZExtValue() != 0) {
20804 if (FVal->getZExtValue() != 1)
20806 // If FVal is 1, opposite cond is needed.
20807 needOppositeCond = !needOppositeCond;
20808 FValIsFalse = false;
20810 // Quit if TVal is not the constant opposite of FVal.
20811 if (FValIsFalse && TVal->getZExtValue() != 1)
20813 if (!FValIsFalse && TVal->getZExtValue() != 0)
20815 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20816 if (needOppositeCond)
20817 CC = X86::GetOppositeBranchCondition(CC);
20818 return SetCC.getOperand(3);
20825 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20826 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20827 TargetLowering::DAGCombinerInfo &DCI,
20828 const X86Subtarget *Subtarget) {
20831 // If the flag operand isn't dead, don't touch this CMOV.
20832 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20835 SDValue FalseOp = N->getOperand(0);
20836 SDValue TrueOp = N->getOperand(1);
20837 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20838 SDValue Cond = N->getOperand(3);
20840 if (CC == X86::COND_E || CC == X86::COND_NE) {
20841 switch (Cond.getOpcode()) {
20845 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20846 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20847 return (CC == X86::COND_E) ? FalseOp : TrueOp;
20853 Flags = checkBoolTestSetCCCombine(Cond, CC);
20854 if (Flags.getNode() &&
20855 // Extra check as FCMOV only supports a subset of X86 cond.
20856 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20857 SDValue Ops[] = { FalseOp, TrueOp,
20858 DAG.getConstant(CC, MVT::i8), Flags };
20859 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20862 // If this is a select between two integer constants, try to do some
20863 // optimizations. Note that the operands are ordered the opposite of SELECT
20865 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20866 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20867 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20868 // larger than FalseC (the false value).
20869 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20870 CC = X86::GetOppositeBranchCondition(CC);
20871 std::swap(TrueC, FalseC);
20872 std::swap(TrueOp, FalseOp);
20875 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
20876 // This is efficient for any integer data type (including i8/i16) and
20878 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20879 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20880 DAG.getConstant(CC, MVT::i8), Cond);
20882 // Zero extend the condition if needed.
20883 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20885 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20886 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20887 DAG.getConstant(ShAmt, MVT::i8));
20888 if (N->getNumValues() == 2) // Dead flag value?
20889 return DCI.CombineTo(N, Cond, SDValue());
20893 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
20894 // for any integer data type, including i8/i16.
20895 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20896 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20897 DAG.getConstant(CC, MVT::i8), Cond);
20899 // Zero extend the condition if needed.
20900 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20901 FalseC->getValueType(0), Cond);
20902 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20903 SDValue(FalseC, 0));
20905 if (N->getNumValues() == 2) // Dead flag value?
20906 return DCI.CombineTo(N, Cond, SDValue());
20910 // Optimize cases that will turn into an LEA instruction. This requires
20911 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20912 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20913 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20914 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20916 bool isFastMultiplier = false;
20918 switch ((unsigned char)Diff) {
20920 case 1: // result = add base, cond
20921 case 2: // result = lea base( , cond*2)
20922 case 3: // result = lea base(cond, cond*2)
20923 case 4: // result = lea base( , cond*4)
20924 case 5: // result = lea base(cond, cond*4)
20925 case 8: // result = lea base( , cond*8)
20926 case 9: // result = lea base(cond, cond*8)
20927 isFastMultiplier = true;
20932 if (isFastMultiplier) {
20933 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20934 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20935 DAG.getConstant(CC, MVT::i8), Cond);
20936 // Zero extend the condition if needed.
20937 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20939 // Scale the condition by the difference.
20941 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20942 DAG.getConstant(Diff, Cond.getValueType()));
20944 // Add the base if non-zero.
20945 if (FalseC->getAPIntValue() != 0)
20946 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20947 SDValue(FalseC, 0));
20948 if (N->getNumValues() == 2) // Dead flag value?
20949 return DCI.CombineTo(N, Cond, SDValue());
20956 // Handle these cases:
20957 // (select (x != c), e, c) -> select (x != c), e, x),
20958 // (select (x == c), c, e) -> select (x == c), x, e)
20959 // where the c is an integer constant, and the "select" is the combination
20960 // of CMOV and CMP.
20962 // The rationale for this change is that the conditional-move from a constant
20963 // needs two instructions, however, conditional-move from a register needs
20964 // only one instruction.
20966 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20967 // some instruction-combining opportunities. This opt needs to be
20968 // postponed as late as possible.
20970 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20971 // the DCI.xxxx conditions are provided to postpone the optimization as
20972 // late as possible.
20974 ConstantSDNode *CmpAgainst = nullptr;
20975 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20976 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20977 !isa<ConstantSDNode>(Cond.getOperand(0))) {
20979 if (CC == X86::COND_NE &&
20980 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20981 CC = X86::GetOppositeBranchCondition(CC);
20982 std::swap(TrueOp, FalseOp);
20985 if (CC == X86::COND_E &&
20986 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20987 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20988 DAG.getConstant(CC, MVT::i8), Cond };
20989 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20997 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20998 const X86Subtarget *Subtarget) {
20999 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21001 default: return SDValue();
21002 // SSE/AVX/AVX2 blend intrinsics.
21003 case Intrinsic::x86_avx2_pblendvb:
21004 case Intrinsic::x86_avx2_pblendw:
21005 case Intrinsic::x86_avx2_pblendd_128:
21006 case Intrinsic::x86_avx2_pblendd_256:
21007 // Don't try to simplify this intrinsic if we don't have AVX2.
21008 if (!Subtarget->hasAVX2())
21011 case Intrinsic::x86_avx_blend_pd_256:
21012 case Intrinsic::x86_avx_blend_ps_256:
21013 case Intrinsic::x86_avx_blendv_pd_256:
21014 case Intrinsic::x86_avx_blendv_ps_256:
21015 // Don't try to simplify this intrinsic if we don't have AVX.
21016 if (!Subtarget->hasAVX())
21019 case Intrinsic::x86_sse41_pblendw:
21020 case Intrinsic::x86_sse41_blendpd:
21021 case Intrinsic::x86_sse41_blendps:
21022 case Intrinsic::x86_sse41_blendvps:
21023 case Intrinsic::x86_sse41_blendvpd:
21024 case Intrinsic::x86_sse41_pblendvb: {
21025 SDValue Op0 = N->getOperand(1);
21026 SDValue Op1 = N->getOperand(2);
21027 SDValue Mask = N->getOperand(3);
21029 // Don't try to simplify this intrinsic if we don't have SSE4.1.
21030 if (!Subtarget->hasSSE41())
21033 // fold (blend A, A, Mask) -> A
21036 // fold (blend A, B, allZeros) -> A
21037 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21039 // fold (blend A, B, allOnes) -> B
21040 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21043 // Simplify the case where the mask is a constant i32 value.
21044 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21045 if (C->isNullValue())
21047 if (C->isAllOnesValue())
21054 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21055 case Intrinsic::x86_sse2_psrai_w:
21056 case Intrinsic::x86_sse2_psrai_d:
21057 case Intrinsic::x86_avx2_psrai_w:
21058 case Intrinsic::x86_avx2_psrai_d:
21059 case Intrinsic::x86_sse2_psra_w:
21060 case Intrinsic::x86_sse2_psra_d:
21061 case Intrinsic::x86_avx2_psra_w:
21062 case Intrinsic::x86_avx2_psra_d: {
21063 SDValue Op0 = N->getOperand(1);
21064 SDValue Op1 = N->getOperand(2);
21065 EVT VT = Op0.getValueType();
21066 assert(VT.isVector() && "Expected a vector type!");
21068 if (isa<BuildVectorSDNode>(Op1))
21069 Op1 = Op1.getOperand(0);
21071 if (!isa<ConstantSDNode>(Op1))
21074 EVT SVT = VT.getVectorElementType();
21075 unsigned SVTBits = SVT.getSizeInBits();
21077 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21078 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21079 uint64_t ShAmt = C.getZExtValue();
21081 // Don't try to convert this shift into a ISD::SRA if the shift
21082 // count is bigger than or equal to the element size.
21083 if (ShAmt >= SVTBits)
21086 // Trivial case: if the shift count is zero, then fold this
21087 // into the first operand.
21091 // Replace this packed shift intrinsic with a target independent
21093 SDValue Splat = DAG.getConstant(C, VT);
21094 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21099 /// PerformMulCombine - Optimize a single multiply with constant into two
21100 /// in order to implement it with two cheaper instructions, e.g.
21101 /// LEA + SHL, LEA + LEA.
21102 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21103 TargetLowering::DAGCombinerInfo &DCI) {
21104 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21107 EVT VT = N->getValueType(0);
21108 if (VT != MVT::i64)
21111 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21114 uint64_t MulAmt = C->getZExtValue();
21115 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21118 uint64_t MulAmt1 = 0;
21119 uint64_t MulAmt2 = 0;
21120 if ((MulAmt % 9) == 0) {
21122 MulAmt2 = MulAmt / 9;
21123 } else if ((MulAmt % 5) == 0) {
21125 MulAmt2 = MulAmt / 5;
21126 } else if ((MulAmt % 3) == 0) {
21128 MulAmt2 = MulAmt / 3;
21131 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21134 if (isPowerOf2_64(MulAmt2) &&
21135 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21136 // If second multiplifer is pow2, issue it first. We want the multiply by
21137 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21139 std::swap(MulAmt1, MulAmt2);
21142 if (isPowerOf2_64(MulAmt1))
21143 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21144 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21146 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21147 DAG.getConstant(MulAmt1, VT));
21149 if (isPowerOf2_64(MulAmt2))
21150 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21151 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21153 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21154 DAG.getConstant(MulAmt2, VT));
21156 // Do not add new nodes to DAG combiner worklist.
21157 DCI.CombineTo(N, NewMul, false);
21162 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21163 SDValue N0 = N->getOperand(0);
21164 SDValue N1 = N->getOperand(1);
21165 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21166 EVT VT = N0.getValueType();
21168 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21169 // since the result of setcc_c is all zero's or all ones.
21170 if (VT.isInteger() && !VT.isVector() &&
21171 N1C && N0.getOpcode() == ISD::AND &&
21172 N0.getOperand(1).getOpcode() == ISD::Constant) {
21173 SDValue N00 = N0.getOperand(0);
21174 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21175 ((N00.getOpcode() == ISD::ANY_EXTEND ||
21176 N00.getOpcode() == ISD::ZERO_EXTEND) &&
21177 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21178 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21179 APInt ShAmt = N1C->getAPIntValue();
21180 Mask = Mask.shl(ShAmt);
21182 return DAG.getNode(ISD::AND, SDLoc(N), VT,
21183 N00, DAG.getConstant(Mask, VT));
21187 // Hardware support for vector shifts is sparse which makes us scalarize the
21188 // vector operations in many cases. Also, on sandybridge ADD is faster than
21190 // (shl V, 1) -> add V,V
21191 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21192 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21193 assert(N0.getValueType().isVector() && "Invalid vector shift type");
21194 // We shift all of the values by one. In many cases we do not have
21195 // hardware support for this operation. This is better expressed as an ADD
21197 if (N1SplatC->getZExtValue() == 1)
21198 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21204 /// \brief Returns a vector of 0s if the node in input is a vector logical
21205 /// shift by a constant amount which is known to be bigger than or equal
21206 /// to the vector element size in bits.
21207 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21208 const X86Subtarget *Subtarget) {
21209 EVT VT = N->getValueType(0);
21211 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21212 (!Subtarget->hasInt256() ||
21213 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21216 SDValue Amt = N->getOperand(1);
21218 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21219 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21220 APInt ShiftAmt = AmtSplat->getAPIntValue();
21221 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21223 // SSE2/AVX2 logical shifts always return a vector of 0s
21224 // if the shift amount is bigger than or equal to
21225 // the element size. The constant shift amount will be
21226 // encoded as a 8-bit immediate.
21227 if (ShiftAmt.trunc(8).uge(MaxAmount))
21228 return getZeroVector(VT, Subtarget, DAG, DL);
21234 /// PerformShiftCombine - Combine shifts.
21235 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21236 TargetLowering::DAGCombinerInfo &DCI,
21237 const X86Subtarget *Subtarget) {
21238 if (N->getOpcode() == ISD::SHL) {
21239 SDValue V = PerformSHLCombine(N, DAG);
21240 if (V.getNode()) return V;
21243 if (N->getOpcode() != ISD::SRA) {
21244 // Try to fold this logical shift into a zero vector.
21245 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21246 if (V.getNode()) return V;
21252 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
21253 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21254 // and friends. Likewise for OR -> CMPNEQSS.
21255 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21256 TargetLowering::DAGCombinerInfo &DCI,
21257 const X86Subtarget *Subtarget) {
21260 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21261 // we're requiring SSE2 for both.
21262 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21263 SDValue N0 = N->getOperand(0);
21264 SDValue N1 = N->getOperand(1);
21265 SDValue CMP0 = N0->getOperand(1);
21266 SDValue CMP1 = N1->getOperand(1);
21269 // The SETCCs should both refer to the same CMP.
21270 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21273 SDValue CMP00 = CMP0->getOperand(0);
21274 SDValue CMP01 = CMP0->getOperand(1);
21275 EVT VT = CMP00.getValueType();
21277 if (VT == MVT::f32 || VT == MVT::f64) {
21278 bool ExpectingFlags = false;
21279 // Check for any users that want flags:
21280 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21281 !ExpectingFlags && UI != UE; ++UI)
21282 switch (UI->getOpcode()) {
21287 ExpectingFlags = true;
21289 case ISD::CopyToReg:
21290 case ISD::SIGN_EXTEND:
21291 case ISD::ZERO_EXTEND:
21292 case ISD::ANY_EXTEND:
21296 if (!ExpectingFlags) {
21297 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21298 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21300 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21301 X86::CondCode tmp = cc0;
21306 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
21307 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21308 // FIXME: need symbolic constants for these magic numbers.
21309 // See X86ATTInstPrinter.cpp:printSSECC().
21310 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21311 if (Subtarget->hasAVX512()) {
21312 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21313 CMP01, DAG.getConstant(x86cc, MVT::i8));
21314 if (N->getValueType(0) != MVT::i1)
21315 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21319 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21320 CMP00.getValueType(), CMP00, CMP01,
21321 DAG.getConstant(x86cc, MVT::i8));
21323 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21324 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21326 if (is64BitFP && !Subtarget->is64Bit()) {
21327 // On a 32-bit target, we cannot bitcast the 64-bit float to a
21328 // 64-bit integer, since that's not a legal type. Since
21329 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21330 // bits, but can do this little dance to extract the lowest 32 bits
21331 // and work with those going forward.
21332 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21334 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21336 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21337 Vector32, DAG.getIntPtrConstant(0));
21341 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21342 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21343 DAG.getConstant(1, IntVT));
21344 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21345 return OneBitOfTruth;
21353 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21354 /// so it can be folded inside ANDNP.
21355 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21356 EVT VT = N->getValueType(0);
21358 // Match direct AllOnes for 128 and 256-bit vectors
21359 if (ISD::isBuildVectorAllOnes(N))
21362 // Look through a bit convert.
21363 if (N->getOpcode() == ISD::BITCAST)
21364 N = N->getOperand(0).getNode();
21366 // Sometimes the operand may come from a insert_subvector building a 256-bit
21368 if (VT.is256BitVector() &&
21369 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21370 SDValue V1 = N->getOperand(0);
21371 SDValue V2 = N->getOperand(1);
21373 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21374 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21375 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21376 ISD::isBuildVectorAllOnes(V2.getNode()))
21383 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21384 // register. In most cases we actually compare or select YMM-sized registers
21385 // and mixing the two types creates horrible code. This method optimizes
21386 // some of the transition sequences.
21387 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21388 TargetLowering::DAGCombinerInfo &DCI,
21389 const X86Subtarget *Subtarget) {
21390 EVT VT = N->getValueType(0);
21391 if (!VT.is256BitVector())
21394 assert((N->getOpcode() == ISD::ANY_EXTEND ||
21395 N->getOpcode() == ISD::ZERO_EXTEND ||
21396 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21398 SDValue Narrow = N->getOperand(0);
21399 EVT NarrowVT = Narrow->getValueType(0);
21400 if (!NarrowVT.is128BitVector())
21403 if (Narrow->getOpcode() != ISD::XOR &&
21404 Narrow->getOpcode() != ISD::AND &&
21405 Narrow->getOpcode() != ISD::OR)
21408 SDValue N0 = Narrow->getOperand(0);
21409 SDValue N1 = Narrow->getOperand(1);
21412 // The Left side has to be a trunc.
21413 if (N0.getOpcode() != ISD::TRUNCATE)
21416 // The type of the truncated inputs.
21417 EVT WideVT = N0->getOperand(0)->getValueType(0);
21421 // The right side has to be a 'trunc' or a constant vector.
21422 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21423 ConstantSDNode *RHSConstSplat = nullptr;
21424 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21425 RHSConstSplat = RHSBV->getConstantSplatNode();
21426 if (!RHSTrunc && !RHSConstSplat)
21429 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21431 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21434 // Set N0 and N1 to hold the inputs to the new wide operation.
21435 N0 = N0->getOperand(0);
21436 if (RHSConstSplat) {
21437 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21438 SDValue(RHSConstSplat, 0));
21439 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21440 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21441 } else if (RHSTrunc) {
21442 N1 = N1->getOperand(0);
21445 // Generate the wide operation.
21446 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21447 unsigned Opcode = N->getOpcode();
21449 case ISD::ANY_EXTEND:
21451 case ISD::ZERO_EXTEND: {
21452 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21453 APInt Mask = APInt::getAllOnesValue(InBits);
21454 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21455 return DAG.getNode(ISD::AND, DL, VT,
21456 Op, DAG.getConstant(Mask, VT));
21458 case ISD::SIGN_EXTEND:
21459 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21460 Op, DAG.getValueType(NarrowVT));
21462 llvm_unreachable("Unexpected opcode");
21466 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21467 TargetLowering::DAGCombinerInfo &DCI,
21468 const X86Subtarget *Subtarget) {
21469 EVT VT = N->getValueType(0);
21470 if (DCI.isBeforeLegalizeOps())
21473 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21477 // Create BEXTR instructions
21478 // BEXTR is ((X >> imm) & (2**size-1))
21479 if (VT == MVT::i32 || VT == MVT::i64) {
21480 SDValue N0 = N->getOperand(0);
21481 SDValue N1 = N->getOperand(1);
21484 // Check for BEXTR.
21485 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21486 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21487 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21488 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21489 if (MaskNode && ShiftNode) {
21490 uint64_t Mask = MaskNode->getZExtValue();
21491 uint64_t Shift = ShiftNode->getZExtValue();
21492 if (isMask_64(Mask)) {
21493 uint64_t MaskSize = CountPopulation_64(Mask);
21494 if (Shift + MaskSize <= VT.getSizeInBits())
21495 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21496 DAG.getConstant(Shift | (MaskSize << 8), VT));
21504 // Want to form ANDNP nodes:
21505 // 1) In the hopes of then easily combining them with OR and AND nodes
21506 // to form PBLEND/PSIGN.
21507 // 2) To match ANDN packed intrinsics
21508 if (VT != MVT::v2i64 && VT != MVT::v4i64)
21511 SDValue N0 = N->getOperand(0);
21512 SDValue N1 = N->getOperand(1);
21515 // Check LHS for vnot
21516 if (N0.getOpcode() == ISD::XOR &&
21517 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21518 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21519 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21521 // Check RHS for vnot
21522 if (N1.getOpcode() == ISD::XOR &&
21523 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21524 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21525 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21530 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21531 TargetLowering::DAGCombinerInfo &DCI,
21532 const X86Subtarget *Subtarget) {
21533 if (DCI.isBeforeLegalizeOps())
21536 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21540 SDValue N0 = N->getOperand(0);
21541 SDValue N1 = N->getOperand(1);
21542 EVT VT = N->getValueType(0);
21544 // look for psign/blend
21545 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21546 if (!Subtarget->hasSSSE3() ||
21547 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21550 // Canonicalize pandn to RHS
21551 if (N0.getOpcode() == X86ISD::ANDNP)
21553 // or (and (m, y), (pandn m, x))
21554 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21555 SDValue Mask = N1.getOperand(0);
21556 SDValue X = N1.getOperand(1);
21558 if (N0.getOperand(0) == Mask)
21559 Y = N0.getOperand(1);
21560 if (N0.getOperand(1) == Mask)
21561 Y = N0.getOperand(0);
21563 // Check to see if the mask appeared in both the AND and ANDNP and
21567 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21568 // Look through mask bitcast.
21569 if (Mask.getOpcode() == ISD::BITCAST)
21570 Mask = Mask.getOperand(0);
21571 if (X.getOpcode() == ISD::BITCAST)
21572 X = X.getOperand(0);
21573 if (Y.getOpcode() == ISD::BITCAST)
21574 Y = Y.getOperand(0);
21576 EVT MaskVT = Mask.getValueType();
21578 // Validate that the Mask operand is a vector sra node.
21579 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21580 // there is no psrai.b
21581 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21582 unsigned SraAmt = ~0;
21583 if (Mask.getOpcode() == ISD::SRA) {
21584 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21585 if (auto *AmtConst = AmtBV->getConstantSplatNode())
21586 SraAmt = AmtConst->getZExtValue();
21587 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21588 SDValue SraC = Mask.getOperand(1);
21589 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
21591 if ((SraAmt + 1) != EltBits)
21596 // Now we know we at least have a plendvb with the mask val. See if
21597 // we can form a psignb/w/d.
21598 // psign = x.type == y.type == mask.type && y = sub(0, x);
21599 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21600 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21601 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21602 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21603 "Unsupported VT for PSIGN");
21604 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21605 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21607 // PBLENDVB only available on SSE 4.1
21608 if (!Subtarget->hasSSE41())
21611 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21613 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21614 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21615 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21616 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21617 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21621 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21624 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21625 MachineFunction &MF = DAG.getMachineFunction();
21626 bool OptForSize = MF.getFunction()->getAttributes().
21627 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21629 // SHLD/SHRD instructions have lower register pressure, but on some
21630 // platforms they have higher latency than the equivalent
21631 // series of shifts/or that would otherwise be generated.
21632 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21633 // have higher latencies and we are not optimizing for size.
21634 if (!OptForSize && Subtarget->isSHLDSlow())
21637 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21639 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21641 if (!N0.hasOneUse() || !N1.hasOneUse())
21644 SDValue ShAmt0 = N0.getOperand(1);
21645 if (ShAmt0.getValueType() != MVT::i8)
21647 SDValue ShAmt1 = N1.getOperand(1);
21648 if (ShAmt1.getValueType() != MVT::i8)
21650 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21651 ShAmt0 = ShAmt0.getOperand(0);
21652 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21653 ShAmt1 = ShAmt1.getOperand(0);
21656 unsigned Opc = X86ISD::SHLD;
21657 SDValue Op0 = N0.getOperand(0);
21658 SDValue Op1 = N1.getOperand(0);
21659 if (ShAmt0.getOpcode() == ISD::SUB) {
21660 Opc = X86ISD::SHRD;
21661 std::swap(Op0, Op1);
21662 std::swap(ShAmt0, ShAmt1);
21665 unsigned Bits = VT.getSizeInBits();
21666 if (ShAmt1.getOpcode() == ISD::SUB) {
21667 SDValue Sum = ShAmt1.getOperand(0);
21668 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21669 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21670 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21671 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21672 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21673 return DAG.getNode(Opc, DL, VT,
21675 DAG.getNode(ISD::TRUNCATE, DL,
21678 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21679 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21681 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21682 return DAG.getNode(Opc, DL, VT,
21683 N0.getOperand(0), N1.getOperand(0),
21684 DAG.getNode(ISD::TRUNCATE, DL,
21691 // Generate NEG and CMOV for integer abs.
21692 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21693 EVT VT = N->getValueType(0);
21695 // Since X86 does not have CMOV for 8-bit integer, we don't convert
21696 // 8-bit integer abs to NEG and CMOV.
21697 if (VT.isInteger() && VT.getSizeInBits() == 8)
21700 SDValue N0 = N->getOperand(0);
21701 SDValue N1 = N->getOperand(1);
21704 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21705 // and change it to SUB and CMOV.
21706 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21707 N0.getOpcode() == ISD::ADD &&
21708 N0.getOperand(1) == N1 &&
21709 N1.getOpcode() == ISD::SRA &&
21710 N1.getOperand(0) == N0.getOperand(0))
21711 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21712 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21713 // Generate SUB & CMOV.
21714 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21715 DAG.getConstant(0, VT), N0.getOperand(0));
21717 SDValue Ops[] = { N0.getOperand(0), Neg,
21718 DAG.getConstant(X86::COND_GE, MVT::i8),
21719 SDValue(Neg.getNode(), 1) };
21720 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21725 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21726 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21727 TargetLowering::DAGCombinerInfo &DCI,
21728 const X86Subtarget *Subtarget) {
21729 if (DCI.isBeforeLegalizeOps())
21732 if (Subtarget->hasCMov()) {
21733 SDValue RV = performIntegerAbsCombine(N, DAG);
21741 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21742 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21743 TargetLowering::DAGCombinerInfo &DCI,
21744 const X86Subtarget *Subtarget) {
21745 LoadSDNode *Ld = cast<LoadSDNode>(N);
21746 EVT RegVT = Ld->getValueType(0);
21747 EVT MemVT = Ld->getMemoryVT();
21749 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21751 // On Sandybridge unaligned 256bit loads are inefficient.
21752 ISD::LoadExtType Ext = Ld->getExtensionType();
21753 unsigned Alignment = Ld->getAlignment();
21754 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21755 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21756 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21757 unsigned NumElems = RegVT.getVectorNumElements();
21761 SDValue Ptr = Ld->getBasePtr();
21762 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21764 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21766 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21767 Ld->getPointerInfo(), Ld->isVolatile(),
21768 Ld->isNonTemporal(), Ld->isInvariant(),
21770 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21771 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21772 Ld->getPointerInfo(), Ld->isVolatile(),
21773 Ld->isNonTemporal(), Ld->isInvariant(),
21774 std::min(16U, Alignment));
21775 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21777 Load2.getValue(1));
21779 SDValue NewVec = DAG.getUNDEF(RegVT);
21780 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21781 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21782 return DCI.CombineTo(N, NewVec, TF, true);
21788 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21789 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21790 const X86Subtarget *Subtarget) {
21791 StoreSDNode *St = cast<StoreSDNode>(N);
21792 EVT VT = St->getValue().getValueType();
21793 EVT StVT = St->getMemoryVT();
21795 SDValue StoredVal = St->getOperand(1);
21796 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21798 // If we are saving a concatenation of two XMM registers, perform two stores.
21799 // On Sandy Bridge, 256-bit memory operations are executed by two
21800 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21801 // memory operation.
21802 unsigned Alignment = St->getAlignment();
21803 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21804 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21805 StVT == VT && !IsAligned) {
21806 unsigned NumElems = VT.getVectorNumElements();
21810 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21811 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21813 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21814 SDValue Ptr0 = St->getBasePtr();
21815 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21817 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21818 St->getPointerInfo(), St->isVolatile(),
21819 St->isNonTemporal(), Alignment);
21820 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21821 St->getPointerInfo(), St->isVolatile(),
21822 St->isNonTemporal(),
21823 std::min(16U, Alignment));
21824 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21827 // Optimize trunc store (of multiple scalars) to shuffle and store.
21828 // First, pack all of the elements in one place. Next, store to memory
21829 // in fewer chunks.
21830 if (St->isTruncatingStore() && VT.isVector()) {
21831 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21832 unsigned NumElems = VT.getVectorNumElements();
21833 assert(StVT != VT && "Cannot truncate to the same type");
21834 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21835 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21837 // From, To sizes and ElemCount must be pow of two
21838 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21839 // We are going to use the original vector elt for storing.
21840 // Accumulated smaller vector elements must be a multiple of the store size.
21841 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21843 unsigned SizeRatio = FromSz / ToSz;
21845 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21847 // Create a type on which we perform the shuffle
21848 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21849 StVT.getScalarType(), NumElems*SizeRatio);
21851 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21853 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21854 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21855 for (unsigned i = 0; i != NumElems; ++i)
21856 ShuffleVec[i] = i * SizeRatio;
21858 // Can't shuffle using an illegal type.
21859 if (!TLI.isTypeLegal(WideVecVT))
21862 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21863 DAG.getUNDEF(WideVecVT),
21865 // At this point all of the data is stored at the bottom of the
21866 // register. We now need to save it to mem.
21868 // Find the largest store unit
21869 MVT StoreType = MVT::i8;
21870 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21871 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21872 MVT Tp = (MVT::SimpleValueType)tp;
21873 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21877 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21878 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21879 (64 <= NumElems * ToSz))
21880 StoreType = MVT::f64;
21882 // Bitcast the original vector into a vector of store-size units
21883 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21884 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21885 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21886 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21887 SmallVector<SDValue, 8> Chains;
21888 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21889 TLI.getPointerTy());
21890 SDValue Ptr = St->getBasePtr();
21892 // Perform one or more big stores into memory.
21893 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21894 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21895 StoreType, ShuffWide,
21896 DAG.getIntPtrConstant(i));
21897 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21898 St->getPointerInfo(), St->isVolatile(),
21899 St->isNonTemporal(), St->getAlignment());
21900 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21901 Chains.push_back(Ch);
21904 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21907 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
21908 // the FP state in cases where an emms may be missing.
21909 // A preferable solution to the general problem is to figure out the right
21910 // places to insert EMMS. This qualifies as a quick hack.
21912 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21913 if (VT.getSizeInBits() != 64)
21916 const Function *F = DAG.getMachineFunction().getFunction();
21917 bool NoImplicitFloatOps = F->getAttributes().
21918 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21919 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21920 && Subtarget->hasSSE2();
21921 if ((VT.isVector() ||
21922 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21923 isa<LoadSDNode>(St->getValue()) &&
21924 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21925 St->getChain().hasOneUse() && !St->isVolatile()) {
21926 SDNode* LdVal = St->getValue().getNode();
21927 LoadSDNode *Ld = nullptr;
21928 int TokenFactorIndex = -1;
21929 SmallVector<SDValue, 8> Ops;
21930 SDNode* ChainVal = St->getChain().getNode();
21931 // Must be a store of a load. We currently handle two cases: the load
21932 // is a direct child, and it's under an intervening TokenFactor. It is
21933 // possible to dig deeper under nested TokenFactors.
21934 if (ChainVal == LdVal)
21935 Ld = cast<LoadSDNode>(St->getChain());
21936 else if (St->getValue().hasOneUse() &&
21937 ChainVal->getOpcode() == ISD::TokenFactor) {
21938 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21939 if (ChainVal->getOperand(i).getNode() == LdVal) {
21940 TokenFactorIndex = i;
21941 Ld = cast<LoadSDNode>(St->getValue());
21943 Ops.push_back(ChainVal->getOperand(i));
21947 if (!Ld || !ISD::isNormalLoad(Ld))
21950 // If this is not the MMX case, i.e. we are just turning i64 load/store
21951 // into f64 load/store, avoid the transformation if there are multiple
21952 // uses of the loaded value.
21953 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21958 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21959 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21961 if (Subtarget->is64Bit() || F64IsLegal) {
21962 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21963 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21964 Ld->getPointerInfo(), Ld->isVolatile(),
21965 Ld->isNonTemporal(), Ld->isInvariant(),
21966 Ld->getAlignment());
21967 SDValue NewChain = NewLd.getValue(1);
21968 if (TokenFactorIndex != -1) {
21969 Ops.push_back(NewChain);
21970 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21972 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21973 St->getPointerInfo(),
21974 St->isVolatile(), St->isNonTemporal(),
21975 St->getAlignment());
21978 // Otherwise, lower to two pairs of 32-bit loads / stores.
21979 SDValue LoAddr = Ld->getBasePtr();
21980 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21981 DAG.getConstant(4, MVT::i32));
21983 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21984 Ld->getPointerInfo(),
21985 Ld->isVolatile(), Ld->isNonTemporal(),
21986 Ld->isInvariant(), Ld->getAlignment());
21987 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21988 Ld->getPointerInfo().getWithOffset(4),
21989 Ld->isVolatile(), Ld->isNonTemporal(),
21991 MinAlign(Ld->getAlignment(), 4));
21993 SDValue NewChain = LoLd.getValue(1);
21994 if (TokenFactorIndex != -1) {
21995 Ops.push_back(LoLd);
21996 Ops.push_back(HiLd);
21997 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22000 LoAddr = St->getBasePtr();
22001 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22002 DAG.getConstant(4, MVT::i32));
22004 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22005 St->getPointerInfo(),
22006 St->isVolatile(), St->isNonTemporal(),
22007 St->getAlignment());
22008 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22009 St->getPointerInfo().getWithOffset(4),
22011 St->isNonTemporal(),
22012 MinAlign(St->getAlignment(), 4));
22013 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22018 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
22019 /// and return the operands for the horizontal operation in LHS and RHS. A
22020 /// horizontal operation performs the binary operation on successive elements
22021 /// of its first operand, then on successive elements of its second operand,
22022 /// returning the resulting values in a vector. For example, if
22023 /// A = < float a0, float a1, float a2, float a3 >
22025 /// B = < float b0, float b1, float b2, float b3 >
22026 /// then the result of doing a horizontal operation on A and B is
22027 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22028 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22029 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22030 /// set to A, RHS to B, and the routine returns 'true'.
22031 /// Note that the binary operation should have the property that if one of the
22032 /// operands is UNDEF then the result is UNDEF.
22033 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22034 // Look for the following pattern: if
22035 // A = < float a0, float a1, float a2, float a3 >
22036 // B = < float b0, float b1, float b2, float b3 >
22038 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22039 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22040 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22041 // which is A horizontal-op B.
22043 // At least one of the operands should be a vector shuffle.
22044 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22045 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22048 MVT VT = LHS.getSimpleValueType();
22050 assert((VT.is128BitVector() || VT.is256BitVector()) &&
22051 "Unsupported vector type for horizontal add/sub");
22053 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22054 // operate independently on 128-bit lanes.
22055 unsigned NumElts = VT.getVectorNumElements();
22056 unsigned NumLanes = VT.getSizeInBits()/128;
22057 unsigned NumLaneElts = NumElts / NumLanes;
22058 assert((NumLaneElts % 2 == 0) &&
22059 "Vector type should have an even number of elements in each lane");
22060 unsigned HalfLaneElts = NumLaneElts/2;
22062 // View LHS in the form
22063 // LHS = VECTOR_SHUFFLE A, B, LMask
22064 // If LHS is not a shuffle then pretend it is the shuffle
22065 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22066 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22069 SmallVector<int, 16> LMask(NumElts);
22070 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22071 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22072 A = LHS.getOperand(0);
22073 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22074 B = LHS.getOperand(1);
22075 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22076 std::copy(Mask.begin(), Mask.end(), LMask.begin());
22078 if (LHS.getOpcode() != ISD::UNDEF)
22080 for (unsigned i = 0; i != NumElts; ++i)
22084 // Likewise, view RHS in the form
22085 // RHS = VECTOR_SHUFFLE C, D, RMask
22087 SmallVector<int, 16> RMask(NumElts);
22088 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22089 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22090 C = RHS.getOperand(0);
22091 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22092 D = RHS.getOperand(1);
22093 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22094 std::copy(Mask.begin(), Mask.end(), RMask.begin());
22096 if (RHS.getOpcode() != ISD::UNDEF)
22098 for (unsigned i = 0; i != NumElts; ++i)
22102 // Check that the shuffles are both shuffling the same vectors.
22103 if (!(A == C && B == D) && !(A == D && B == C))
22106 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22107 if (!A.getNode() && !B.getNode())
22110 // If A and B occur in reverse order in RHS, then "swap" them (which means
22111 // rewriting the mask).
22113 CommuteVectorShuffleMask(RMask, NumElts);
22115 // At this point LHS and RHS are equivalent to
22116 // LHS = VECTOR_SHUFFLE A, B, LMask
22117 // RHS = VECTOR_SHUFFLE A, B, RMask
22118 // Check that the masks correspond to performing a horizontal operation.
22119 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22120 for (unsigned i = 0; i != NumLaneElts; ++i) {
22121 int LIdx = LMask[i+l], RIdx = RMask[i+l];
22123 // Ignore any UNDEF components.
22124 if (LIdx < 0 || RIdx < 0 ||
22125 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22126 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22129 // Check that successive elements are being operated on. If not, this is
22130 // not a horizontal operation.
22131 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22132 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22133 if (!(LIdx == Index && RIdx == Index + 1) &&
22134 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22139 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22140 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22144 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22145 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22146 const X86Subtarget *Subtarget) {
22147 EVT VT = N->getValueType(0);
22148 SDValue LHS = N->getOperand(0);
22149 SDValue RHS = N->getOperand(1);
22151 // Try to synthesize horizontal adds from adds of shuffles.
22152 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22153 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22154 isHorizontalBinOp(LHS, RHS, true))
22155 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22159 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22160 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22161 const X86Subtarget *Subtarget) {
22162 EVT VT = N->getValueType(0);
22163 SDValue LHS = N->getOperand(0);
22164 SDValue RHS = N->getOperand(1);
22166 // Try to synthesize horizontal subs from subs of shuffles.
22167 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22168 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22169 isHorizontalBinOp(LHS, RHS, false))
22170 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22174 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22175 /// X86ISD::FXOR nodes.
22176 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22177 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22178 // F[X]OR(0.0, x) -> x
22179 // F[X]OR(x, 0.0) -> x
22180 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22181 if (C->getValueAPF().isPosZero())
22182 return N->getOperand(1);
22183 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22184 if (C->getValueAPF().isPosZero())
22185 return N->getOperand(0);
22189 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22190 /// X86ISD::FMAX nodes.
22191 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22192 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22194 // Only perform optimizations if UnsafeMath is used.
22195 if (!DAG.getTarget().Options.UnsafeFPMath)
22198 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22199 // into FMINC and FMAXC, which are Commutative operations.
22200 unsigned NewOp = 0;
22201 switch (N->getOpcode()) {
22202 default: llvm_unreachable("unknown opcode");
22203 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
22204 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
22207 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22208 N->getOperand(0), N->getOperand(1));
22211 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22212 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22213 // FAND(0.0, x) -> 0.0
22214 // FAND(x, 0.0) -> 0.0
22215 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22216 if (C->getValueAPF().isPosZero())
22217 return N->getOperand(0);
22218 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22219 if (C->getValueAPF().isPosZero())
22220 return N->getOperand(1);
22224 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22225 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22226 // FANDN(x, 0.0) -> 0.0
22227 // FANDN(0.0, x) -> x
22228 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22229 if (C->getValueAPF().isPosZero())
22230 return N->getOperand(1);
22231 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22232 if (C->getValueAPF().isPosZero())
22233 return N->getOperand(1);
22237 static SDValue PerformBTCombine(SDNode *N,
22239 TargetLowering::DAGCombinerInfo &DCI) {
22240 // BT ignores high bits in the bit index operand.
22241 SDValue Op1 = N->getOperand(1);
22242 if (Op1.hasOneUse()) {
22243 unsigned BitWidth = Op1.getValueSizeInBits();
22244 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22245 APInt KnownZero, KnownOne;
22246 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22247 !DCI.isBeforeLegalizeOps());
22248 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22249 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22250 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22251 DCI.CommitTargetLoweringOpt(TLO);
22256 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22257 SDValue Op = N->getOperand(0);
22258 if (Op.getOpcode() == ISD::BITCAST)
22259 Op = Op.getOperand(0);
22260 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22261 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22262 VT.getVectorElementType().getSizeInBits() ==
22263 OpVT.getVectorElementType().getSizeInBits()) {
22264 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22269 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22270 const X86Subtarget *Subtarget) {
22271 EVT VT = N->getValueType(0);
22272 if (!VT.isVector())
22275 SDValue N0 = N->getOperand(0);
22276 SDValue N1 = N->getOperand(1);
22277 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22280 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22281 // both SSE and AVX2 since there is no sign-extended shift right
22282 // operation on a vector with 64-bit elements.
22283 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22284 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22285 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22286 N0.getOpcode() == ISD::SIGN_EXTEND)) {
22287 SDValue N00 = N0.getOperand(0);
22289 // EXTLOAD has a better solution on AVX2,
22290 // it may be replaced with X86ISD::VSEXT node.
22291 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22292 if (!ISD::isNormalLoad(N00.getNode()))
22295 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22296 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22298 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22304 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22305 TargetLowering::DAGCombinerInfo &DCI,
22306 const X86Subtarget *Subtarget) {
22307 if (!DCI.isBeforeLegalizeOps())
22310 if (!Subtarget->hasFp256())
22313 EVT VT = N->getValueType(0);
22314 if (VT.isVector() && VT.getSizeInBits() == 256) {
22315 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22323 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22324 const X86Subtarget* Subtarget) {
22326 EVT VT = N->getValueType(0);
22328 // Let legalize expand this if it isn't a legal type yet.
22329 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22332 EVT ScalarVT = VT.getScalarType();
22333 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22334 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22337 SDValue A = N->getOperand(0);
22338 SDValue B = N->getOperand(1);
22339 SDValue C = N->getOperand(2);
22341 bool NegA = (A.getOpcode() == ISD::FNEG);
22342 bool NegB = (B.getOpcode() == ISD::FNEG);
22343 bool NegC = (C.getOpcode() == ISD::FNEG);
22345 // Negative multiplication when NegA xor NegB
22346 bool NegMul = (NegA != NegB);
22348 A = A.getOperand(0);
22350 B = B.getOperand(0);
22352 C = C.getOperand(0);
22356 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22358 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22360 return DAG.getNode(Opcode, dl, VT, A, B, C);
22363 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22364 TargetLowering::DAGCombinerInfo &DCI,
22365 const X86Subtarget *Subtarget) {
22366 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
22367 // (and (i32 x86isd::setcc_carry), 1)
22368 // This eliminates the zext. This transformation is necessary because
22369 // ISD::SETCC is always legalized to i8.
22371 SDValue N0 = N->getOperand(0);
22372 EVT VT = N->getValueType(0);
22374 if (N0.getOpcode() == ISD::AND &&
22376 N0.getOperand(0).hasOneUse()) {
22377 SDValue N00 = N0.getOperand(0);
22378 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22379 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22380 if (!C || C->getZExtValue() != 1)
22382 return DAG.getNode(ISD::AND, dl, VT,
22383 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22384 N00.getOperand(0), N00.getOperand(1)),
22385 DAG.getConstant(1, VT));
22389 if (N0.getOpcode() == ISD::TRUNCATE &&
22391 N0.getOperand(0).hasOneUse()) {
22392 SDValue N00 = N0.getOperand(0);
22393 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22394 return DAG.getNode(ISD::AND, dl, VT,
22395 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22396 N00.getOperand(0), N00.getOperand(1)),
22397 DAG.getConstant(1, VT));
22400 if (VT.is256BitVector()) {
22401 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22409 // Optimize x == -y --> x+y == 0
22410 // x != -y --> x+y != 0
22411 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22412 const X86Subtarget* Subtarget) {
22413 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22414 SDValue LHS = N->getOperand(0);
22415 SDValue RHS = N->getOperand(1);
22416 EVT VT = N->getValueType(0);
22419 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22420 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22421 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22422 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22423 LHS.getValueType(), RHS, LHS.getOperand(1));
22424 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22425 addV, DAG.getConstant(0, addV.getValueType()), CC);
22427 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22428 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22429 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22430 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22431 RHS.getValueType(), LHS, RHS.getOperand(1));
22432 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22433 addV, DAG.getConstant(0, addV.getValueType()), CC);
22436 if (VT.getScalarType() == MVT::i1) {
22437 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22438 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22439 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22440 if (!IsSEXT0 && !IsVZero0)
22442 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22443 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22444 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22446 if (!IsSEXT1 && !IsVZero1)
22449 if (IsSEXT0 && IsVZero1) {
22450 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22451 if (CC == ISD::SETEQ)
22452 return DAG.getNOT(DL, LHS.getOperand(0), VT);
22453 return LHS.getOperand(0);
22455 if (IsSEXT1 && IsVZero0) {
22456 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22457 if (CC == ISD::SETEQ)
22458 return DAG.getNOT(DL, RHS.getOperand(0), VT);
22459 return RHS.getOperand(0);
22466 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22467 const X86Subtarget *Subtarget) {
22469 MVT VT = N->getOperand(1)->getSimpleValueType(0);
22470 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22471 "X86insertps is only defined for v4x32");
22473 SDValue Ld = N->getOperand(1);
22474 if (MayFoldLoad(Ld)) {
22475 // Extract the countS bits from the immediate so we can get the proper
22476 // address when narrowing the vector load to a specific element.
22477 // When the second source op is a memory address, interps doesn't use
22478 // countS and just gets an f32 from that address.
22479 unsigned DestIndex =
22480 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22481 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22485 // Create this as a scalar to vector to match the instruction pattern.
22486 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22487 // countS bits are ignored when loading from memory on insertps, which
22488 // means we don't need to explicitly set them to 0.
22489 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22490 LoadScalarToVector, N->getOperand(2));
22493 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22494 // as "sbb reg,reg", since it can be extended without zext and produces
22495 // an all-ones bit which is more useful than 0/1 in some cases.
22496 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22499 return DAG.getNode(ISD::AND, DL, VT,
22500 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22501 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22502 DAG.getConstant(1, VT));
22503 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22504 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22505 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22506 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22509 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22510 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22511 TargetLowering::DAGCombinerInfo &DCI,
22512 const X86Subtarget *Subtarget) {
22514 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22515 SDValue EFLAGS = N->getOperand(1);
22517 if (CC == X86::COND_A) {
22518 // Try to convert COND_A into COND_B in an attempt to facilitate
22519 // materializing "setb reg".
22521 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22522 // cannot take an immediate as its first operand.
22524 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22525 EFLAGS.getValueType().isInteger() &&
22526 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22527 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22528 EFLAGS.getNode()->getVTList(),
22529 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22530 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22531 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22535 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22536 // a zext and produces an all-ones bit which is more useful than 0/1 in some
22538 if (CC == X86::COND_B)
22539 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22543 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22544 if (Flags.getNode()) {
22545 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22546 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22552 // Optimize branch condition evaluation.
22554 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22555 TargetLowering::DAGCombinerInfo &DCI,
22556 const X86Subtarget *Subtarget) {
22558 SDValue Chain = N->getOperand(0);
22559 SDValue Dest = N->getOperand(1);
22560 SDValue EFLAGS = N->getOperand(3);
22561 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22565 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22566 if (Flags.getNode()) {
22567 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22568 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22575 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22576 SelectionDAG &DAG) {
22577 // Take advantage of vector comparisons producing 0 or -1 in each lane to
22578 // optimize away operation when it's from a constant.
22580 // The general transformation is:
22581 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22582 // AND(VECTOR_CMP(x,y), constant2)
22583 // constant2 = UNARYOP(constant)
22585 // Early exit if this isn't a vector operation, the operand of the
22586 // unary operation isn't a bitwise AND, or if the sizes of the operations
22587 // aren't the same.
22588 EVT VT = N->getValueType(0);
22589 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22590 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22591 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22594 // Now check that the other operand of the AND is a constant. We could
22595 // make the transformation for non-constant splats as well, but it's unclear
22596 // that would be a benefit as it would not eliminate any operations, just
22597 // perform one more step in scalar code before moving to the vector unit.
22598 if (BuildVectorSDNode *BV =
22599 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22600 // Bail out if the vector isn't a constant.
22601 if (!BV->isConstant())
22604 // Everything checks out. Build up the new and improved node.
22606 EVT IntVT = BV->getValueType(0);
22607 // Create a new constant of the appropriate type for the transformed
22609 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22610 // The AND node needs bitcasts to/from an integer vector type around it.
22611 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22612 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22613 N->getOperand(0)->getOperand(0), MaskConst);
22614 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22621 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22622 const X86TargetLowering *XTLI) {
22623 // First try to optimize away the conversion entirely when it's
22624 // conditionally from a constant. Vectors only.
22625 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22626 if (Res != SDValue())
22629 // Now move on to more general possibilities.
22630 SDValue Op0 = N->getOperand(0);
22631 EVT InVT = Op0->getValueType(0);
22633 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22634 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22636 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22637 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22638 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22641 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22642 // a 32-bit target where SSE doesn't support i64->FP operations.
22643 if (Op0.getOpcode() == ISD::LOAD) {
22644 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22645 EVT VT = Ld->getValueType(0);
22646 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22647 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22648 !XTLI->getSubtarget()->is64Bit() &&
22650 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22651 Ld->getChain(), Op0, DAG);
22652 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22659 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22660 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22661 X86TargetLowering::DAGCombinerInfo &DCI) {
22662 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22663 // the result is either zero or one (depending on the input carry bit).
22664 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22665 if (X86::isZeroNode(N->getOperand(0)) &&
22666 X86::isZeroNode(N->getOperand(1)) &&
22667 // We don't have a good way to replace an EFLAGS use, so only do this when
22669 SDValue(N, 1).use_empty()) {
22671 EVT VT = N->getValueType(0);
22672 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22673 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22674 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22675 DAG.getConstant(X86::COND_B,MVT::i8),
22677 DAG.getConstant(1, VT));
22678 return DCI.CombineTo(N, Res1, CarryOut);
22684 // fold (add Y, (sete X, 0)) -> adc 0, Y
22685 // (add Y, (setne X, 0)) -> sbb -1, Y
22686 // (sub (sete X, 0), Y) -> sbb 0, Y
22687 // (sub (setne X, 0), Y) -> adc -1, Y
22688 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22691 // Look through ZExts.
22692 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22693 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22696 SDValue SetCC = Ext.getOperand(0);
22697 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22700 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22701 if (CC != X86::COND_E && CC != X86::COND_NE)
22704 SDValue Cmp = SetCC.getOperand(1);
22705 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22706 !X86::isZeroNode(Cmp.getOperand(1)) ||
22707 !Cmp.getOperand(0).getValueType().isInteger())
22710 SDValue CmpOp0 = Cmp.getOperand(0);
22711 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22712 DAG.getConstant(1, CmpOp0.getValueType()));
22714 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22715 if (CC == X86::COND_NE)
22716 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22717 DL, OtherVal.getValueType(), OtherVal,
22718 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22719 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22720 DL, OtherVal.getValueType(), OtherVal,
22721 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22724 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22725 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22726 const X86Subtarget *Subtarget) {
22727 EVT VT = N->getValueType(0);
22728 SDValue Op0 = N->getOperand(0);
22729 SDValue Op1 = N->getOperand(1);
22731 // Try to synthesize horizontal adds from adds of shuffles.
22732 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22733 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22734 isHorizontalBinOp(Op0, Op1, true))
22735 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22737 return OptimizeConditionalInDecrement(N, DAG);
22740 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22741 const X86Subtarget *Subtarget) {
22742 SDValue Op0 = N->getOperand(0);
22743 SDValue Op1 = N->getOperand(1);
22745 // X86 can't encode an immediate LHS of a sub. See if we can push the
22746 // negation into a preceding instruction.
22747 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22748 // If the RHS of the sub is a XOR with one use and a constant, invert the
22749 // immediate. Then add one to the LHS of the sub so we can turn
22750 // X-Y -> X+~Y+1, saving one register.
22751 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22752 isa<ConstantSDNode>(Op1.getOperand(1))) {
22753 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22754 EVT VT = Op0.getValueType();
22755 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22757 DAG.getConstant(~XorC, VT));
22758 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22759 DAG.getConstant(C->getAPIntValue()+1, VT));
22763 // Try to synthesize horizontal adds from adds of shuffles.
22764 EVT VT = N->getValueType(0);
22765 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22766 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22767 isHorizontalBinOp(Op0, Op1, true))
22768 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22770 return OptimizeConditionalInDecrement(N, DAG);
22773 /// performVZEXTCombine - Performs build vector combines
22774 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22775 TargetLowering::DAGCombinerInfo &DCI,
22776 const X86Subtarget *Subtarget) {
22777 // (vzext (bitcast (vzext (x)) -> (vzext x)
22778 SDValue In = N->getOperand(0);
22779 while (In.getOpcode() == ISD::BITCAST)
22780 In = In.getOperand(0);
22782 if (In.getOpcode() != X86ISD::VZEXT)
22785 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22789 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22790 DAGCombinerInfo &DCI) const {
22791 SelectionDAG &DAG = DCI.DAG;
22792 switch (N->getOpcode()) {
22794 case ISD::EXTRACT_VECTOR_ELT:
22795 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22797 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22798 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22799 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
22800 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
22801 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
22802 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
22805 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
22806 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
22807 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
22808 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
22809 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
22810 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
22811 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
22812 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
22813 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
22815 case X86ISD::FOR: return PerformFORCombine(N, DAG);
22817 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
22818 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
22819 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
22820 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
22821 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
22822 case ISD::ANY_EXTEND:
22823 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
22824 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
22825 case ISD::SIGN_EXTEND_INREG:
22826 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22827 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22828 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
22829 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22830 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22831 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
22832 case X86ISD::SHUFP: // Handle all target specific shuffles
22833 case X86ISD::PALIGNR:
22834 case X86ISD::UNPCKH:
22835 case X86ISD::UNPCKL:
22836 case X86ISD::MOVHLPS:
22837 case X86ISD::MOVLHPS:
22838 case X86ISD::PSHUFB:
22839 case X86ISD::PSHUFD:
22840 case X86ISD::PSHUFHW:
22841 case X86ISD::PSHUFLW:
22842 case X86ISD::MOVSS:
22843 case X86ISD::MOVSD:
22844 case X86ISD::VPERMILP:
22845 case X86ISD::VPERM2X128:
22846 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22847 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
22848 case ISD::INTRINSIC_WO_CHAIN:
22849 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22850 case X86ISD::INSERTPS:
22851 return PerformINSERTPSCombine(N, DAG, Subtarget);
22852 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22858 /// isTypeDesirableForOp - Return true if the target has native support for
22859 /// the specified value type and it is 'desirable' to use the type for the
22860 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22861 /// instruction encodings are longer and some i16 instructions are slow.
22862 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22863 if (!isTypeLegal(VT))
22865 if (VT != MVT::i16)
22872 case ISD::SIGN_EXTEND:
22873 case ISD::ZERO_EXTEND:
22874 case ISD::ANY_EXTEND:
22887 /// IsDesirableToPromoteOp - This method query the target whether it is
22888 /// beneficial for dag combiner to promote the specified node. If true, it
22889 /// should return the desired promotion type by reference.
22890 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22891 EVT VT = Op.getValueType();
22892 if (VT != MVT::i16)
22895 bool Promote = false;
22896 bool Commute = false;
22897 switch (Op.getOpcode()) {
22900 LoadSDNode *LD = cast<LoadSDNode>(Op);
22901 // If the non-extending load has a single use and it's not live out, then it
22902 // might be folded.
22903 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22904 Op.hasOneUse()*/) {
22905 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22906 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22907 // The only case where we'd want to promote LOAD (rather then it being
22908 // promoted as an operand is when it's only use is liveout.
22909 if (UI->getOpcode() != ISD::CopyToReg)
22916 case ISD::SIGN_EXTEND:
22917 case ISD::ZERO_EXTEND:
22918 case ISD::ANY_EXTEND:
22923 SDValue N0 = Op.getOperand(0);
22924 // Look out for (store (shl (load), x)).
22925 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22938 SDValue N0 = Op.getOperand(0);
22939 SDValue N1 = Op.getOperand(1);
22940 if (!Commute && MayFoldLoad(N1))
22942 // Avoid disabling potential load folding opportunities.
22943 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22945 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22955 //===----------------------------------------------------------------------===//
22956 // X86 Inline Assembly Support
22957 //===----------------------------------------------------------------------===//
22960 // Helper to match a string separated by whitespace.
22961 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22962 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22964 for (unsigned i = 0, e = args.size(); i != e; ++i) {
22965 StringRef piece(*args[i]);
22966 if (!s.startswith(piece)) // Check if the piece matches.
22969 s = s.substr(piece.size());
22970 StringRef::size_type pos = s.find_first_not_of(" \t");
22971 if (pos == 0) // We matched a prefix.
22979 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22982 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22984 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22985 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22986 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22987 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22989 if (AsmPieces.size() == 3)
22991 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22998 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22999 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23001 std::string AsmStr = IA->getAsmString();
23003 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23004 if (!Ty || Ty->getBitWidth() % 16 != 0)
23007 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23008 SmallVector<StringRef, 4> AsmPieces;
23009 SplitString(AsmStr, AsmPieces, ";\n");
23011 switch (AsmPieces.size()) {
23012 default: return false;
23014 // FIXME: this should verify that we are targeting a 486 or better. If not,
23015 // we will turn this bswap into something that will be lowered to logical
23016 // ops instead of emitting the bswap asm. For now, we don't support 486 or
23017 // lower so don't worry about this.
23019 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
23020 matchAsm(AsmPieces[0], "bswapl", "$0") ||
23021 matchAsm(AsmPieces[0], "bswapq", "$0") ||
23022 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
23023 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
23024 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
23025 // No need to check constraints, nothing other than the equivalent of
23026 // "=r,0" would be valid here.
23027 return IntrinsicLowering::LowerToByteSwap(CI);
23030 // rorw $$8, ${0:w} --> llvm.bswap.i16
23031 if (CI->getType()->isIntegerTy(16) &&
23032 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23033 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
23034 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
23036 const std::string &ConstraintsStr = IA->getConstraintString();
23037 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23038 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23039 if (clobbersFlagRegisters(AsmPieces))
23040 return IntrinsicLowering::LowerToByteSwap(CI);
23044 if (CI->getType()->isIntegerTy(32) &&
23045 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23046 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
23047 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
23048 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
23050 const std::string &ConstraintsStr = IA->getConstraintString();
23051 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23052 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23053 if (clobbersFlagRegisters(AsmPieces))
23054 return IntrinsicLowering::LowerToByteSwap(CI);
23057 if (CI->getType()->isIntegerTy(64)) {
23058 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23059 if (Constraints.size() >= 2 &&
23060 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23061 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23062 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
23063 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
23064 matchAsm(AsmPieces[1], "bswap", "%edx") &&
23065 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
23066 return IntrinsicLowering::LowerToByteSwap(CI);
23074 /// getConstraintType - Given a constraint letter, return the type of
23075 /// constraint it is for this target.
23076 X86TargetLowering::ConstraintType
23077 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23078 if (Constraint.size() == 1) {
23079 switch (Constraint[0]) {
23090 return C_RegisterClass;
23114 return TargetLowering::getConstraintType(Constraint);
23117 /// Examine constraint type and operand type and determine a weight value.
23118 /// This object must already have been set up with the operand type
23119 /// and the current alternative constraint selected.
23120 TargetLowering::ConstraintWeight
23121 X86TargetLowering::getSingleConstraintMatchWeight(
23122 AsmOperandInfo &info, const char *constraint) const {
23123 ConstraintWeight weight = CW_Invalid;
23124 Value *CallOperandVal = info.CallOperandVal;
23125 // If we don't have a value, we can't do a match,
23126 // but allow it at the lowest weight.
23127 if (!CallOperandVal)
23129 Type *type = CallOperandVal->getType();
23130 // Look at the constraint type.
23131 switch (*constraint) {
23133 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23144 if (CallOperandVal->getType()->isIntegerTy())
23145 weight = CW_SpecificReg;
23150 if (type->isFloatingPointTy())
23151 weight = CW_SpecificReg;
23154 if (type->isX86_MMXTy() && Subtarget->hasMMX())
23155 weight = CW_SpecificReg;
23159 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23160 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23161 weight = CW_Register;
23164 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23165 if (C->getZExtValue() <= 31)
23166 weight = CW_Constant;
23170 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23171 if (C->getZExtValue() <= 63)
23172 weight = CW_Constant;
23176 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23177 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23178 weight = CW_Constant;
23182 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23183 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23184 weight = CW_Constant;
23188 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23189 if (C->getZExtValue() <= 3)
23190 weight = CW_Constant;
23194 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23195 if (C->getZExtValue() <= 0xff)
23196 weight = CW_Constant;
23201 if (dyn_cast<ConstantFP>(CallOperandVal)) {
23202 weight = CW_Constant;
23206 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23207 if ((C->getSExtValue() >= -0x80000000LL) &&
23208 (C->getSExtValue() <= 0x7fffffffLL))
23209 weight = CW_Constant;
23213 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23214 if (C->getZExtValue() <= 0xffffffff)
23215 weight = CW_Constant;
23222 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23223 /// with another that has more specific requirements based on the type of the
23224 /// corresponding operand.
23225 const char *X86TargetLowering::
23226 LowerXConstraint(EVT ConstraintVT) const {
23227 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23228 // 'f' like normal targets.
23229 if (ConstraintVT.isFloatingPoint()) {
23230 if (Subtarget->hasSSE2())
23232 if (Subtarget->hasSSE1())
23236 return TargetLowering::LowerXConstraint(ConstraintVT);
23239 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23240 /// vector. If it is invalid, don't add anything to Ops.
23241 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23242 std::string &Constraint,
23243 std::vector<SDValue>&Ops,
23244 SelectionDAG &DAG) const {
23247 // Only support length 1 constraints for now.
23248 if (Constraint.length() > 1) return;
23250 char ConstraintLetter = Constraint[0];
23251 switch (ConstraintLetter) {
23254 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23255 if (C->getZExtValue() <= 31) {
23256 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23262 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23263 if (C->getZExtValue() <= 63) {
23264 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23270 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23271 if (isInt<8>(C->getSExtValue())) {
23272 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23278 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23279 if (C->getZExtValue() <= 255) {
23280 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23286 // 32-bit signed value
23287 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23288 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23289 C->getSExtValue())) {
23290 // Widen to 64 bits here to get it sign extended.
23291 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23294 // FIXME gcc accepts some relocatable values here too, but only in certain
23295 // memory models; it's complicated.
23300 // 32-bit unsigned value
23301 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23302 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23303 C->getZExtValue())) {
23304 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23308 // FIXME gcc accepts some relocatable values here too, but only in certain
23309 // memory models; it's complicated.
23313 // Literal immediates are always ok.
23314 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23315 // Widen to 64 bits here to get it sign extended.
23316 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23320 // In any sort of PIC mode addresses need to be computed at runtime by
23321 // adding in a register or some sort of table lookup. These can't
23322 // be used as immediates.
23323 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23326 // If we are in non-pic codegen mode, we allow the address of a global (with
23327 // an optional displacement) to be used with 'i'.
23328 GlobalAddressSDNode *GA = nullptr;
23329 int64_t Offset = 0;
23331 // Match either (GA), (GA+C), (GA+C1+C2), etc.
23333 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23334 Offset += GA->getOffset();
23336 } else if (Op.getOpcode() == ISD::ADD) {
23337 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23338 Offset += C->getZExtValue();
23339 Op = Op.getOperand(0);
23342 } else if (Op.getOpcode() == ISD::SUB) {
23343 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23344 Offset += -C->getZExtValue();
23345 Op = Op.getOperand(0);
23350 // Otherwise, this isn't something we can handle, reject it.
23354 const GlobalValue *GV = GA->getGlobal();
23355 // If we require an extra load to get this address, as in PIC mode, we
23356 // can't accept it.
23357 if (isGlobalStubReference(
23358 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23361 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23362 GA->getValueType(0), Offset);
23367 if (Result.getNode()) {
23368 Ops.push_back(Result);
23371 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23374 std::pair<unsigned, const TargetRegisterClass*>
23375 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23377 // First, see if this is a constraint that directly corresponds to an LLVM
23379 if (Constraint.size() == 1) {
23380 // GCC Constraint Letters
23381 switch (Constraint[0]) {
23383 // TODO: Slight differences here in allocation order and leaving
23384 // RIP in the class. Do they matter any more here than they do
23385 // in the normal allocation?
23386 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23387 if (Subtarget->is64Bit()) {
23388 if (VT == MVT::i32 || VT == MVT::f32)
23389 return std::make_pair(0U, &X86::GR32RegClass);
23390 if (VT == MVT::i16)
23391 return std::make_pair(0U, &X86::GR16RegClass);
23392 if (VT == MVT::i8 || VT == MVT::i1)
23393 return std::make_pair(0U, &X86::GR8RegClass);
23394 if (VT == MVT::i64 || VT == MVT::f64)
23395 return std::make_pair(0U, &X86::GR64RegClass);
23398 // 32-bit fallthrough
23399 case 'Q': // Q_REGS
23400 if (VT == MVT::i32 || VT == MVT::f32)
23401 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23402 if (VT == MVT::i16)
23403 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23404 if (VT == MVT::i8 || VT == MVT::i1)
23405 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23406 if (VT == MVT::i64)
23407 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23409 case 'r': // GENERAL_REGS
23410 case 'l': // INDEX_REGS
23411 if (VT == MVT::i8 || VT == MVT::i1)
23412 return std::make_pair(0U, &X86::GR8RegClass);
23413 if (VT == MVT::i16)
23414 return std::make_pair(0U, &X86::GR16RegClass);
23415 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23416 return std::make_pair(0U, &X86::GR32RegClass);
23417 return std::make_pair(0U, &X86::GR64RegClass);
23418 case 'R': // LEGACY_REGS
23419 if (VT == MVT::i8 || VT == MVT::i1)
23420 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23421 if (VT == MVT::i16)
23422 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23423 if (VT == MVT::i32 || !Subtarget->is64Bit())
23424 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23425 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23426 case 'f': // FP Stack registers.
23427 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23428 // value to the correct fpstack register class.
23429 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23430 return std::make_pair(0U, &X86::RFP32RegClass);
23431 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23432 return std::make_pair(0U, &X86::RFP64RegClass);
23433 return std::make_pair(0U, &X86::RFP80RegClass);
23434 case 'y': // MMX_REGS if MMX allowed.
23435 if (!Subtarget->hasMMX()) break;
23436 return std::make_pair(0U, &X86::VR64RegClass);
23437 case 'Y': // SSE_REGS if SSE2 allowed
23438 if (!Subtarget->hasSSE2()) break;
23440 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23441 if (!Subtarget->hasSSE1()) break;
23443 switch (VT.SimpleTy) {
23445 // Scalar SSE types.
23448 return std::make_pair(0U, &X86::FR32RegClass);
23451 return std::make_pair(0U, &X86::FR64RegClass);
23459 return std::make_pair(0U, &X86::VR128RegClass);
23467 return std::make_pair(0U, &X86::VR256RegClass);
23472 return std::make_pair(0U, &X86::VR512RegClass);
23478 // Use the default implementation in TargetLowering to convert the register
23479 // constraint into a member of a register class.
23480 std::pair<unsigned, const TargetRegisterClass*> Res;
23481 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23483 // Not found as a standard register?
23485 // Map st(0) -> st(7) -> ST0
23486 if (Constraint.size() == 7 && Constraint[0] == '{' &&
23487 tolower(Constraint[1]) == 's' &&
23488 tolower(Constraint[2]) == 't' &&
23489 Constraint[3] == '(' &&
23490 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23491 Constraint[5] == ')' &&
23492 Constraint[6] == '}') {
23494 Res.first = X86::FP0+Constraint[4]-'0';
23495 Res.second = &X86::RFP80RegClass;
23499 // GCC allows "st(0)" to be called just plain "st".
23500 if (StringRef("{st}").equals_lower(Constraint)) {
23501 Res.first = X86::FP0;
23502 Res.second = &X86::RFP80RegClass;
23507 if (StringRef("{flags}").equals_lower(Constraint)) {
23508 Res.first = X86::EFLAGS;
23509 Res.second = &X86::CCRRegClass;
23513 // 'A' means EAX + EDX.
23514 if (Constraint == "A") {
23515 Res.first = X86::EAX;
23516 Res.second = &X86::GR32_ADRegClass;
23522 // Otherwise, check to see if this is a register class of the wrong value
23523 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23524 // turn into {ax},{dx}.
23525 if (Res.second->hasType(VT))
23526 return Res; // Correct type already, nothing to do.
23528 // All of the single-register GCC register classes map their values onto
23529 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
23530 // really want an 8-bit or 32-bit register, map to the appropriate register
23531 // class and return the appropriate register.
23532 if (Res.second == &X86::GR16RegClass) {
23533 if (VT == MVT::i8 || VT == MVT::i1) {
23534 unsigned DestReg = 0;
23535 switch (Res.first) {
23537 case X86::AX: DestReg = X86::AL; break;
23538 case X86::DX: DestReg = X86::DL; break;
23539 case X86::CX: DestReg = X86::CL; break;
23540 case X86::BX: DestReg = X86::BL; break;
23543 Res.first = DestReg;
23544 Res.second = &X86::GR8RegClass;
23546 } else if (VT == MVT::i32 || VT == MVT::f32) {
23547 unsigned DestReg = 0;
23548 switch (Res.first) {
23550 case X86::AX: DestReg = X86::EAX; break;
23551 case X86::DX: DestReg = X86::EDX; break;
23552 case X86::CX: DestReg = X86::ECX; break;
23553 case X86::BX: DestReg = X86::EBX; break;
23554 case X86::SI: DestReg = X86::ESI; break;
23555 case X86::DI: DestReg = X86::EDI; break;
23556 case X86::BP: DestReg = X86::EBP; break;
23557 case X86::SP: DestReg = X86::ESP; break;
23560 Res.first = DestReg;
23561 Res.second = &X86::GR32RegClass;
23563 } else if (VT == MVT::i64 || VT == MVT::f64) {
23564 unsigned DestReg = 0;
23565 switch (Res.first) {
23567 case X86::AX: DestReg = X86::RAX; break;
23568 case X86::DX: DestReg = X86::RDX; break;
23569 case X86::CX: DestReg = X86::RCX; break;
23570 case X86::BX: DestReg = X86::RBX; break;
23571 case X86::SI: DestReg = X86::RSI; break;
23572 case X86::DI: DestReg = X86::RDI; break;
23573 case X86::BP: DestReg = X86::RBP; break;
23574 case X86::SP: DestReg = X86::RSP; break;
23577 Res.first = DestReg;
23578 Res.second = &X86::GR64RegClass;
23581 } else if (Res.second == &X86::FR32RegClass ||
23582 Res.second == &X86::FR64RegClass ||
23583 Res.second == &X86::VR128RegClass ||
23584 Res.second == &X86::VR256RegClass ||
23585 Res.second == &X86::FR32XRegClass ||
23586 Res.second == &X86::FR64XRegClass ||
23587 Res.second == &X86::VR128XRegClass ||
23588 Res.second == &X86::VR256XRegClass ||
23589 Res.second == &X86::VR512RegClass) {
23590 // Handle references to XMM physical registers that got mapped into the
23591 // wrong class. This can happen with constraints like {xmm0} where the
23592 // target independent register mapper will just pick the first match it can
23593 // find, ignoring the required type.
23595 if (VT == MVT::f32 || VT == MVT::i32)
23596 Res.second = &X86::FR32RegClass;
23597 else if (VT == MVT::f64 || VT == MVT::i64)
23598 Res.second = &X86::FR64RegClass;
23599 else if (X86::VR128RegClass.hasType(VT))
23600 Res.second = &X86::VR128RegClass;
23601 else if (X86::VR256RegClass.hasType(VT))
23602 Res.second = &X86::VR256RegClass;
23603 else if (X86::VR512RegClass.hasType(VT))
23604 Res.second = &X86::VR512RegClass;
23610 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23612 // Scaling factors are not free at all.
23613 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23614 // will take 2 allocations in the out of order engine instead of 1
23615 // for plain addressing mode, i.e. inst (reg1).
23617 // vaddps (%rsi,%drx), %ymm0, %ymm1
23618 // Requires two allocations (one for the load, one for the computation)
23620 // vaddps (%rsi), %ymm0, %ymm1
23621 // Requires just 1 allocation, i.e., freeing allocations for other operations
23622 // and having less micro operations to execute.
23624 // For some X86 architectures, this is even worse because for instance for
23625 // stores, the complex addressing mode forces the instruction to use the
23626 // "load" ports instead of the dedicated "store" port.
23627 // E.g., on Haswell:
23628 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23629 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
23630 if (isLegalAddressingMode(AM, Ty))
23631 // Scale represents reg2 * scale, thus account for 1
23632 // as soon as we use a second register.
23633 return AM.Scale != 0;
23637 bool X86TargetLowering::isTargetFTOL() const {
23638 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();