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 means XMM
960 // registers cannot be used even for integer operations.
961 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
966 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
967 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
968 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
969 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
970 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
971 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
972 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
973 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
974 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
975 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
976 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
977 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
978 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
979 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
980 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
981 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
982 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
983 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
984 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
985 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
986 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
987 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
989 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
990 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
991 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
992 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
994 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
995 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
996 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
997 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
998 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1000 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002 MVT VT = (MVT::SimpleValueType)i;
1003 // Do not attempt to custom lower non-power-of-2 vectors
1004 if (!isPowerOf2_32(VT.getVectorNumElements()))
1006 // Do not attempt to custom lower non-128-bit vectors
1007 if (!VT.is128BitVector())
1009 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1010 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1011 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1014 // 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 if (Subtarget->is64Bit()) {
1020 setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1021 setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1023 setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1024 setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1025 setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1026 setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1027 setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1028 setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1030 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1031 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1032 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1033 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1034 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1035 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1037 if (Subtarget->is64Bit()) {
1038 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1039 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1042 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1043 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1044 MVT VT = (MVT::SimpleValueType)i;
1046 // Do not attempt to promote non-128-bit vectors
1047 if (!VT.is128BitVector())
1050 setOperationAction(ISD::AND, VT, Promote);
1051 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1052 setOperationAction(ISD::OR, VT, Promote);
1053 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1054 setOperationAction(ISD::XOR, VT, Promote);
1055 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1056 setOperationAction(ISD::LOAD, VT, Promote);
1057 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1058 setOperationAction(ISD::SELECT, VT, Promote);
1059 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1062 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1064 // Custom lower v2i64 and v2f64 selects.
1065 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1066 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1067 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1068 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1070 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1071 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1073 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1074 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1075 // As there is no 64-bit GPR available, we need build a special custom
1076 // sequence to convert from v2i32 to v2f32.
1077 if (!Subtarget->is64Bit())
1078 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1080 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1081 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1083 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1085 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1086 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1087 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1090 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1091 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1092 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1093 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1094 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1095 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1096 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1097 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1098 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1099 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1100 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1102 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1103 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1104 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1105 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1106 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1107 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1108 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1109 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1110 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1111 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1113 // FIXME: Do we need to handle scalar-to-vector here?
1114 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1116 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1117 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1118 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1119 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1120 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1121 // There is no BLENDI for byte vectors. We don't need to custom lower
1122 // some vselects for now.
1123 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1125 // SSE41 brings specific instructions for doing vector sign extend even in
1126 // cases where we don't have SRA.
1127 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1128 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1129 setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1131 // i8 and i16 vectors are custom because the source register and source
1132 // source memory operand types are not the same width. f32 vectors are
1133 // custom since the immediate controlling the insert encodes additional
1135 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1136 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1137 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1138 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1140 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1141 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1142 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1143 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1145 // FIXME: these should be Legal, but that's only for the case where
1146 // the index is constant. For now custom expand to deal with that.
1147 if (Subtarget->is64Bit()) {
1148 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1149 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1153 if (Subtarget->hasSSE2()) {
1154 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1155 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1157 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1158 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1160 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1161 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1163 // In the customized shift lowering, the legal cases in AVX2 will be
1165 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1166 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1168 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1169 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1171 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1174 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1175 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1176 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1177 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1178 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1179 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1180 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1182 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1183 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1184 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1186 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1187 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1188 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1189 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1190 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1191 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1192 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1193 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1194 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1195 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1196 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1197 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1199 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1200 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1201 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1202 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1203 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1204 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1205 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1206 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1207 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1208 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1209 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1210 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1212 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1213 // even though v8i16 is a legal type.
1214 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1215 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1216 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1218 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1219 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1220 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1222 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1223 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1225 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1227 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1228 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1230 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1231 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1233 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1234 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1236 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1237 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1238 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1239 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1241 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1242 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1243 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1245 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1246 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1247 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1248 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1250 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1251 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1252 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1253 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1254 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1255 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1256 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1257 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1258 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1259 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1260 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1261 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1263 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1264 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1265 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1266 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1267 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1268 setOperationAction(ISD::FMA, MVT::f32, Legal);
1269 setOperationAction(ISD::FMA, MVT::f64, Legal);
1272 if (Subtarget->hasInt256()) {
1273 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1274 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1275 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1276 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1278 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1279 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1280 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1281 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1283 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1284 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1285 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1286 // Don't lower v32i8 because there is no 128-bit byte mul
1288 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1289 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1290 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1291 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1293 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1294 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1296 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1297 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1298 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1299 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1301 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1302 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1303 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1304 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1306 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1307 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1308 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1309 // Don't lower v32i8 because there is no 128-bit byte mul
1312 // In the customized shift lowering, the legal cases in AVX2 will be
1314 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1315 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1317 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1318 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1320 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1322 // Custom lower several nodes for 256-bit types.
1323 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1324 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1325 MVT VT = (MVT::SimpleValueType)i;
1327 // Extract subvector is special because the value type
1328 // (result) is 128-bit but the source is 256-bit wide.
1329 if (VT.is128BitVector())
1330 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1332 // Do not attempt to custom lower other non-256-bit vectors
1333 if (!VT.is256BitVector())
1336 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1337 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1338 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1339 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1340 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1341 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1342 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1345 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1346 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1347 MVT VT = (MVT::SimpleValueType)i;
1349 // Do not attempt to promote non-256-bit vectors
1350 if (!VT.is256BitVector())
1353 setOperationAction(ISD::AND, VT, Promote);
1354 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1355 setOperationAction(ISD::OR, VT, Promote);
1356 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1357 setOperationAction(ISD::XOR, VT, Promote);
1358 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1359 setOperationAction(ISD::LOAD, VT, Promote);
1360 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1361 setOperationAction(ISD::SELECT, VT, Promote);
1362 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1366 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1367 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1368 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1369 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1370 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1372 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1373 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1374 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1376 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1377 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1378 setOperationAction(ISD::XOR, MVT::i1, Legal);
1379 setOperationAction(ISD::OR, MVT::i1, Legal);
1380 setOperationAction(ISD::AND, MVT::i1, Legal);
1381 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1382 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1383 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1384 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1385 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1386 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1388 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1389 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1390 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1391 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1392 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1393 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1395 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1396 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1397 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1398 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1399 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1400 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1401 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1402 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1404 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1405 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1406 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1407 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1408 if (Subtarget->is64Bit()) {
1409 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1410 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1411 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1412 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1414 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1415 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1416 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1417 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1418 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1419 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1420 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1421 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1422 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1423 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1425 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1426 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1427 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1428 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1429 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1430 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1431 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1432 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1433 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1434 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1435 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1436 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1437 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1439 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1440 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1441 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1442 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1443 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1444 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1446 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1447 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1449 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1451 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1452 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1454 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1455 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1456 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1457 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1458 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1459 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1461 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1462 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1464 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1465 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1467 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1469 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1470 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1472 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1473 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1475 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1476 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1478 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1479 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1480 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1481 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1482 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1483 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1485 if (Subtarget->hasCDI()) {
1486 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1487 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1490 // Custom lower several nodes.
1491 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1492 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1493 MVT VT = (MVT::SimpleValueType)i;
1495 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1496 // Extract subvector is special because the value type
1497 // (result) is 256/128-bit but the source is 512-bit wide.
1498 if (VT.is128BitVector() || VT.is256BitVector())
1499 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1501 if (VT.getVectorElementType() == MVT::i1)
1502 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1504 // Do not attempt to custom lower other non-512-bit vectors
1505 if (!VT.is512BitVector())
1508 if ( EltSize >= 32) {
1509 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1510 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1511 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1512 setOperationAction(ISD::VSELECT, VT, Legal);
1513 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1514 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1515 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1518 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1519 MVT VT = (MVT::SimpleValueType)i;
1521 // Do not attempt to promote non-256-bit vectors
1522 if (!VT.is512BitVector())
1525 setOperationAction(ISD::SELECT, VT, Promote);
1526 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1530 if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1531 addRegisterClass(MVT::v32i1, &X86::VK32RegClass);
1532 addRegisterClass(MVT::v64i1, &X86::VK64RegClass);
1535 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1536 // of this type with custom code.
1537 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1538 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1539 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1543 // We want to custom lower some of our intrinsics.
1544 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1545 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1546 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1547 if (!Subtarget->is64Bit())
1548 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1550 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1551 // handle type legalization for these operations here.
1553 // FIXME: We really should do custom legalization for addition and
1554 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1555 // than generic legalization for 64-bit multiplication-with-overflow, though.
1556 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1557 // Add/Sub/Mul with overflow operations are custom lowered.
1559 setOperationAction(ISD::SADDO, VT, Custom);
1560 setOperationAction(ISD::UADDO, VT, Custom);
1561 setOperationAction(ISD::SSUBO, VT, Custom);
1562 setOperationAction(ISD::USUBO, VT, Custom);
1563 setOperationAction(ISD::SMULO, VT, Custom);
1564 setOperationAction(ISD::UMULO, VT, Custom);
1567 // There are no 8-bit 3-address imul/mul instructions
1568 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1569 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1571 if (!Subtarget->is64Bit()) {
1572 // These libcalls are not available in 32-bit.
1573 setLibcallName(RTLIB::SHL_I128, nullptr);
1574 setLibcallName(RTLIB::SRL_I128, nullptr);
1575 setLibcallName(RTLIB::SRA_I128, nullptr);
1578 // Combine sin / cos into one node or libcall if possible.
1579 if (Subtarget->hasSinCos()) {
1580 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1581 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1582 if (Subtarget->isTargetDarwin()) {
1583 // For MacOSX, we don't want to the normal expansion of a libcall to
1584 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1586 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1587 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1591 if (Subtarget->isTargetWin64()) {
1592 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1593 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1594 setOperationAction(ISD::SREM, MVT::i128, Custom);
1595 setOperationAction(ISD::UREM, MVT::i128, Custom);
1596 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1597 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1600 // We have target-specific dag combine patterns for the following nodes:
1601 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1602 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1603 setTargetDAGCombine(ISD::VSELECT);
1604 setTargetDAGCombine(ISD::SELECT);
1605 setTargetDAGCombine(ISD::SHL);
1606 setTargetDAGCombine(ISD::SRA);
1607 setTargetDAGCombine(ISD::SRL);
1608 setTargetDAGCombine(ISD::OR);
1609 setTargetDAGCombine(ISD::AND);
1610 setTargetDAGCombine(ISD::ADD);
1611 setTargetDAGCombine(ISD::FADD);
1612 setTargetDAGCombine(ISD::FSUB);
1613 setTargetDAGCombine(ISD::FMA);
1614 setTargetDAGCombine(ISD::SUB);
1615 setTargetDAGCombine(ISD::LOAD);
1616 setTargetDAGCombine(ISD::STORE);
1617 setTargetDAGCombine(ISD::ZERO_EXTEND);
1618 setTargetDAGCombine(ISD::ANY_EXTEND);
1619 setTargetDAGCombine(ISD::SIGN_EXTEND);
1620 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1621 setTargetDAGCombine(ISD::TRUNCATE);
1622 setTargetDAGCombine(ISD::SINT_TO_FP);
1623 setTargetDAGCombine(ISD::SETCC);
1624 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1625 setTargetDAGCombine(ISD::BUILD_VECTOR);
1626 if (Subtarget->is64Bit())
1627 setTargetDAGCombine(ISD::MUL);
1628 setTargetDAGCombine(ISD::XOR);
1630 computeRegisterProperties();
1632 // On Darwin, -Os means optimize for size without hurting performance,
1633 // do not reduce the limit.
1634 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1635 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1636 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1637 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1638 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1639 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1640 setPrefLoopAlignment(4); // 2^4 bytes.
1642 // Predictable cmov don't hurt on atom because it's in-order.
1643 PredictableSelectIsExpensive = !Subtarget->isAtom();
1645 setPrefFunctionAlignment(4); // 2^4 bytes.
1648 // This has so far only been implemented for 64-bit MachO.
1649 bool X86TargetLowering::useLoadStackGuardNode() const {
1650 return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1651 Subtarget->is64Bit();
1654 TargetLoweringBase::LegalizeTypeAction
1655 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1656 if (ExperimentalVectorWideningLegalization &&
1657 VT.getVectorNumElements() != 1 &&
1658 VT.getVectorElementType().getSimpleVT() != MVT::i1)
1659 return TypeWidenVector;
1661 return TargetLoweringBase::getPreferredVectorAction(VT);
1664 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1666 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1668 if (Subtarget->hasAVX512())
1669 switch(VT.getVectorNumElements()) {
1670 case 8: return MVT::v8i1;
1671 case 16: return MVT::v16i1;
1674 return VT.changeVectorElementTypeToInteger();
1677 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1678 /// the desired ByVal argument alignment.
1679 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1682 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1683 if (VTy->getBitWidth() == 128)
1685 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1686 unsigned EltAlign = 0;
1687 getMaxByValAlign(ATy->getElementType(), EltAlign);
1688 if (EltAlign > MaxAlign)
1689 MaxAlign = EltAlign;
1690 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1691 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1692 unsigned EltAlign = 0;
1693 getMaxByValAlign(STy->getElementType(i), EltAlign);
1694 if (EltAlign > MaxAlign)
1695 MaxAlign = EltAlign;
1702 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1703 /// function arguments in the caller parameter area. For X86, aggregates
1704 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1705 /// are at 4-byte boundaries.
1706 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1707 if (Subtarget->is64Bit()) {
1708 // Max of 8 and alignment of type.
1709 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1716 if (Subtarget->hasSSE1())
1717 getMaxByValAlign(Ty, Align);
1721 /// getOptimalMemOpType - Returns the target specific optimal type for load
1722 /// and store operations as a result of memset, memcpy, and memmove
1723 /// lowering. If DstAlign is zero that means it's safe to destination
1724 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1725 /// means there isn't a need to check it against alignment requirement,
1726 /// probably because the source does not need to be loaded. If 'IsMemset' is
1727 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1728 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1729 /// source is constant so it does not need to be loaded.
1730 /// It returns EVT::Other if the type should be determined using generic
1731 /// target-independent logic.
1733 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1734 unsigned DstAlign, unsigned SrcAlign,
1735 bool IsMemset, bool ZeroMemset,
1737 MachineFunction &MF) const {
1738 const Function *F = MF.getFunction();
1739 if ((!IsMemset || ZeroMemset) &&
1740 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1741 Attribute::NoImplicitFloat)) {
1743 (Subtarget->isUnalignedMemAccessFast() ||
1744 ((DstAlign == 0 || DstAlign >= 16) &&
1745 (SrcAlign == 0 || SrcAlign >= 16)))) {
1747 if (Subtarget->hasInt256())
1749 if (Subtarget->hasFp256())
1752 if (Subtarget->hasSSE2())
1754 if (Subtarget->hasSSE1())
1756 } else if (!MemcpyStrSrc && Size >= 8 &&
1757 !Subtarget->is64Bit() &&
1758 Subtarget->hasSSE2()) {
1759 // Do not use f64 to lower memcpy if source is string constant. It's
1760 // better to use i32 to avoid the loads.
1764 if (Subtarget->is64Bit() && Size >= 8)
1769 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1771 return X86ScalarSSEf32;
1772 else if (VT == MVT::f64)
1773 return X86ScalarSSEf64;
1778 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1783 *Fast = Subtarget->isUnalignedMemAccessFast();
1787 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1788 /// current function. The returned value is a member of the
1789 /// MachineJumpTableInfo::JTEntryKind enum.
1790 unsigned X86TargetLowering::getJumpTableEncoding() const {
1791 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1793 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1794 Subtarget->isPICStyleGOT())
1795 return MachineJumpTableInfo::EK_Custom32;
1797 // Otherwise, use the normal jump table encoding heuristics.
1798 return TargetLowering::getJumpTableEncoding();
1802 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1803 const MachineBasicBlock *MBB,
1804 unsigned uid,MCContext &Ctx) const{
1805 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1806 Subtarget->isPICStyleGOT());
1807 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1809 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1810 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1813 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1815 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1816 SelectionDAG &DAG) const {
1817 if (!Subtarget->is64Bit())
1818 // This doesn't have SDLoc associated with it, but is not really the
1819 // same as a Register.
1820 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1824 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1825 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1827 const MCExpr *X86TargetLowering::
1828 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1829 MCContext &Ctx) const {
1830 // X86-64 uses RIP relative addressing based on the jump table label.
1831 if (Subtarget->isPICStyleRIPRel())
1832 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1834 // Otherwise, the reference is relative to the PIC base.
1835 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1838 // FIXME: Why this routine is here? Move to RegInfo!
1839 std::pair<const TargetRegisterClass*, uint8_t>
1840 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1841 const TargetRegisterClass *RRC = nullptr;
1843 switch (VT.SimpleTy) {
1845 return TargetLowering::findRepresentativeClass(VT);
1846 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1847 RRC = Subtarget->is64Bit() ?
1848 (const TargetRegisterClass*)&X86::GR64RegClass :
1849 (const TargetRegisterClass*)&X86::GR32RegClass;
1852 RRC = &X86::VR64RegClass;
1854 case MVT::f32: case MVT::f64:
1855 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1856 case MVT::v4f32: case MVT::v2f64:
1857 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1859 RRC = &X86::VR128RegClass;
1862 return std::make_pair(RRC, Cost);
1865 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1866 unsigned &Offset) const {
1867 if (!Subtarget->isTargetLinux())
1870 if (Subtarget->is64Bit()) {
1871 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1873 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1885 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1886 unsigned DestAS) const {
1887 assert(SrcAS != DestAS && "Expected different address spaces!");
1889 return SrcAS < 256 && DestAS < 256;
1892 //===----------------------------------------------------------------------===//
1893 // Return Value Calling Convention Implementation
1894 //===----------------------------------------------------------------------===//
1896 #include "X86GenCallingConv.inc"
1899 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1900 MachineFunction &MF, bool isVarArg,
1901 const SmallVectorImpl<ISD::OutputArg> &Outs,
1902 LLVMContext &Context) const {
1903 SmallVector<CCValAssign, 16> RVLocs;
1904 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1905 return CCInfo.CheckReturn(Outs, RetCC_X86);
1908 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1909 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1914 X86TargetLowering::LowerReturn(SDValue Chain,
1915 CallingConv::ID CallConv, bool isVarArg,
1916 const SmallVectorImpl<ISD::OutputArg> &Outs,
1917 const SmallVectorImpl<SDValue> &OutVals,
1918 SDLoc dl, SelectionDAG &DAG) const {
1919 MachineFunction &MF = DAG.getMachineFunction();
1920 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1922 SmallVector<CCValAssign, 16> RVLocs;
1923 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1924 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1927 SmallVector<SDValue, 6> RetOps;
1928 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1929 // Operand #1 = Bytes To Pop
1930 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1933 // Copy the result values into the output registers.
1934 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1935 CCValAssign &VA = RVLocs[i];
1936 assert(VA.isRegLoc() && "Can only return in registers!");
1937 SDValue ValToCopy = OutVals[i];
1938 EVT ValVT = ValToCopy.getValueType();
1940 // Promote values to the appropriate types
1941 if (VA.getLocInfo() == CCValAssign::SExt)
1942 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1943 else if (VA.getLocInfo() == CCValAssign::ZExt)
1944 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1945 else if (VA.getLocInfo() == CCValAssign::AExt)
1946 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1947 else if (VA.getLocInfo() == CCValAssign::BCvt)
1948 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1950 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1951 "Unexpected FP-extend for return value.");
1953 // If this is x86-64, and we disabled SSE, we can't return FP values,
1954 // or SSE or MMX vectors.
1955 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1956 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1957 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1958 report_fatal_error("SSE register return with SSE disabled");
1960 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1961 // llvm-gcc has never done it right and no one has noticed, so this
1962 // should be OK for now.
1963 if (ValVT == MVT::f64 &&
1964 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1965 report_fatal_error("SSE2 register return with SSE2 disabled");
1967 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1968 // the RET instruction and handled by the FP Stackifier.
1969 if (VA.getLocReg() == X86::FP0 ||
1970 VA.getLocReg() == X86::FP1) {
1971 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1972 // change the value to the FP stack register class.
1973 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1974 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1975 RetOps.push_back(ValToCopy);
1976 // Don't emit a copytoreg.
1980 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1981 // which is returned in RAX / RDX.
1982 if (Subtarget->is64Bit()) {
1983 if (ValVT == MVT::x86mmx) {
1984 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1985 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1986 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1988 // If we don't have SSE2 available, convert to v4f32 so the generated
1989 // register is legal.
1990 if (!Subtarget->hasSSE2())
1991 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1996 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1997 Flag = Chain.getValue(1);
1998 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2001 // The x86-64 ABIs require that for returning structs by value we copy
2002 // the sret argument into %rax/%eax (depending on ABI) for the return.
2003 // Win32 requires us to put the sret argument to %eax as well.
2004 // We saved the argument into a virtual register in the entry block,
2005 // so now we copy the value out and into %rax/%eax.
2006 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2007 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2008 MachineFunction &MF = DAG.getMachineFunction();
2009 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2010 unsigned Reg = FuncInfo->getSRetReturnReg();
2012 "SRetReturnReg should have been set in LowerFormalArguments().");
2013 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2016 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2017 X86::RAX : X86::EAX;
2018 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2019 Flag = Chain.getValue(1);
2021 // RAX/EAX now acts like a return value.
2022 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2025 RetOps[0] = Chain; // Update chain.
2027 // Add the flag if we have it.
2029 RetOps.push_back(Flag);
2031 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2034 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2035 if (N->getNumValues() != 1)
2037 if (!N->hasNUsesOfValue(1, 0))
2040 SDValue TCChain = Chain;
2041 SDNode *Copy = *N->use_begin();
2042 if (Copy->getOpcode() == ISD::CopyToReg) {
2043 // If the copy has a glue operand, we conservatively assume it isn't safe to
2044 // perform a tail call.
2045 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2047 TCChain = Copy->getOperand(0);
2048 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2051 bool HasRet = false;
2052 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2054 if (UI->getOpcode() != X86ISD::RET_FLAG)
2067 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2068 ISD::NodeType ExtendKind) const {
2070 // TODO: Is this also valid on 32-bit?
2071 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2072 ReturnMVT = MVT::i8;
2074 ReturnMVT = MVT::i32;
2076 EVT MinVT = getRegisterType(Context, ReturnMVT);
2077 return VT.bitsLT(MinVT) ? MinVT : VT;
2080 /// LowerCallResult - Lower the result values of a call into the
2081 /// appropriate copies out of appropriate physical registers.
2084 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2085 CallingConv::ID CallConv, bool isVarArg,
2086 const SmallVectorImpl<ISD::InputArg> &Ins,
2087 SDLoc dl, SelectionDAG &DAG,
2088 SmallVectorImpl<SDValue> &InVals) const {
2090 // Assign locations to each value returned by this call.
2091 SmallVector<CCValAssign, 16> RVLocs;
2092 bool Is64Bit = Subtarget->is64Bit();
2093 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2095 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2097 // Copy all of the result registers out of their specified physreg.
2098 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2099 CCValAssign &VA = RVLocs[i];
2100 EVT CopyVT = VA.getValVT();
2102 // If this is x86-64, and we disabled SSE, we can't return FP values
2103 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2104 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2105 report_fatal_error("SSE register return with SSE disabled");
2108 // If we prefer to use the value in xmm registers, copy it out as f80 and
2109 // use a truncate to move it from fp stack reg to xmm reg.
2110 if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2111 isScalarFPTypeInSSEReg(VA.getValVT()))
2114 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2115 CopyVT, InFlag).getValue(1);
2116 SDValue Val = Chain.getValue(0);
2118 if (CopyVT != VA.getValVT())
2119 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2120 // This truncation won't change the value.
2121 DAG.getIntPtrConstant(1));
2123 InFlag = Chain.getValue(2);
2124 InVals.push_back(Val);
2130 //===----------------------------------------------------------------------===//
2131 // C & StdCall & Fast Calling Convention implementation
2132 //===----------------------------------------------------------------------===//
2133 // StdCall calling convention seems to be standard for many Windows' API
2134 // routines and around. It differs from C calling convention just a little:
2135 // callee should clean up the stack, not caller. Symbols should be also
2136 // decorated in some fancy way :) It doesn't support any vector arguments.
2137 // For info on fast calling convention see Fast Calling Convention (tail call)
2138 // implementation LowerX86_32FastCCCallTo.
2140 /// CallIsStructReturn - Determines whether a call uses struct return
2142 enum StructReturnType {
2147 static StructReturnType
2148 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2150 return NotStructReturn;
2152 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2153 if (!Flags.isSRet())
2154 return NotStructReturn;
2155 if (Flags.isInReg())
2156 return RegStructReturn;
2157 return StackStructReturn;
2160 /// ArgsAreStructReturn - Determines whether a function uses struct
2161 /// return semantics.
2162 static StructReturnType
2163 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2165 return NotStructReturn;
2167 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2168 if (!Flags.isSRet())
2169 return NotStructReturn;
2170 if (Flags.isInReg())
2171 return RegStructReturn;
2172 return StackStructReturn;
2175 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2176 /// by "Src" to address "Dst" with size and alignment information specified by
2177 /// the specific parameter attribute. The copy will be passed as a byval
2178 /// function parameter.
2180 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2181 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2183 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2185 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2186 /*isVolatile*/false, /*AlwaysInline=*/true,
2187 MachinePointerInfo(), MachinePointerInfo());
2190 /// IsTailCallConvention - Return true if the calling convention is one that
2191 /// supports tail call optimization.
2192 static bool IsTailCallConvention(CallingConv::ID CC) {
2193 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2194 CC == CallingConv::HiPE);
2197 /// \brief Return true if the calling convention is a C calling convention.
2198 static bool IsCCallConvention(CallingConv::ID CC) {
2199 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2200 CC == CallingConv::X86_64_SysV);
2203 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2204 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2208 CallingConv::ID CalleeCC = CS.getCallingConv();
2209 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2215 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2216 /// a tailcall target by changing its ABI.
2217 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2218 bool GuaranteedTailCallOpt) {
2219 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2223 X86TargetLowering::LowerMemArgument(SDValue Chain,
2224 CallingConv::ID CallConv,
2225 const SmallVectorImpl<ISD::InputArg> &Ins,
2226 SDLoc dl, SelectionDAG &DAG,
2227 const CCValAssign &VA,
2228 MachineFrameInfo *MFI,
2230 // Create the nodes corresponding to a load from this parameter slot.
2231 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2232 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2233 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2234 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2237 // If value is passed by pointer we have address passed instead of the value
2239 if (VA.getLocInfo() == CCValAssign::Indirect)
2240 ValVT = VA.getLocVT();
2242 ValVT = VA.getValVT();
2244 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2245 // changed with more analysis.
2246 // In case of tail call optimization mark all arguments mutable. Since they
2247 // could be overwritten by lowering of arguments in case of a tail call.
2248 if (Flags.isByVal()) {
2249 unsigned Bytes = Flags.getByValSize();
2250 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2251 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2252 return DAG.getFrameIndex(FI, getPointerTy());
2254 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2255 VA.getLocMemOffset(), isImmutable);
2256 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2257 return DAG.getLoad(ValVT, dl, Chain, FIN,
2258 MachinePointerInfo::getFixedStack(FI),
2259 false, false, false, 0);
2264 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2265 CallingConv::ID CallConv,
2267 const SmallVectorImpl<ISD::InputArg> &Ins,
2270 SmallVectorImpl<SDValue> &InVals)
2272 MachineFunction &MF = DAG.getMachineFunction();
2273 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2275 const Function* Fn = MF.getFunction();
2276 if (Fn->hasExternalLinkage() &&
2277 Subtarget->isTargetCygMing() &&
2278 Fn->getName() == "main")
2279 FuncInfo->setForceFramePointer(true);
2281 MachineFrameInfo *MFI = MF.getFrameInfo();
2282 bool Is64Bit = Subtarget->is64Bit();
2283 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2285 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2286 "Var args not supported with calling convention fastcc, ghc or hipe");
2288 // Assign locations to all of the incoming arguments.
2289 SmallVector<CCValAssign, 16> ArgLocs;
2290 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2292 // Allocate shadow area for Win64
2294 CCInfo.AllocateStack(32, 8);
2296 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2298 unsigned LastVal = ~0U;
2300 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2301 CCValAssign &VA = ArgLocs[i];
2302 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2304 assert(VA.getValNo() != LastVal &&
2305 "Don't support value assigned to multiple locs yet");
2307 LastVal = VA.getValNo();
2309 if (VA.isRegLoc()) {
2310 EVT RegVT = VA.getLocVT();
2311 const TargetRegisterClass *RC;
2312 if (RegVT == MVT::i32)
2313 RC = &X86::GR32RegClass;
2314 else if (Is64Bit && RegVT == MVT::i64)
2315 RC = &X86::GR64RegClass;
2316 else if (RegVT == MVT::f32)
2317 RC = &X86::FR32RegClass;
2318 else if (RegVT == MVT::f64)
2319 RC = &X86::FR64RegClass;
2320 else if (RegVT.is512BitVector())
2321 RC = &X86::VR512RegClass;
2322 else if (RegVT.is256BitVector())
2323 RC = &X86::VR256RegClass;
2324 else if (RegVT.is128BitVector())
2325 RC = &X86::VR128RegClass;
2326 else if (RegVT == MVT::x86mmx)
2327 RC = &X86::VR64RegClass;
2328 else if (RegVT == MVT::i1)
2329 RC = &X86::VK1RegClass;
2330 else if (RegVT == MVT::v8i1)
2331 RC = &X86::VK8RegClass;
2332 else if (RegVT == MVT::v16i1)
2333 RC = &X86::VK16RegClass;
2334 else if (RegVT == MVT::v32i1)
2335 RC = &X86::VK32RegClass;
2336 else if (RegVT == MVT::v64i1)
2337 RC = &X86::VK64RegClass;
2339 llvm_unreachable("Unknown argument type!");
2341 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2342 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2344 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2345 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2347 if (VA.getLocInfo() == CCValAssign::SExt)
2348 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2349 DAG.getValueType(VA.getValVT()));
2350 else if (VA.getLocInfo() == CCValAssign::ZExt)
2351 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2352 DAG.getValueType(VA.getValVT()));
2353 else if (VA.getLocInfo() == CCValAssign::BCvt)
2354 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2356 if (VA.isExtInLoc()) {
2357 // Handle MMX values passed in XMM regs.
2358 if (RegVT.isVector())
2359 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2361 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2364 assert(VA.isMemLoc());
2365 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2368 // If value is passed via pointer - do a load.
2369 if (VA.getLocInfo() == CCValAssign::Indirect)
2370 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2371 MachinePointerInfo(), false, false, false, 0);
2373 InVals.push_back(ArgValue);
2376 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2377 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2378 // The x86-64 ABIs require that for returning structs by value we copy
2379 // the sret argument into %rax/%eax (depending on ABI) for the return.
2380 // Win32 requires us to put the sret argument to %eax as well.
2381 // Save the argument into a virtual register so that we can access it
2382 // from the return points.
2383 if (Ins[i].Flags.isSRet()) {
2384 unsigned Reg = FuncInfo->getSRetReturnReg();
2386 MVT PtrTy = getPointerTy();
2387 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2388 FuncInfo->setSRetReturnReg(Reg);
2390 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2391 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2397 unsigned StackSize = CCInfo.getNextStackOffset();
2398 // Align stack specially for tail calls.
2399 if (FuncIsMadeTailCallSafe(CallConv,
2400 MF.getTarget().Options.GuaranteedTailCallOpt))
2401 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2403 // If the function takes variable number of arguments, make a frame index for
2404 // the start of the first vararg value... for expansion of llvm.va_start.
2406 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2407 CallConv != CallingConv::X86_ThisCall)) {
2408 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2411 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2413 // FIXME: We should really autogenerate these arrays
2414 static const MCPhysReg GPR64ArgRegsWin64[] = {
2415 X86::RCX, X86::RDX, X86::R8, X86::R9
2417 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2418 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2420 static const MCPhysReg XMMArgRegs64Bit[] = {
2421 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2422 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2424 const MCPhysReg *GPR64ArgRegs;
2425 unsigned NumXMMRegs = 0;
2428 // The XMM registers which might contain var arg parameters are shadowed
2429 // in their paired GPR. So we only need to save the GPR to their home
2431 TotalNumIntRegs = 4;
2432 GPR64ArgRegs = GPR64ArgRegsWin64;
2434 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2435 GPR64ArgRegs = GPR64ArgRegs64Bit;
2437 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2440 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2443 bool NoImplicitFloatOps = Fn->getAttributes().
2444 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2445 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2446 "SSE register cannot be used when SSE is disabled!");
2447 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2448 NoImplicitFloatOps) &&
2449 "SSE register cannot be used when SSE is disabled!");
2450 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2451 !Subtarget->hasSSE1())
2452 // Kernel mode asks for SSE to be disabled, so don't push them
2454 TotalNumXMMRegs = 0;
2457 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2458 // Get to the caller-allocated home save location. Add 8 to account
2459 // for the return address.
2460 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2461 FuncInfo->setRegSaveFrameIndex(
2462 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2463 // Fixup to set vararg frame on shadow area (4 x i64).
2465 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2467 // For X86-64, if there are vararg parameters that are passed via
2468 // registers, then we must store them to their spots on the stack so
2469 // they may be loaded by deferencing the result of va_next.
2470 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2471 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2472 FuncInfo->setRegSaveFrameIndex(
2473 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2477 // Store the integer parameter registers.
2478 SmallVector<SDValue, 8> MemOps;
2479 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2481 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2482 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2483 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2484 DAG.getIntPtrConstant(Offset));
2485 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2486 &X86::GR64RegClass);
2487 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2489 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2490 MachinePointerInfo::getFixedStack(
2491 FuncInfo->getRegSaveFrameIndex(), Offset),
2493 MemOps.push_back(Store);
2497 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2498 // Now store the XMM (fp + vector) parameter registers.
2499 SmallVector<SDValue, 12> SaveXMMOps;
2500 SaveXMMOps.push_back(Chain);
2502 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2503 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2504 SaveXMMOps.push_back(ALVal);
2506 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2507 FuncInfo->getRegSaveFrameIndex()));
2508 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2509 FuncInfo->getVarArgsFPOffset()));
2511 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2512 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2513 &X86::VR128RegClass);
2514 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2515 SaveXMMOps.push_back(Val);
2517 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2518 MVT::Other, SaveXMMOps));
2521 if (!MemOps.empty())
2522 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2526 // Some CCs need callee pop.
2527 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2528 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2529 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2531 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2532 // If this is an sret function, the return should pop the hidden pointer.
2533 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2534 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2535 argsAreStructReturn(Ins) == StackStructReturn)
2536 FuncInfo->setBytesToPopOnReturn(4);
2540 // RegSaveFrameIndex is X86-64 only.
2541 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2542 if (CallConv == CallingConv::X86_FastCall ||
2543 CallConv == CallingConv::X86_ThisCall)
2544 // fastcc functions can't have varargs.
2545 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2548 FuncInfo->setArgumentStackSize(StackSize);
2554 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2555 SDValue StackPtr, SDValue Arg,
2556 SDLoc dl, SelectionDAG &DAG,
2557 const CCValAssign &VA,
2558 ISD::ArgFlagsTy Flags) const {
2559 unsigned LocMemOffset = VA.getLocMemOffset();
2560 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2561 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2562 if (Flags.isByVal())
2563 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2565 return DAG.getStore(Chain, dl, Arg, PtrOff,
2566 MachinePointerInfo::getStack(LocMemOffset),
2570 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2571 /// optimization is performed and it is required.
2573 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2574 SDValue &OutRetAddr, SDValue Chain,
2575 bool IsTailCall, bool Is64Bit,
2576 int FPDiff, SDLoc dl) const {
2577 // Adjust the Return address stack slot.
2578 EVT VT = getPointerTy();
2579 OutRetAddr = getReturnAddressFrameIndex(DAG);
2581 // Load the "old" Return address.
2582 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2583 false, false, false, 0);
2584 return SDValue(OutRetAddr.getNode(), 1);
2587 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2588 /// optimization is performed and it is required (FPDiff!=0).
2589 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2590 SDValue Chain, SDValue RetAddrFrIdx,
2591 EVT PtrVT, unsigned SlotSize,
2592 int FPDiff, SDLoc dl) {
2593 // Store the return address to the appropriate stack slot.
2594 if (!FPDiff) return Chain;
2595 // Calculate the new stack slot for the return address.
2596 int NewReturnAddrFI =
2597 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2599 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2600 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2601 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2607 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2608 SmallVectorImpl<SDValue> &InVals) const {
2609 SelectionDAG &DAG = CLI.DAG;
2611 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2612 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2613 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2614 SDValue Chain = CLI.Chain;
2615 SDValue Callee = CLI.Callee;
2616 CallingConv::ID CallConv = CLI.CallConv;
2617 bool &isTailCall = CLI.IsTailCall;
2618 bool isVarArg = CLI.IsVarArg;
2620 MachineFunction &MF = DAG.getMachineFunction();
2621 bool Is64Bit = Subtarget->is64Bit();
2622 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2623 StructReturnType SR = callIsStructReturn(Outs);
2624 bool IsSibcall = false;
2626 if (MF.getTarget().Options.DisableTailCalls)
2629 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2631 // Force this to be a tail call. The verifier rules are enough to ensure
2632 // that we can lower this successfully without moving the return address
2635 } else if (isTailCall) {
2636 // Check if it's really possible to do a tail call.
2637 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2638 isVarArg, SR != NotStructReturn,
2639 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2640 Outs, OutVals, Ins, DAG);
2642 // Sibcalls are automatically detected tailcalls which do not require
2644 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2651 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2652 "Var args not supported with calling convention fastcc, ghc or hipe");
2654 // Analyze operands of the call, assigning locations to each operand.
2655 SmallVector<CCValAssign, 16> ArgLocs;
2656 CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2658 // Allocate shadow area for Win64
2660 CCInfo.AllocateStack(32, 8);
2662 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2664 // Get a count of how many bytes are to be pushed on the stack.
2665 unsigned NumBytes = CCInfo.getNextStackOffset();
2667 // This is a sibcall. The memory operands are available in caller's
2668 // own caller's stack.
2670 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2671 IsTailCallConvention(CallConv))
2672 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2675 if (isTailCall && !IsSibcall && !IsMustTail) {
2676 // Lower arguments at fp - stackoffset + fpdiff.
2677 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2678 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2680 FPDiff = NumBytesCallerPushed - NumBytes;
2682 // Set the delta of movement of the returnaddr stackslot.
2683 // But only set if delta is greater than previous delta.
2684 if (FPDiff < X86Info->getTCReturnAddrDelta())
2685 X86Info->setTCReturnAddrDelta(FPDiff);
2688 unsigned NumBytesToPush = NumBytes;
2689 unsigned NumBytesToPop = NumBytes;
2691 // If we have an inalloca argument, all stack space has already been allocated
2692 // for us and be right at the top of the stack. We don't support multiple
2693 // arguments passed in memory when using inalloca.
2694 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2696 if (!ArgLocs.back().isMemLoc())
2697 report_fatal_error("cannot use inalloca attribute on a register "
2699 if (ArgLocs.back().getLocMemOffset() != 0)
2700 report_fatal_error("any parameter with the inalloca attribute must be "
2701 "the only memory argument");
2705 Chain = DAG.getCALLSEQ_START(
2706 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2708 SDValue RetAddrFrIdx;
2709 // Load return address for tail calls.
2710 if (isTailCall && FPDiff)
2711 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2712 Is64Bit, FPDiff, dl);
2714 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2715 SmallVector<SDValue, 8> MemOpChains;
2718 // Walk the register/memloc assignments, inserting copies/loads. In the case
2719 // of tail call optimization arguments are handle later.
2720 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2721 DAG.getSubtarget().getRegisterInfo());
2722 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2723 // Skip inalloca arguments, they have already been written.
2724 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2725 if (Flags.isInAlloca())
2728 CCValAssign &VA = ArgLocs[i];
2729 EVT RegVT = VA.getLocVT();
2730 SDValue Arg = OutVals[i];
2731 bool isByVal = Flags.isByVal();
2733 // Promote the value if needed.
2734 switch (VA.getLocInfo()) {
2735 default: llvm_unreachable("Unknown loc info!");
2736 case CCValAssign::Full: break;
2737 case CCValAssign::SExt:
2738 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2740 case CCValAssign::ZExt:
2741 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2743 case CCValAssign::AExt:
2744 if (RegVT.is128BitVector()) {
2745 // Special case: passing MMX values in XMM registers.
2746 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2747 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2748 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2750 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2752 case CCValAssign::BCvt:
2753 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2755 case CCValAssign::Indirect: {
2756 // Store the argument.
2757 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2758 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2759 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2760 MachinePointerInfo::getFixedStack(FI),
2767 if (VA.isRegLoc()) {
2768 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2769 if (isVarArg && IsWin64) {
2770 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2771 // shadow reg if callee is a varargs function.
2772 unsigned ShadowReg = 0;
2773 switch (VA.getLocReg()) {
2774 case X86::XMM0: ShadowReg = X86::RCX; break;
2775 case X86::XMM1: ShadowReg = X86::RDX; break;
2776 case X86::XMM2: ShadowReg = X86::R8; break;
2777 case X86::XMM3: ShadowReg = X86::R9; break;
2780 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2782 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2783 assert(VA.isMemLoc());
2784 if (!StackPtr.getNode())
2785 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2787 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2788 dl, DAG, VA, Flags));
2792 if (!MemOpChains.empty())
2793 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2795 if (Subtarget->isPICStyleGOT()) {
2796 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2799 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2800 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2802 // If we are tail calling and generating PIC/GOT style code load the
2803 // address of the callee into ECX. The value in ecx is used as target of
2804 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2805 // for tail calls on PIC/GOT architectures. Normally we would just put the
2806 // address of GOT into ebx and then call target@PLT. But for tail calls
2807 // ebx would be restored (since ebx is callee saved) before jumping to the
2810 // Note: The actual moving to ECX is done further down.
2811 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2812 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2813 !G->getGlobal()->hasProtectedVisibility())
2814 Callee = LowerGlobalAddress(Callee, DAG);
2815 else if (isa<ExternalSymbolSDNode>(Callee))
2816 Callee = LowerExternalSymbol(Callee, DAG);
2820 if (Is64Bit && isVarArg && !IsWin64) {
2821 // From AMD64 ABI document:
2822 // For calls that may call functions that use varargs or stdargs
2823 // (prototype-less calls or calls to functions containing ellipsis (...) in
2824 // the declaration) %al is used as hidden argument to specify the number
2825 // of SSE registers used. The contents of %al do not need to match exactly
2826 // the number of registers, but must be an ubound on the number of SSE
2827 // registers used and is in the range 0 - 8 inclusive.
2829 // Count the number of XMM registers allocated.
2830 static const MCPhysReg XMMArgRegs[] = {
2831 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2832 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2834 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2835 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2836 && "SSE registers cannot be used when SSE is disabled");
2838 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2839 DAG.getConstant(NumXMMRegs, MVT::i8)));
2842 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2843 // don't need this because the eligibility check rejects calls that require
2844 // shuffling arguments passed in memory.
2845 if (!IsSibcall && isTailCall) {
2846 // Force all the incoming stack arguments to be loaded from the stack
2847 // before any new outgoing arguments are stored to the stack, because the
2848 // outgoing stack slots may alias the incoming argument stack slots, and
2849 // the alias isn't otherwise explicit. This is slightly more conservative
2850 // than necessary, because it means that each store effectively depends
2851 // on every argument instead of just those arguments it would clobber.
2852 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2854 SmallVector<SDValue, 8> MemOpChains2;
2857 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2858 CCValAssign &VA = ArgLocs[i];
2861 assert(VA.isMemLoc());
2862 SDValue Arg = OutVals[i];
2863 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2864 // Skip inalloca arguments. They don't require any work.
2865 if (Flags.isInAlloca())
2867 // Create frame index.
2868 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2869 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2870 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2871 FIN = DAG.getFrameIndex(FI, getPointerTy());
2873 if (Flags.isByVal()) {
2874 // Copy relative to framepointer.
2875 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2876 if (!StackPtr.getNode())
2877 StackPtr = DAG.getCopyFromReg(Chain, dl,
2878 RegInfo->getStackRegister(),
2880 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2882 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2886 // Store relative to framepointer.
2887 MemOpChains2.push_back(
2888 DAG.getStore(ArgChain, dl, Arg, FIN,
2889 MachinePointerInfo::getFixedStack(FI),
2894 if (!MemOpChains2.empty())
2895 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2897 // Store the return address to the appropriate stack slot.
2898 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2899 getPointerTy(), RegInfo->getSlotSize(),
2903 // Build a sequence of copy-to-reg nodes chained together with token chain
2904 // and flag operands which copy the outgoing args into registers.
2906 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2907 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2908 RegsToPass[i].second, InFlag);
2909 InFlag = Chain.getValue(1);
2912 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2913 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2914 // In the 64-bit large code model, we have to make all calls
2915 // through a register, since the call instruction's 32-bit
2916 // pc-relative offset may not be large enough to hold the whole
2918 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2919 // If the callee is a GlobalAddress node (quite common, every direct call
2920 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2923 // We should use extra load for direct calls to dllimported functions in
2925 const GlobalValue *GV = G->getGlobal();
2926 if (!GV->hasDLLImportStorageClass()) {
2927 unsigned char OpFlags = 0;
2928 bool ExtraLoad = false;
2929 unsigned WrapperKind = ISD::DELETED_NODE;
2931 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2932 // external symbols most go through the PLT in PIC mode. If the symbol
2933 // has hidden or protected visibility, or if it is static or local, then
2934 // we don't need to use the PLT - we can directly call it.
2935 if (Subtarget->isTargetELF() &&
2936 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2937 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2938 OpFlags = X86II::MO_PLT;
2939 } else if (Subtarget->isPICStyleStubAny() &&
2940 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2941 (!Subtarget->getTargetTriple().isMacOSX() ||
2942 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2943 // PC-relative references to external symbols should go through $stub,
2944 // unless we're building with the leopard linker or later, which
2945 // automatically synthesizes these stubs.
2946 OpFlags = X86II::MO_DARWIN_STUB;
2947 } else if (Subtarget->isPICStyleRIPRel() &&
2948 isa<Function>(GV) &&
2949 cast<Function>(GV)->getAttributes().
2950 hasAttribute(AttributeSet::FunctionIndex,
2951 Attribute::NonLazyBind)) {
2952 // If the function is marked as non-lazy, generate an indirect call
2953 // which loads from the GOT directly. This avoids runtime overhead
2954 // at the cost of eager binding (and one extra byte of encoding).
2955 OpFlags = X86II::MO_GOTPCREL;
2956 WrapperKind = X86ISD::WrapperRIP;
2960 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2961 G->getOffset(), OpFlags);
2963 // Add a wrapper if needed.
2964 if (WrapperKind != ISD::DELETED_NODE)
2965 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2966 // Add extra indirection if needed.
2968 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2969 MachinePointerInfo::getGOT(),
2970 false, false, false, 0);
2972 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2973 unsigned char OpFlags = 0;
2975 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2976 // external symbols should go through the PLT.
2977 if (Subtarget->isTargetELF() &&
2978 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2979 OpFlags = X86II::MO_PLT;
2980 } else if (Subtarget->isPICStyleStubAny() &&
2981 (!Subtarget->getTargetTriple().isMacOSX() ||
2982 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2983 // PC-relative references to external symbols should go through $stub,
2984 // unless we're building with the leopard linker or later, which
2985 // automatically synthesizes these stubs.
2986 OpFlags = X86II::MO_DARWIN_STUB;
2989 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2993 // Returns a chain & a flag for retval copy to use.
2994 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2995 SmallVector<SDValue, 8> Ops;
2997 if (!IsSibcall && isTailCall) {
2998 Chain = DAG.getCALLSEQ_END(Chain,
2999 DAG.getIntPtrConstant(NumBytesToPop, true),
3000 DAG.getIntPtrConstant(0, true), InFlag, dl);
3001 InFlag = Chain.getValue(1);
3004 Ops.push_back(Chain);
3005 Ops.push_back(Callee);
3008 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3010 // Add argument registers to the end of the list so that they are known live
3012 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3013 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3014 RegsToPass[i].second.getValueType()));
3016 // Add a register mask operand representing the call-preserved registers.
3017 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3018 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3019 assert(Mask && "Missing call preserved mask for calling convention");
3020 Ops.push_back(DAG.getRegisterMask(Mask));
3022 if (InFlag.getNode())
3023 Ops.push_back(InFlag);
3027 //// If this is the first return lowered for this function, add the regs
3028 //// to the liveout set for the function.
3029 // This isn't right, although it's probably harmless on x86; liveouts
3030 // should be computed from returns not tail calls. Consider a void
3031 // function making a tail call to a function returning int.
3032 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3035 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3036 InFlag = Chain.getValue(1);
3038 // Create the CALLSEQ_END node.
3039 unsigned NumBytesForCalleeToPop;
3040 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3041 DAG.getTarget().Options.GuaranteedTailCallOpt))
3042 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
3043 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3044 !Subtarget->getTargetTriple().isOSMSVCRT() &&
3045 SR == StackStructReturn)
3046 // If this is a call to a struct-return function, the callee
3047 // pops the hidden struct pointer, so we have to push it back.
3048 // This is common for Darwin/X86, Linux & Mingw32 targets.
3049 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3050 NumBytesForCalleeToPop = 4;
3052 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3054 // Returns a flag for retval copy to use.
3056 Chain = DAG.getCALLSEQ_END(Chain,
3057 DAG.getIntPtrConstant(NumBytesToPop, true),
3058 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3061 InFlag = Chain.getValue(1);
3064 // Handle result values, copying them out of physregs into vregs that we
3066 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3067 Ins, dl, DAG, InVals);
3070 //===----------------------------------------------------------------------===//
3071 // Fast Calling Convention (tail call) implementation
3072 //===----------------------------------------------------------------------===//
3074 // Like std call, callee cleans arguments, convention except that ECX is
3075 // reserved for storing the tail called function address. Only 2 registers are
3076 // free for argument passing (inreg). Tail call optimization is performed
3078 // * tailcallopt is enabled
3079 // * caller/callee are fastcc
3080 // On X86_64 architecture with GOT-style position independent code only local
3081 // (within module) calls are supported at the moment.
3082 // To keep the stack aligned according to platform abi the function
3083 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3084 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3085 // If a tail called function callee has more arguments than the caller the
3086 // caller needs to make sure that there is room to move the RETADDR to. This is
3087 // achieved by reserving an area the size of the argument delta right after the
3088 // original RETADDR, but before the saved framepointer or the spilled registers
3089 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3101 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3102 /// for a 16 byte align requirement.
3104 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3105 SelectionDAG& DAG) const {
3106 MachineFunction &MF = DAG.getMachineFunction();
3107 const TargetMachine &TM = MF.getTarget();
3108 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3109 TM.getSubtargetImpl()->getRegisterInfo());
3110 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3111 unsigned StackAlignment = TFI.getStackAlignment();
3112 uint64_t AlignMask = StackAlignment - 1;
3113 int64_t Offset = StackSize;
3114 unsigned SlotSize = RegInfo->getSlotSize();
3115 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3116 // Number smaller than 12 so just add the difference.
3117 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3119 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3120 Offset = ((~AlignMask) & Offset) + StackAlignment +
3121 (StackAlignment-SlotSize);
3126 /// MatchingStackOffset - Return true if the given stack call argument is
3127 /// already available in the same position (relatively) of the caller's
3128 /// incoming argument stack.
3130 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3131 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3132 const X86InstrInfo *TII) {
3133 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3135 if (Arg.getOpcode() == ISD::CopyFromReg) {
3136 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3137 if (!TargetRegisterInfo::isVirtualRegister(VR))
3139 MachineInstr *Def = MRI->getVRegDef(VR);
3142 if (!Flags.isByVal()) {
3143 if (!TII->isLoadFromStackSlot(Def, FI))
3146 unsigned Opcode = Def->getOpcode();
3147 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3148 Def->getOperand(1).isFI()) {
3149 FI = Def->getOperand(1).getIndex();
3150 Bytes = Flags.getByValSize();
3154 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3155 if (Flags.isByVal())
3156 // ByVal argument is passed in as a pointer but it's now being
3157 // dereferenced. e.g.
3158 // define @foo(%struct.X* %A) {
3159 // tail call @bar(%struct.X* byval %A)
3162 SDValue Ptr = Ld->getBasePtr();
3163 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3166 FI = FINode->getIndex();
3167 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3168 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3169 FI = FINode->getIndex();
3170 Bytes = Flags.getByValSize();
3174 assert(FI != INT_MAX);
3175 if (!MFI->isFixedObjectIndex(FI))
3177 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3180 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3181 /// for tail call optimization. Targets which want to do tail call
3182 /// optimization should implement this function.
3184 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3185 CallingConv::ID CalleeCC,
3187 bool isCalleeStructRet,
3188 bool isCallerStructRet,
3190 const SmallVectorImpl<ISD::OutputArg> &Outs,
3191 const SmallVectorImpl<SDValue> &OutVals,
3192 const SmallVectorImpl<ISD::InputArg> &Ins,
3193 SelectionDAG &DAG) const {
3194 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3197 // If -tailcallopt is specified, make fastcc functions tail-callable.
3198 const MachineFunction &MF = DAG.getMachineFunction();
3199 const Function *CallerF = MF.getFunction();
3201 // If the function return type is x86_fp80 and the callee return type is not,
3202 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3203 // perform a tailcall optimization here.
3204 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3207 CallingConv::ID CallerCC = CallerF->getCallingConv();
3208 bool CCMatch = CallerCC == CalleeCC;
3209 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3210 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3212 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3213 if (IsTailCallConvention(CalleeCC) && CCMatch)
3218 // Look for obvious safe cases to perform tail call optimization that do not
3219 // require ABI changes. This is what gcc calls sibcall.
3221 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3222 // emit a special epilogue.
3223 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3224 DAG.getSubtarget().getRegisterInfo());
3225 if (RegInfo->needsStackRealignment(MF))
3228 // Also avoid sibcall optimization if either caller or callee uses struct
3229 // return semantics.
3230 if (isCalleeStructRet || isCallerStructRet)
3233 // An stdcall/thiscall caller is expected to clean up its arguments; the
3234 // callee isn't going to do that.
3235 // FIXME: this is more restrictive than needed. We could produce a tailcall
3236 // when the stack adjustment matches. For example, with a thiscall that takes
3237 // only one argument.
3238 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3239 CallerCC == CallingConv::X86_ThisCall))
3242 // Do not sibcall optimize vararg calls unless all arguments are passed via
3244 if (isVarArg && !Outs.empty()) {
3246 // Optimizing for varargs on Win64 is unlikely to be safe without
3247 // additional testing.
3248 if (IsCalleeWin64 || IsCallerWin64)
3251 SmallVector<CCValAssign, 16> ArgLocs;
3252 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3255 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3256 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3257 if (!ArgLocs[i].isRegLoc())
3261 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3262 // stack. Therefore, if it's not used by the call it is not safe to optimize
3263 // this into a sibcall.
3264 bool Unused = false;
3265 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3272 SmallVector<CCValAssign, 16> RVLocs;
3273 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3275 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3276 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3277 CCValAssign &VA = RVLocs[i];
3278 if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3283 // If the calling conventions do not match, then we'd better make sure the
3284 // results are returned in the same way as what the caller expects.
3286 SmallVector<CCValAssign, 16> RVLocs1;
3287 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3289 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3291 SmallVector<CCValAssign, 16> RVLocs2;
3292 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3294 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3296 if (RVLocs1.size() != RVLocs2.size())
3298 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3299 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3301 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3303 if (RVLocs1[i].isRegLoc()) {
3304 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3307 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3313 // If the callee takes no arguments then go on to check the results of the
3315 if (!Outs.empty()) {
3316 // Check if stack adjustment is needed. For now, do not do this if any
3317 // argument is passed on the stack.
3318 SmallVector<CCValAssign, 16> ArgLocs;
3319 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3322 // Allocate shadow area for Win64
3324 CCInfo.AllocateStack(32, 8);
3326 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3327 if (CCInfo.getNextStackOffset()) {
3328 MachineFunction &MF = DAG.getMachineFunction();
3329 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3332 // Check if the arguments are already laid out in the right way as
3333 // the caller's fixed stack objects.
3334 MachineFrameInfo *MFI = MF.getFrameInfo();
3335 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3336 const X86InstrInfo *TII =
3337 static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3338 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3339 CCValAssign &VA = ArgLocs[i];
3340 SDValue Arg = OutVals[i];
3341 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3342 if (VA.getLocInfo() == CCValAssign::Indirect)
3344 if (!VA.isRegLoc()) {
3345 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3352 // If the tailcall address may be in a register, then make sure it's
3353 // possible to register allocate for it. In 32-bit, the call address can
3354 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3355 // callee-saved registers are restored. These happen to be the same
3356 // registers used to pass 'inreg' arguments so watch out for those.
3357 if (!Subtarget->is64Bit() &&
3358 ((!isa<GlobalAddressSDNode>(Callee) &&
3359 !isa<ExternalSymbolSDNode>(Callee)) ||
3360 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3361 unsigned NumInRegs = 0;
3362 // In PIC we need an extra register to formulate the address computation
3364 unsigned MaxInRegs =
3365 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3367 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3368 CCValAssign &VA = ArgLocs[i];
3371 unsigned Reg = VA.getLocReg();
3374 case X86::EAX: case X86::EDX: case X86::ECX:
3375 if (++NumInRegs == MaxInRegs)
3387 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3388 const TargetLibraryInfo *libInfo) const {
3389 return X86::createFastISel(funcInfo, libInfo);
3392 //===----------------------------------------------------------------------===//
3393 // Other Lowering Hooks
3394 //===----------------------------------------------------------------------===//
3396 static bool MayFoldLoad(SDValue Op) {
3397 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3400 static bool MayFoldIntoStore(SDValue Op) {
3401 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3404 static bool isTargetShuffle(unsigned Opcode) {
3406 default: return false;
3407 case X86ISD::PSHUFB:
3408 case X86ISD::PSHUFD:
3409 case X86ISD::PSHUFHW:
3410 case X86ISD::PSHUFLW:
3412 case X86ISD::PALIGNR:
3413 case X86ISD::MOVLHPS:
3414 case X86ISD::MOVLHPD:
3415 case X86ISD::MOVHLPS:
3416 case X86ISD::MOVLPS:
3417 case X86ISD::MOVLPD:
3418 case X86ISD::MOVSHDUP:
3419 case X86ISD::MOVSLDUP:
3420 case X86ISD::MOVDDUP:
3423 case X86ISD::UNPCKL:
3424 case X86ISD::UNPCKH:
3425 case X86ISD::VPERMILP:
3426 case X86ISD::VPERM2X128:
3427 case X86ISD::VPERMI:
3432 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3433 SDValue V1, SelectionDAG &DAG) {
3435 default: llvm_unreachable("Unknown x86 shuffle node");
3436 case X86ISD::MOVSHDUP:
3437 case X86ISD::MOVSLDUP:
3438 case X86ISD::MOVDDUP:
3439 return DAG.getNode(Opc, dl, VT, V1);
3443 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3444 SDValue V1, unsigned TargetMask,
3445 SelectionDAG &DAG) {
3447 default: llvm_unreachable("Unknown x86 shuffle node");
3448 case X86ISD::PSHUFD:
3449 case X86ISD::PSHUFHW:
3450 case X86ISD::PSHUFLW:
3451 case X86ISD::VPERMILP:
3452 case X86ISD::VPERMI:
3453 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3457 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3458 SDValue V1, SDValue V2, unsigned TargetMask,
3459 SelectionDAG &DAG) {
3461 default: llvm_unreachable("Unknown x86 shuffle node");
3462 case X86ISD::PALIGNR:
3463 case X86ISD::VALIGN:
3465 case X86ISD::VPERM2X128:
3466 return DAG.getNode(Opc, dl, VT, V1, V2,
3467 DAG.getConstant(TargetMask, MVT::i8));
3471 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3472 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3474 default: llvm_unreachable("Unknown x86 shuffle node");
3475 case X86ISD::MOVLHPS:
3476 case X86ISD::MOVLHPD:
3477 case X86ISD::MOVHLPS:
3478 case X86ISD::MOVLPS:
3479 case X86ISD::MOVLPD:
3482 case X86ISD::UNPCKL:
3483 case X86ISD::UNPCKH:
3484 return DAG.getNode(Opc, dl, VT, V1, V2);
3488 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3489 MachineFunction &MF = DAG.getMachineFunction();
3490 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3491 DAG.getSubtarget().getRegisterInfo());
3492 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3493 int ReturnAddrIndex = FuncInfo->getRAIndex();
3495 if (ReturnAddrIndex == 0) {
3496 // Set up a frame object for the return address.
3497 unsigned SlotSize = RegInfo->getSlotSize();
3498 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3501 FuncInfo->setRAIndex(ReturnAddrIndex);
3504 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3507 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3508 bool hasSymbolicDisplacement) {
3509 // Offset should fit into 32 bit immediate field.
3510 if (!isInt<32>(Offset))
3513 // If we don't have a symbolic displacement - we don't have any extra
3515 if (!hasSymbolicDisplacement)
3518 // FIXME: Some tweaks might be needed for medium code model.
3519 if (M != CodeModel::Small && M != CodeModel::Kernel)
3522 // For small code model we assume that latest object is 16MB before end of 31
3523 // bits boundary. We may also accept pretty large negative constants knowing
3524 // that all objects are in the positive half of address space.
3525 if (M == CodeModel::Small && Offset < 16*1024*1024)
3528 // For kernel code model we know that all object resist in the negative half
3529 // of 32bits address space. We may not accept negative offsets, since they may
3530 // be just off and we may accept pretty large positive ones.
3531 if (M == CodeModel::Kernel && Offset > 0)
3537 /// isCalleePop - Determines whether the callee is required to pop its
3538 /// own arguments. Callee pop is necessary to support tail calls.
3539 bool X86::isCalleePop(CallingConv::ID CallingConv,
3540 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3544 switch (CallingConv) {
3547 case CallingConv::X86_StdCall:
3549 case CallingConv::X86_FastCall:
3551 case CallingConv::X86_ThisCall:
3553 case CallingConv::Fast:
3555 case CallingConv::GHC:
3557 case CallingConv::HiPE:
3562 /// \brief Return true if the condition is an unsigned comparison operation.
3563 static bool isX86CCUnsigned(unsigned X86CC) {
3565 default: llvm_unreachable("Invalid integer condition!");
3566 case X86::COND_E: return true;
3567 case X86::COND_G: return false;
3568 case X86::COND_GE: return false;
3569 case X86::COND_L: return false;
3570 case X86::COND_LE: return false;
3571 case X86::COND_NE: return true;
3572 case X86::COND_B: return true;
3573 case X86::COND_A: return true;
3574 case X86::COND_BE: return true;
3575 case X86::COND_AE: return true;
3577 llvm_unreachable("covered switch fell through?!");
3580 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3581 /// specific condition code, returning the condition code and the LHS/RHS of the
3582 /// comparison to make.
3583 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3584 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3586 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3587 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3588 // X > -1 -> X == 0, jump !sign.
3589 RHS = DAG.getConstant(0, RHS.getValueType());
3590 return X86::COND_NS;
3592 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3593 // X < 0 -> X == 0, jump on sign.
3596 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3598 RHS = DAG.getConstant(0, RHS.getValueType());
3599 return X86::COND_LE;
3603 switch (SetCCOpcode) {
3604 default: llvm_unreachable("Invalid integer condition!");
3605 case ISD::SETEQ: return X86::COND_E;
3606 case ISD::SETGT: return X86::COND_G;
3607 case ISD::SETGE: return X86::COND_GE;
3608 case ISD::SETLT: return X86::COND_L;
3609 case ISD::SETLE: return X86::COND_LE;
3610 case ISD::SETNE: return X86::COND_NE;
3611 case ISD::SETULT: return X86::COND_B;
3612 case ISD::SETUGT: return X86::COND_A;
3613 case ISD::SETULE: return X86::COND_BE;
3614 case ISD::SETUGE: return X86::COND_AE;
3618 // First determine if it is required or is profitable to flip the operands.
3620 // If LHS is a foldable load, but RHS is not, flip the condition.
3621 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3622 !ISD::isNON_EXTLoad(RHS.getNode())) {
3623 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3624 std::swap(LHS, RHS);
3627 switch (SetCCOpcode) {
3633 std::swap(LHS, RHS);
3637 // On a floating point condition, the flags are set as follows:
3639 // 0 | 0 | 0 | X > Y
3640 // 0 | 0 | 1 | X < Y
3641 // 1 | 0 | 0 | X == Y
3642 // 1 | 1 | 1 | unordered
3643 switch (SetCCOpcode) {
3644 default: llvm_unreachable("Condcode should be pre-legalized away");
3646 case ISD::SETEQ: return X86::COND_E;
3647 case ISD::SETOLT: // flipped
3649 case ISD::SETGT: return X86::COND_A;
3650 case ISD::SETOLE: // flipped
3652 case ISD::SETGE: return X86::COND_AE;
3653 case ISD::SETUGT: // flipped
3655 case ISD::SETLT: return X86::COND_B;
3656 case ISD::SETUGE: // flipped
3658 case ISD::SETLE: return X86::COND_BE;
3660 case ISD::SETNE: return X86::COND_NE;
3661 case ISD::SETUO: return X86::COND_P;
3662 case ISD::SETO: return X86::COND_NP;
3664 case ISD::SETUNE: return X86::COND_INVALID;
3668 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3669 /// code. Current x86 isa includes the following FP cmov instructions:
3670 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3671 static bool hasFPCMov(unsigned X86CC) {
3687 /// isFPImmLegal - Returns true if the target can instruction select the
3688 /// specified FP immediate natively. If false, the legalizer will
3689 /// materialize the FP immediate as a load from a constant pool.
3690 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3691 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3692 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3698 /// \brief Returns true if it is beneficial to convert a load of a constant
3699 /// to just the constant itself.
3700 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3702 assert(Ty->isIntegerTy());
3704 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3705 if (BitSize == 0 || BitSize > 64)
3710 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3711 /// the specified range (L, H].
3712 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3713 return (Val < 0) || (Val >= Low && Val < Hi);
3716 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3717 /// specified value.
3718 static bool isUndefOrEqual(int Val, int CmpVal) {
3719 return (Val < 0 || Val == CmpVal);
3722 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3723 /// from position Pos and ending in Pos+Size, falls within the specified
3724 /// sequential range (L, L+Pos]. or is undef.
3725 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3726 unsigned Pos, unsigned Size, int Low) {
3727 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3728 if (!isUndefOrEqual(Mask[i], Low))
3733 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3734 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3735 /// the second operand.
3736 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3737 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3738 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3739 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3740 return (Mask[0] < 2 && Mask[1] < 2);
3744 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3745 /// is suitable for input to PSHUFHW.
3746 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3747 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3750 // Lower quadword copied in order or undef.
3751 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3754 // Upper quadword shuffled.
3755 for (unsigned i = 4; i != 8; ++i)
3756 if (!isUndefOrInRange(Mask[i], 4, 8))
3759 if (VT == MVT::v16i16) {
3760 // Lower quadword copied in order or undef.
3761 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3764 // Upper quadword shuffled.
3765 for (unsigned i = 12; i != 16; ++i)
3766 if (!isUndefOrInRange(Mask[i], 12, 16))
3773 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3774 /// is suitable for input to PSHUFLW.
3775 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3776 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3779 // Upper quadword copied in order.
3780 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3783 // Lower quadword shuffled.
3784 for (unsigned i = 0; i != 4; ++i)
3785 if (!isUndefOrInRange(Mask[i], 0, 4))
3788 if (VT == MVT::v16i16) {
3789 // Upper quadword copied in order.
3790 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3793 // Lower quadword shuffled.
3794 for (unsigned i = 8; i != 12; ++i)
3795 if (!isUndefOrInRange(Mask[i], 8, 12))
3802 /// \brief Return true if the mask specifies a shuffle of elements that is
3803 /// suitable for input to intralane (palignr) or interlane (valign) vector
3805 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3806 unsigned NumElts = VT.getVectorNumElements();
3807 unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3808 unsigned NumLaneElts = NumElts/NumLanes;
3810 // Do not handle 64-bit element shuffles with palignr.
3811 if (NumLaneElts == 2)
3814 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3816 for (i = 0; i != NumLaneElts; ++i) {
3821 // Lane is all undef, go to next lane
3822 if (i == NumLaneElts)
3825 int Start = Mask[i+l];
3827 // Make sure its in this lane in one of the sources
3828 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3829 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3832 // If not lane 0, then we must match lane 0
3833 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3836 // Correct second source to be contiguous with first source
3837 if (Start >= (int)NumElts)
3838 Start -= NumElts - NumLaneElts;
3840 // Make sure we're shifting in the right direction.
3841 if (Start <= (int)(i+l))
3846 // Check the rest of the elements to see if they are consecutive.
3847 for (++i; i != NumLaneElts; ++i) {
3848 int Idx = Mask[i+l];
3850 // Make sure its in this lane
3851 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3852 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3855 // If not lane 0, then we must match lane 0
3856 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3859 if (Idx >= (int)NumElts)
3860 Idx -= NumElts - NumLaneElts;
3862 if (!isUndefOrEqual(Idx, Start+i))
3871 /// \brief Return true if the node specifies a shuffle of elements that is
3872 /// suitable for input to PALIGNR.
3873 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3874 const X86Subtarget *Subtarget) {
3875 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3876 (VT.is256BitVector() && !Subtarget->hasInt256()) ||
3877 VT.is512BitVector())
3878 // FIXME: Add AVX512BW.
3881 return isAlignrMask(Mask, VT, false);
3884 /// \brief Return true if the node specifies a shuffle of elements that is
3885 /// suitable for input to VALIGN.
3886 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
3887 const X86Subtarget *Subtarget) {
3888 // FIXME: Add AVX512VL.
3889 if (!VT.is512BitVector() || !Subtarget->hasAVX512())
3891 return isAlignrMask(Mask, VT, true);
3894 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3895 /// the two vector operands have swapped position.
3896 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3897 unsigned NumElems) {
3898 for (unsigned i = 0; i != NumElems; ++i) {
3902 else if (idx < (int)NumElems)
3903 Mask[i] = idx + NumElems;
3905 Mask[i] = idx - NumElems;
3909 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3910 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3911 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3912 /// reverse of what x86 shuffles want.
3913 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3915 unsigned NumElems = VT.getVectorNumElements();
3916 unsigned NumLanes = VT.getSizeInBits()/128;
3917 unsigned NumLaneElems = NumElems/NumLanes;
3919 if (NumLaneElems != 2 && NumLaneElems != 4)
3922 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3923 bool symetricMaskRequired =
3924 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3926 // VSHUFPSY divides the resulting vector into 4 chunks.
3927 // The sources are also splitted into 4 chunks, and each destination
3928 // chunk must come from a different source chunk.
3930 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3931 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3933 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3934 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3936 // VSHUFPDY divides the resulting vector into 4 chunks.
3937 // The sources are also splitted into 4 chunks, and each destination
3938 // chunk must come from a different source chunk.
3940 // SRC1 => X3 X2 X1 X0
3941 // SRC2 => Y3 Y2 Y1 Y0
3943 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3945 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3946 unsigned HalfLaneElems = NumLaneElems/2;
3947 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3948 for (unsigned i = 0; i != NumLaneElems; ++i) {
3949 int Idx = Mask[i+l];
3950 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3951 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3953 // For VSHUFPSY, the mask of the second half must be the same as the
3954 // first but with the appropriate offsets. This works in the same way as
3955 // VPERMILPS works with masks.
3956 if (!symetricMaskRequired || Idx < 0)
3958 if (MaskVal[i] < 0) {
3959 MaskVal[i] = Idx - l;
3962 if ((signed)(Idx - l) != MaskVal[i])
3970 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3971 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3972 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3973 if (!VT.is128BitVector())
3976 unsigned NumElems = VT.getVectorNumElements();
3981 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3982 return isUndefOrEqual(Mask[0], 6) &&
3983 isUndefOrEqual(Mask[1], 7) &&
3984 isUndefOrEqual(Mask[2], 2) &&
3985 isUndefOrEqual(Mask[3], 3);
3988 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3989 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3991 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3992 if (!VT.is128BitVector())
3995 unsigned NumElems = VT.getVectorNumElements();
4000 return isUndefOrEqual(Mask[0], 2) &&
4001 isUndefOrEqual(Mask[1], 3) &&
4002 isUndefOrEqual(Mask[2], 2) &&
4003 isUndefOrEqual(Mask[3], 3);
4006 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4007 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4008 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4009 if (!VT.is128BitVector())
4012 unsigned NumElems = VT.getVectorNumElements();
4014 if (NumElems != 2 && NumElems != 4)
4017 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4018 if (!isUndefOrEqual(Mask[i], i + NumElems))
4021 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4022 if (!isUndefOrEqual(Mask[i], i))
4028 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4029 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4030 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4031 if (!VT.is128BitVector())
4034 unsigned NumElems = VT.getVectorNumElements();
4036 if (NumElems != 2 && NumElems != 4)
4039 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4040 if (!isUndefOrEqual(Mask[i], i))
4043 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4044 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4050 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4051 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4052 /// i. e: If all but one element come from the same vector.
4053 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4054 // TODO: Deal with AVX's VINSERTPS
4055 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4058 unsigned CorrectPosV1 = 0;
4059 unsigned CorrectPosV2 = 0;
4060 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4061 if (Mask[i] == -1) {
4069 else if (Mask[i] == i + 4)
4073 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4074 // We have 3 elements (undefs count as elements from any vector) from one
4075 // vector, and one from another.
4082 // Some special combinations that can be optimized.
4085 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4086 SelectionDAG &DAG) {
4087 MVT VT = SVOp->getSimpleValueType(0);
4090 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4093 ArrayRef<int> Mask = SVOp->getMask();
4095 // These are the special masks that may be optimized.
4096 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4097 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4098 bool MatchEvenMask = true;
4099 bool MatchOddMask = true;
4100 for (int i=0; i<8; ++i) {
4101 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4102 MatchEvenMask = false;
4103 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4104 MatchOddMask = false;
4107 if (!MatchEvenMask && !MatchOddMask)
4110 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4112 SDValue Op0 = SVOp->getOperand(0);
4113 SDValue Op1 = SVOp->getOperand(1);
4115 if (MatchEvenMask) {
4116 // Shift the second operand right to 32 bits.
4117 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4118 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4120 // Shift the first operand left to 32 bits.
4121 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4122 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4124 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4125 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4128 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4129 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4130 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4131 bool HasInt256, bool V2IsSplat = false) {
4133 assert(VT.getSizeInBits() >= 128 &&
4134 "Unsupported vector type for unpckl");
4136 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4138 unsigned NumOf256BitLanes;
4139 unsigned NumElts = VT.getVectorNumElements();
4140 if (VT.is256BitVector()) {
4141 if (NumElts != 4 && NumElts != 8 &&
4142 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4145 NumOf256BitLanes = 1;
4146 } else if (VT.is512BitVector()) {
4147 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4148 "Unsupported vector type for unpckh");
4150 NumOf256BitLanes = 2;
4153 NumOf256BitLanes = 1;
4156 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4157 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4159 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4160 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4161 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4162 int BitI = Mask[l256*NumEltsInStride+l+i];
4163 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4164 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4166 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4168 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4176 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4177 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4178 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4179 bool HasInt256, bool V2IsSplat = false) {
4180 assert(VT.getSizeInBits() >= 128 &&
4181 "Unsupported vector type for unpckh");
4183 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4185 unsigned NumOf256BitLanes;
4186 unsigned NumElts = VT.getVectorNumElements();
4187 if (VT.is256BitVector()) {
4188 if (NumElts != 4 && NumElts != 8 &&
4189 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4192 NumOf256BitLanes = 1;
4193 } else if (VT.is512BitVector()) {
4194 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4195 "Unsupported vector type for unpckh");
4197 NumOf256BitLanes = 2;
4200 NumOf256BitLanes = 1;
4203 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4204 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4206 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4207 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4208 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4209 int BitI = Mask[l256*NumEltsInStride+l+i];
4210 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4211 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4213 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4215 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4223 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4224 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4226 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4227 unsigned NumElts = VT.getVectorNumElements();
4228 bool Is256BitVec = VT.is256BitVector();
4230 if (VT.is512BitVector())
4232 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4233 "Unsupported vector type for unpckh");
4235 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4236 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4239 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4240 // FIXME: Need a better way to get rid of this, there's no latency difference
4241 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4242 // the former later. We should also remove the "_undef" special mask.
4243 if (NumElts == 4 && Is256BitVec)
4246 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4247 // independently on 128-bit lanes.
4248 unsigned NumLanes = VT.getSizeInBits()/128;
4249 unsigned NumLaneElts = NumElts/NumLanes;
4251 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4252 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4253 int BitI = Mask[l+i];
4254 int BitI1 = Mask[l+i+1];
4256 if (!isUndefOrEqual(BitI, j))
4258 if (!isUndefOrEqual(BitI1, j))
4266 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4267 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4269 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4270 unsigned NumElts = VT.getVectorNumElements();
4272 if (VT.is512BitVector())
4275 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4276 "Unsupported vector type for unpckh");
4278 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4279 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4282 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4283 // independently on 128-bit lanes.
4284 unsigned NumLanes = VT.getSizeInBits()/128;
4285 unsigned NumLaneElts = NumElts/NumLanes;
4287 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4288 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4289 int BitI = Mask[l+i];
4290 int BitI1 = Mask[l+i+1];
4291 if (!isUndefOrEqual(BitI, j))
4293 if (!isUndefOrEqual(BitI1, j))
4300 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4301 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4302 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4303 if (!VT.is512BitVector())
4306 unsigned NumElts = VT.getVectorNumElements();
4307 unsigned HalfSize = NumElts/2;
4308 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4309 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4314 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4315 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4323 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4324 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4325 /// MOVSD, and MOVD, i.e. setting the lowest element.
4326 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4327 if (VT.getVectorElementType().getSizeInBits() < 32)
4329 if (!VT.is128BitVector())
4332 unsigned NumElts = VT.getVectorNumElements();
4334 if (!isUndefOrEqual(Mask[0], NumElts))
4337 for (unsigned i = 1; i != NumElts; ++i)
4338 if (!isUndefOrEqual(Mask[i], i))
4344 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4345 /// as permutations between 128-bit chunks or halves. As an example: this
4347 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4348 /// The first half comes from the second half of V1 and the second half from the
4349 /// the second half of V2.
4350 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4351 if (!HasFp256 || !VT.is256BitVector())
4354 // The shuffle result is divided into half A and half B. In total the two
4355 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4356 // B must come from C, D, E or F.
4357 unsigned HalfSize = VT.getVectorNumElements()/2;
4358 bool MatchA = false, MatchB = false;
4360 // Check if A comes from one of C, D, E, F.
4361 for (unsigned Half = 0; Half != 4; ++Half) {
4362 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4368 // Check if B comes from one of C, D, E, F.
4369 for (unsigned Half = 0; Half != 4; ++Half) {
4370 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4376 return MatchA && MatchB;
4379 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4380 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4381 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4382 MVT VT = SVOp->getSimpleValueType(0);
4384 unsigned HalfSize = VT.getVectorNumElements()/2;
4386 unsigned FstHalf = 0, SndHalf = 0;
4387 for (unsigned i = 0; i < HalfSize; ++i) {
4388 if (SVOp->getMaskElt(i) > 0) {
4389 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4393 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4394 if (SVOp->getMaskElt(i) > 0) {
4395 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4400 return (FstHalf | (SndHalf << 4));
4403 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4404 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4405 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4409 unsigned NumElts = VT.getVectorNumElements();
4411 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4412 for (unsigned i = 0; i != NumElts; ++i) {
4415 Imm8 |= Mask[i] << (i*2);
4420 unsigned LaneSize = 4;
4421 SmallVector<int, 4> MaskVal(LaneSize, -1);
4423 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4424 for (unsigned i = 0; i != LaneSize; ++i) {
4425 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4429 if (MaskVal[i] < 0) {
4430 MaskVal[i] = Mask[i+l] - l;
4431 Imm8 |= MaskVal[i] << (i*2);
4434 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4441 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4442 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4443 /// Note that VPERMIL mask matching is different depending whether theunderlying
4444 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4445 /// to the same elements of the low, but to the higher half of the source.
4446 /// In VPERMILPD the two lanes could be shuffled independently of each other
4447 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4448 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4449 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4450 if (VT.getSizeInBits() < 256 || EltSize < 32)
4452 bool symetricMaskRequired = (EltSize == 32);
4453 unsigned NumElts = VT.getVectorNumElements();
4455 unsigned NumLanes = VT.getSizeInBits()/128;
4456 unsigned LaneSize = NumElts/NumLanes;
4457 // 2 or 4 elements in one lane
4459 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4460 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4461 for (unsigned i = 0; i != LaneSize; ++i) {
4462 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4464 if (symetricMaskRequired) {
4465 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4466 ExpectedMaskVal[i] = Mask[i+l] - l;
4469 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4477 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4478 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4479 /// element of vector 2 and the other elements to come from vector 1 in order.
4480 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4481 bool V2IsSplat = false, bool V2IsUndef = false) {
4482 if (!VT.is128BitVector())
4485 unsigned NumOps = VT.getVectorNumElements();
4486 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4489 if (!isUndefOrEqual(Mask[0], 0))
4492 for (unsigned i = 1; i != NumOps; ++i)
4493 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4494 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4495 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4501 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4502 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4503 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4504 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4505 const X86Subtarget *Subtarget) {
4506 if (!Subtarget->hasSSE3())
4509 unsigned NumElems = VT.getVectorNumElements();
4511 if ((VT.is128BitVector() && NumElems != 4) ||
4512 (VT.is256BitVector() && NumElems != 8) ||
4513 (VT.is512BitVector() && NumElems != 16))
4516 // "i+1" is the value the indexed mask element must have
4517 for (unsigned i = 0; i != NumElems; i += 2)
4518 if (!isUndefOrEqual(Mask[i], i+1) ||
4519 !isUndefOrEqual(Mask[i+1], i+1))
4525 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4526 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4527 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4528 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4529 const X86Subtarget *Subtarget) {
4530 if (!Subtarget->hasSSE3())
4533 unsigned NumElems = VT.getVectorNumElements();
4535 if ((VT.is128BitVector() && NumElems != 4) ||
4536 (VT.is256BitVector() && NumElems != 8) ||
4537 (VT.is512BitVector() && NumElems != 16))
4540 // "i" is the value the indexed mask element must have
4541 for (unsigned i = 0; i != NumElems; i += 2)
4542 if (!isUndefOrEqual(Mask[i], i) ||
4543 !isUndefOrEqual(Mask[i+1], i))
4549 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4550 /// specifies a shuffle of elements that is suitable for input to 256-bit
4551 /// version of MOVDDUP.
4552 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4553 if (!HasFp256 || !VT.is256BitVector())
4556 unsigned NumElts = VT.getVectorNumElements();
4560 for (unsigned i = 0; i != NumElts/2; ++i)
4561 if (!isUndefOrEqual(Mask[i], 0))
4563 for (unsigned i = NumElts/2; i != NumElts; ++i)
4564 if (!isUndefOrEqual(Mask[i], NumElts/2))
4569 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4570 /// specifies a shuffle of elements that is suitable for input to 128-bit
4571 /// version of MOVDDUP.
4572 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4573 if (!VT.is128BitVector())
4576 unsigned e = VT.getVectorNumElements() / 2;
4577 for (unsigned i = 0; i != e; ++i)
4578 if (!isUndefOrEqual(Mask[i], i))
4580 for (unsigned i = 0; i != e; ++i)
4581 if (!isUndefOrEqual(Mask[e+i], i))
4586 /// isVEXTRACTIndex - Return true if the specified
4587 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4588 /// suitable for instruction that extract 128 or 256 bit vectors
4589 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4590 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4591 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4594 // The index should be aligned on a vecWidth-bit boundary.
4596 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4598 MVT VT = N->getSimpleValueType(0);
4599 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4600 bool Result = (Index * ElSize) % vecWidth == 0;
4605 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4606 /// operand specifies a subvector insert that is suitable for input to
4607 /// insertion of 128 or 256-bit subvectors
4608 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4609 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4610 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4612 // The index should be aligned on a vecWidth-bit boundary.
4614 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4616 MVT VT = N->getSimpleValueType(0);
4617 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4618 bool Result = (Index * ElSize) % vecWidth == 0;
4623 bool X86::isVINSERT128Index(SDNode *N) {
4624 return isVINSERTIndex(N, 128);
4627 bool X86::isVINSERT256Index(SDNode *N) {
4628 return isVINSERTIndex(N, 256);
4631 bool X86::isVEXTRACT128Index(SDNode *N) {
4632 return isVEXTRACTIndex(N, 128);
4635 bool X86::isVEXTRACT256Index(SDNode *N) {
4636 return isVEXTRACTIndex(N, 256);
4639 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4640 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4641 /// Handles 128-bit and 256-bit.
4642 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4643 MVT VT = N->getSimpleValueType(0);
4645 assert((VT.getSizeInBits() >= 128) &&
4646 "Unsupported vector type for PSHUF/SHUFP");
4648 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4649 // independently on 128-bit lanes.
4650 unsigned NumElts = VT.getVectorNumElements();
4651 unsigned NumLanes = VT.getSizeInBits()/128;
4652 unsigned NumLaneElts = NumElts/NumLanes;
4654 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4655 "Only supports 2, 4 or 8 elements per lane");
4657 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4659 for (unsigned i = 0; i != NumElts; ++i) {
4660 int Elt = N->getMaskElt(i);
4661 if (Elt < 0) continue;
4662 Elt &= NumLaneElts - 1;
4663 unsigned ShAmt = (i << Shift) % 8;
4664 Mask |= Elt << ShAmt;
4670 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4671 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4672 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4673 MVT VT = N->getSimpleValueType(0);
4675 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4676 "Unsupported vector type for PSHUFHW");
4678 unsigned NumElts = VT.getVectorNumElements();
4681 for (unsigned l = 0; l != NumElts; l += 8) {
4682 // 8 nodes per lane, but we only care about the last 4.
4683 for (unsigned i = 0; i < 4; ++i) {
4684 int Elt = N->getMaskElt(l+i+4);
4685 if (Elt < 0) continue;
4686 Elt &= 0x3; // only 2-bits.
4687 Mask |= Elt << (i * 2);
4694 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4695 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4696 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4697 MVT VT = N->getSimpleValueType(0);
4699 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4700 "Unsupported vector type for PSHUFHW");
4702 unsigned NumElts = VT.getVectorNumElements();
4705 for (unsigned l = 0; l != NumElts; l += 8) {
4706 // 8 nodes per lane, but we only care about the first 4.
4707 for (unsigned i = 0; i < 4; ++i) {
4708 int Elt = N->getMaskElt(l+i);
4709 if (Elt < 0) continue;
4710 Elt &= 0x3; // only 2-bits
4711 Mask |= Elt << (i * 2);
4718 /// \brief Return the appropriate immediate to shuffle the specified
4719 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4720 /// VALIGN (if Interlane is true) instructions.
4721 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4723 MVT VT = SVOp->getSimpleValueType(0);
4724 unsigned EltSize = InterLane ? 1 :
4725 VT.getVectorElementType().getSizeInBits() >> 3;
4727 unsigned NumElts = VT.getVectorNumElements();
4728 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4729 unsigned NumLaneElts = NumElts/NumLanes;
4733 for (i = 0; i != NumElts; ++i) {
4734 Val = SVOp->getMaskElt(i);
4738 if (Val >= (int)NumElts)
4739 Val -= NumElts - NumLaneElts;
4741 assert(Val - i > 0 && "PALIGNR imm should be positive");
4742 return (Val - i) * EltSize;
4745 /// \brief Return the appropriate immediate to shuffle the specified
4746 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4747 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4748 return getShuffleAlignrImmediate(SVOp, false);
4751 /// \brief Return the appropriate immediate to shuffle the specified
4752 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4753 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4754 return getShuffleAlignrImmediate(SVOp, true);
4758 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4759 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4760 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4761 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4764 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4766 MVT VecVT = N->getOperand(0).getSimpleValueType();
4767 MVT ElVT = VecVT.getVectorElementType();
4769 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4770 return Index / NumElemsPerChunk;
4773 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4774 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4775 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4776 llvm_unreachable("Illegal insert subvector for VINSERT");
4779 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4781 MVT VecVT = N->getSimpleValueType(0);
4782 MVT ElVT = VecVT.getVectorElementType();
4784 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4785 return Index / NumElemsPerChunk;
4788 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4789 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4790 /// and VINSERTI128 instructions.
4791 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4792 return getExtractVEXTRACTImmediate(N, 128);
4795 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4796 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4797 /// and VINSERTI64x4 instructions.
4798 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4799 return getExtractVEXTRACTImmediate(N, 256);
4802 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4803 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4804 /// and VINSERTI128 instructions.
4805 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4806 return getInsertVINSERTImmediate(N, 128);
4809 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4810 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4811 /// and VINSERTI64x4 instructions.
4812 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4813 return getInsertVINSERTImmediate(N, 256);
4816 /// isZero - Returns true if Elt is a constant integer zero
4817 static bool isZero(SDValue V) {
4818 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4819 return C && C->isNullValue();
4822 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4824 bool X86::isZeroNode(SDValue Elt) {
4827 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4828 return CFP->getValueAPF().isPosZero();
4832 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4833 /// match movhlps. The lower half elements should come from upper half of
4834 /// V1 (and in order), and the upper half elements should come from the upper
4835 /// half of V2 (and in order).
4836 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4837 if (!VT.is128BitVector())
4839 if (VT.getVectorNumElements() != 4)
4841 for (unsigned i = 0, e = 2; i != e; ++i)
4842 if (!isUndefOrEqual(Mask[i], i+2))
4844 for (unsigned i = 2; i != 4; ++i)
4845 if (!isUndefOrEqual(Mask[i], i+4))
4850 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4851 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4853 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4854 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4856 N = N->getOperand(0).getNode();
4857 if (!ISD::isNON_EXTLoad(N))
4860 *LD = cast<LoadSDNode>(N);
4864 // Test whether the given value is a vector value which will be legalized
4866 static bool WillBeConstantPoolLoad(SDNode *N) {
4867 if (N->getOpcode() != ISD::BUILD_VECTOR)
4870 // Check for any non-constant elements.
4871 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4872 switch (N->getOperand(i).getNode()->getOpcode()) {
4874 case ISD::ConstantFP:
4881 // Vectors of all-zeros and all-ones are materialized with special
4882 // instructions rather than being loaded.
4883 return !ISD::isBuildVectorAllZeros(N) &&
4884 !ISD::isBuildVectorAllOnes(N);
4887 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4888 /// match movlp{s|d}. The lower half elements should come from lower half of
4889 /// V1 (and in order), and the upper half elements should come from the upper
4890 /// half of V2 (and in order). And since V1 will become the source of the
4891 /// MOVLP, it must be either a vector load or a scalar load to vector.
4892 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4893 ArrayRef<int> Mask, MVT VT) {
4894 if (!VT.is128BitVector())
4897 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4899 // Is V2 is a vector load, don't do this transformation. We will try to use
4900 // load folding shufps op.
4901 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4904 unsigned NumElems = VT.getVectorNumElements();
4906 if (NumElems != 2 && NumElems != 4)
4908 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4909 if (!isUndefOrEqual(Mask[i], i))
4911 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4912 if (!isUndefOrEqual(Mask[i], i+NumElems))
4917 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4918 /// to an zero vector.
4919 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4920 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4921 SDValue V1 = N->getOperand(0);
4922 SDValue V2 = N->getOperand(1);
4923 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4924 for (unsigned i = 0; i != NumElems; ++i) {
4925 int Idx = N->getMaskElt(i);
4926 if (Idx >= (int)NumElems) {
4927 unsigned Opc = V2.getOpcode();
4928 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4930 if (Opc != ISD::BUILD_VECTOR ||
4931 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4933 } else if (Idx >= 0) {
4934 unsigned Opc = V1.getOpcode();
4935 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4937 if (Opc != ISD::BUILD_VECTOR ||
4938 !X86::isZeroNode(V1.getOperand(Idx)))
4945 /// getZeroVector - Returns a vector of specified type with all zero elements.
4947 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4948 SelectionDAG &DAG, SDLoc dl) {
4949 assert(VT.isVector() && "Expected a vector type");
4951 // Always build SSE zero vectors as <4 x i32> bitcasted
4952 // to their dest type. This ensures they get CSE'd.
4954 if (VT.is128BitVector()) { // SSE
4955 if (Subtarget->hasSSE2()) { // SSE2
4956 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4957 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4959 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4960 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4962 } else if (VT.is256BitVector()) { // AVX
4963 if (Subtarget->hasInt256()) { // AVX2
4964 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4965 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4966 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4968 // 256-bit logic and arithmetic instructions in AVX are all
4969 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4970 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4971 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4972 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4974 } else if (VT.is512BitVector()) { // AVX-512
4975 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4976 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4977 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4978 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4979 } else if (VT.getScalarType() == MVT::i1) {
4980 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4981 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4982 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4983 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4985 llvm_unreachable("Unexpected vector type");
4987 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4990 /// getOnesVector - Returns a vector of specified type with all bits set.
4991 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4992 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4993 /// Then bitcast to their original type, ensuring they get CSE'd.
4994 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4996 assert(VT.isVector() && "Expected a vector type");
4998 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5000 if (VT.is256BitVector()) {
5001 if (HasInt256) { // AVX2
5002 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5003 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5005 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5006 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5008 } else if (VT.is128BitVector()) {
5009 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5011 llvm_unreachable("Unexpected vector type");
5013 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5016 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5017 /// that point to V2 points to its first element.
5018 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5019 for (unsigned i = 0; i != NumElems; ++i) {
5020 if (Mask[i] > (int)NumElems) {
5026 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5027 /// operation of specified width.
5028 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5030 unsigned NumElems = VT.getVectorNumElements();
5031 SmallVector<int, 8> Mask;
5032 Mask.push_back(NumElems);
5033 for (unsigned i = 1; i != NumElems; ++i)
5035 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5038 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5039 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5041 unsigned NumElems = VT.getVectorNumElements();
5042 SmallVector<int, 8> Mask;
5043 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5045 Mask.push_back(i + NumElems);
5047 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5050 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5051 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5053 unsigned NumElems = VT.getVectorNumElements();
5054 SmallVector<int, 8> Mask;
5055 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5056 Mask.push_back(i + Half);
5057 Mask.push_back(i + NumElems + Half);
5059 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5062 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5063 // a generic shuffle instruction because the target has no such instructions.
5064 // Generate shuffles which repeat i16 and i8 several times until they can be
5065 // represented by v4f32 and then be manipulated by target suported shuffles.
5066 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5067 MVT VT = V.getSimpleValueType();
5068 int NumElems = VT.getVectorNumElements();
5071 while (NumElems > 4) {
5072 if (EltNo < NumElems/2) {
5073 V = getUnpackl(DAG, dl, VT, V, V);
5075 V = getUnpackh(DAG, dl, VT, V, V);
5076 EltNo -= NumElems/2;
5083 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5084 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5085 MVT VT = V.getSimpleValueType();
5088 if (VT.is128BitVector()) {
5089 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5090 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5091 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5093 } else if (VT.is256BitVector()) {
5094 // To use VPERMILPS to splat scalars, the second half of indicies must
5095 // refer to the higher part, which is a duplication of the lower one,
5096 // because VPERMILPS can only handle in-lane permutations.
5097 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5098 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5100 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5101 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5104 llvm_unreachable("Vector size not supported");
5106 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5109 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5110 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5111 MVT SrcVT = SV->getSimpleValueType(0);
5112 SDValue V1 = SV->getOperand(0);
5115 int EltNo = SV->getSplatIndex();
5116 int NumElems = SrcVT.getVectorNumElements();
5117 bool Is256BitVec = SrcVT.is256BitVector();
5119 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5120 "Unknown how to promote splat for type");
5122 // Extract the 128-bit part containing the splat element and update
5123 // the splat element index when it refers to the higher register.
5125 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5126 if (EltNo >= NumElems/2)
5127 EltNo -= NumElems/2;
5130 // All i16 and i8 vector types can't be used directly by a generic shuffle
5131 // instruction because the target has no such instruction. Generate shuffles
5132 // which repeat i16 and i8 several times until they fit in i32, and then can
5133 // be manipulated by target suported shuffles.
5134 MVT EltVT = SrcVT.getVectorElementType();
5135 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5136 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5138 // Recreate the 256-bit vector and place the same 128-bit vector
5139 // into the low and high part. This is necessary because we want
5140 // to use VPERM* to shuffle the vectors
5142 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5145 return getLegalSplat(DAG, V1, EltNo);
5148 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5149 /// vector of zero or undef vector. This produces a shuffle where the low
5150 /// element of V2 is swizzled into the zero/undef vector, landing at element
5151 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5152 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5154 const X86Subtarget *Subtarget,
5155 SelectionDAG &DAG) {
5156 MVT VT = V2.getSimpleValueType();
5158 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5159 unsigned NumElems = VT.getVectorNumElements();
5160 SmallVector<int, 16> MaskVec;
5161 for (unsigned i = 0; i != NumElems; ++i)
5162 // If this is the insertion idx, put the low elt of V2 here.
5163 MaskVec.push_back(i == Idx ? NumElems : i);
5164 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5167 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5168 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5169 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5170 /// shuffles which use a single input multiple times, and in those cases it will
5171 /// adjust the mask to only have indices within that single input.
5172 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5173 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5174 unsigned NumElems = VT.getVectorNumElements();
5178 bool IsFakeUnary = false;
5179 switch(N->getOpcode()) {
5181 ImmN = N->getOperand(N->getNumOperands()-1);
5182 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5183 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5185 case X86ISD::UNPCKH:
5186 DecodeUNPCKHMask(VT, Mask);
5187 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5189 case X86ISD::UNPCKL:
5190 DecodeUNPCKLMask(VT, Mask);
5191 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5193 case X86ISD::MOVHLPS:
5194 DecodeMOVHLPSMask(NumElems, Mask);
5195 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5197 case X86ISD::MOVLHPS:
5198 DecodeMOVLHPSMask(NumElems, Mask);
5199 IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5201 case X86ISD::PALIGNR:
5202 ImmN = N->getOperand(N->getNumOperands()-1);
5203 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5205 case X86ISD::PSHUFD:
5206 case X86ISD::VPERMILP:
5207 ImmN = N->getOperand(N->getNumOperands()-1);
5208 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5211 case X86ISD::PSHUFHW:
5212 ImmN = N->getOperand(N->getNumOperands()-1);
5213 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5216 case X86ISD::PSHUFLW:
5217 ImmN = N->getOperand(N->getNumOperands()-1);
5218 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5221 case X86ISD::PSHUFB: {
5223 SDValue MaskNode = N->getOperand(1);
5224 while (MaskNode->getOpcode() == ISD::BITCAST)
5225 MaskNode = MaskNode->getOperand(0);
5227 if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5228 // If we have a build-vector, then things are easy.
5229 EVT VT = MaskNode.getValueType();
5230 assert(VT.isVector() &&
5231 "Can't produce a non-vector with a build_vector!");
5232 if (!VT.isInteger())
5235 int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5237 SmallVector<uint64_t, 32> RawMask;
5238 for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5239 auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5242 APInt MaskElement = CN->getAPIntValue();
5244 // We now have to decode the element which could be any integer size and
5245 // extract each byte of it.
5246 for (int j = 0; j < NumBytesPerElement; ++j) {
5247 // Note that this is x86 and so always little endian: the low byte is
5248 // the first byte of the mask.
5249 RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5250 MaskElement = MaskElement.lshr(8);
5253 DecodePSHUFBMask(RawMask, Mask);
5257 auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5261 SDValue Ptr = MaskLoad->getBasePtr();
5262 if (Ptr->getOpcode() == X86ISD::Wrapper)
5263 Ptr = Ptr->getOperand(0);
5265 auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5266 if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5269 if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5270 // FIXME: Support AVX-512 here.
5271 if (!C->getType()->isVectorTy() ||
5272 (C->getNumElements() != 16 && C->getNumElements() != 32))
5275 assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5276 DecodePSHUFBMask(C, Mask);
5282 case X86ISD::VPERMI:
5283 ImmN = N->getOperand(N->getNumOperands()-1);
5284 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5288 case X86ISD::MOVSD: {
5289 // The index 0 always comes from the first element of the second source,
5290 // this is why MOVSS and MOVSD are used in the first place. The other
5291 // elements come from the other positions of the first source vector
5292 Mask.push_back(NumElems);
5293 for (unsigned i = 1; i != NumElems; ++i) {
5298 case X86ISD::VPERM2X128:
5299 ImmN = N->getOperand(N->getNumOperands()-1);
5300 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5301 if (Mask.empty()) return false;
5303 case X86ISD::MOVDDUP:
5304 case X86ISD::MOVLHPD:
5305 case X86ISD::MOVLPD:
5306 case X86ISD::MOVLPS:
5307 case X86ISD::MOVSHDUP:
5308 case X86ISD::MOVSLDUP:
5309 // Not yet implemented
5311 default: llvm_unreachable("unknown target shuffle node");
5314 // If we have a fake unary shuffle, the shuffle mask is spread across two
5315 // inputs that are actually the same node. Re-map the mask to always point
5316 // into the first input.
5319 if (M >= (int)Mask.size())
5325 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5326 /// element of the result of the vector shuffle.
5327 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5330 return SDValue(); // Limit search depth.
5332 SDValue V = SDValue(N, 0);
5333 EVT VT = V.getValueType();
5334 unsigned Opcode = V.getOpcode();
5336 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5337 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5338 int Elt = SV->getMaskElt(Index);
5341 return DAG.getUNDEF(VT.getVectorElementType());
5343 unsigned NumElems = VT.getVectorNumElements();
5344 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5345 : SV->getOperand(1);
5346 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5349 // Recurse into target specific vector shuffles to find scalars.
5350 if (isTargetShuffle(Opcode)) {
5351 MVT ShufVT = V.getSimpleValueType();
5352 unsigned NumElems = ShufVT.getVectorNumElements();
5353 SmallVector<int, 16> ShuffleMask;
5356 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5359 int Elt = ShuffleMask[Index];
5361 return DAG.getUNDEF(ShufVT.getVectorElementType());
5363 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5365 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5369 // Actual nodes that may contain scalar elements
5370 if (Opcode == ISD::BITCAST) {
5371 V = V.getOperand(0);
5372 EVT SrcVT = V.getValueType();
5373 unsigned NumElems = VT.getVectorNumElements();
5375 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5379 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5380 return (Index == 0) ? V.getOperand(0)
5381 : DAG.getUNDEF(VT.getVectorElementType());
5383 if (V.getOpcode() == ISD::BUILD_VECTOR)
5384 return V.getOperand(Index);
5389 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5390 /// shuffle operation which come from a consecutively from a zero. The
5391 /// search can start in two different directions, from left or right.
5392 /// We count undefs as zeros until PreferredNum is reached.
5393 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5394 unsigned NumElems, bool ZerosFromLeft,
5396 unsigned PreferredNum = -1U) {
5397 unsigned NumZeros = 0;
5398 for (unsigned i = 0; i != NumElems; ++i) {
5399 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5400 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5404 if (X86::isZeroNode(Elt))
5406 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5407 NumZeros = std::min(NumZeros + 1, PreferredNum);
5415 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5416 /// correspond consecutively to elements from one of the vector operands,
5417 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5419 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5420 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5421 unsigned NumElems, unsigned &OpNum) {
5422 bool SeenV1 = false;
5423 bool SeenV2 = false;
5425 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5426 int Idx = SVOp->getMaskElt(i);
5427 // Ignore undef indicies
5431 if (Idx < (int)NumElems)
5436 // Only accept consecutive elements from the same vector
5437 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5441 OpNum = SeenV1 ? 0 : 1;
5445 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5446 /// logical left shift of a vector.
5447 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5448 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5450 SVOp->getSimpleValueType(0).getVectorNumElements();
5451 unsigned NumZeros = getNumOfConsecutiveZeros(
5452 SVOp, NumElems, false /* check zeros from right */, DAG,
5453 SVOp->getMaskElt(0));
5459 // Considering the elements in the mask that are not consecutive zeros,
5460 // check if they consecutively come from only one of the source vectors.
5462 // V1 = {X, A, B, C} 0
5464 // vector_shuffle V1, V2 <1, 2, 3, X>
5466 if (!isShuffleMaskConsecutive(SVOp,
5467 0, // Mask Start Index
5468 NumElems-NumZeros, // Mask End Index(exclusive)
5469 NumZeros, // Where to start looking in the src vector
5470 NumElems, // Number of elements in vector
5471 OpSrc)) // Which source operand ?
5476 ShVal = SVOp->getOperand(OpSrc);
5480 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5481 /// logical left shift of a vector.
5482 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5483 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5485 SVOp->getSimpleValueType(0).getVectorNumElements();
5486 unsigned NumZeros = getNumOfConsecutiveZeros(
5487 SVOp, NumElems, true /* check zeros from left */, DAG,
5488 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5494 // Considering the elements in the mask that are not consecutive zeros,
5495 // check if they consecutively come from only one of the source vectors.
5497 // 0 { A, B, X, X } = V2
5499 // vector_shuffle V1, V2 <X, X, 4, 5>
5501 if (!isShuffleMaskConsecutive(SVOp,
5502 NumZeros, // Mask Start Index
5503 NumElems, // Mask End Index(exclusive)
5504 0, // Where to start looking in the src vector
5505 NumElems, // Number of elements in vector
5506 OpSrc)) // Which source operand ?
5511 ShVal = SVOp->getOperand(OpSrc);
5515 /// isVectorShift - Returns true if the shuffle can be implemented as a
5516 /// logical left or right shift of a vector.
5517 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5518 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5519 // Although the logic below support any bitwidth size, there are no
5520 // shift instructions which handle more than 128-bit vectors.
5521 if (!SVOp->getSimpleValueType(0).is128BitVector())
5524 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5525 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5531 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5533 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5534 unsigned NumNonZero, unsigned NumZero,
5536 const X86Subtarget* Subtarget,
5537 const TargetLowering &TLI) {
5544 for (unsigned i = 0; i < 16; ++i) {
5545 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5546 if (ThisIsNonZero && First) {
5548 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5550 V = DAG.getUNDEF(MVT::v8i16);
5555 SDValue ThisElt, LastElt;
5556 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5557 if (LastIsNonZero) {
5558 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5559 MVT::i16, Op.getOperand(i-1));
5561 if (ThisIsNonZero) {
5562 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5563 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5564 ThisElt, DAG.getConstant(8, MVT::i8));
5566 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5570 if (ThisElt.getNode())
5571 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5572 DAG.getIntPtrConstant(i/2));
5576 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5579 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5581 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5582 unsigned NumNonZero, unsigned NumZero,
5584 const X86Subtarget* Subtarget,
5585 const TargetLowering &TLI) {
5592 for (unsigned i = 0; i < 8; ++i) {
5593 bool isNonZero = (NonZeros & (1 << i)) != 0;
5597 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5599 V = DAG.getUNDEF(MVT::v8i16);
5602 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5603 MVT::v8i16, V, Op.getOperand(i),
5604 DAG.getIntPtrConstant(i));
5611 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5612 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5613 unsigned NonZeros, unsigned NumNonZero,
5614 unsigned NumZero, SelectionDAG &DAG,
5615 const X86Subtarget *Subtarget,
5616 const TargetLowering &TLI) {
5617 // We know there's at least one non-zero element
5618 unsigned FirstNonZeroIdx = 0;
5619 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5620 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5621 X86::isZeroNode(FirstNonZero)) {
5623 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5626 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5627 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5630 SDValue V = FirstNonZero.getOperand(0);
5631 MVT VVT = V.getSimpleValueType();
5632 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5635 unsigned FirstNonZeroDst =
5636 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5637 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5638 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5639 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5641 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5642 SDValue Elem = Op.getOperand(Idx);
5643 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5646 // TODO: What else can be here? Deal with it.
5647 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5650 // TODO: Some optimizations are still possible here
5651 // ex: Getting one element from a vector, and the rest from another.
5652 if (Elem.getOperand(0) != V)
5655 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5658 else if (IncorrectIdx == -1U) {
5662 // There was already one element with an incorrect index.
5663 // We can't optimize this case to an insertps.
5667 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5669 EVT VT = Op.getSimpleValueType();
5670 unsigned ElementMoveMask = 0;
5671 if (IncorrectIdx == -1U)
5672 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5674 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5676 SDValue InsertpsMask =
5677 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5678 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5684 /// getVShift - Return a vector logical shift node.
5686 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5687 unsigned NumBits, SelectionDAG &DAG,
5688 const TargetLowering &TLI, SDLoc dl) {
5689 assert(VT.is128BitVector() && "Unknown type for VShift");
5690 EVT ShVT = MVT::v2i64;
5691 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5692 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5693 return DAG.getNode(ISD::BITCAST, dl, VT,
5694 DAG.getNode(Opc, dl, ShVT, SrcOp,
5695 DAG.getConstant(NumBits,
5696 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5700 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5702 // Check if the scalar load can be widened into a vector load. And if
5703 // the address is "base + cst" see if the cst can be "absorbed" into
5704 // the shuffle mask.
5705 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5706 SDValue Ptr = LD->getBasePtr();
5707 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5709 EVT PVT = LD->getValueType(0);
5710 if (PVT != MVT::i32 && PVT != MVT::f32)
5715 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5716 FI = FINode->getIndex();
5718 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5719 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5720 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5721 Offset = Ptr.getConstantOperandVal(1);
5722 Ptr = Ptr.getOperand(0);
5727 // FIXME: 256-bit vector instructions don't require a strict alignment,
5728 // improve this code to support it better.
5729 unsigned RequiredAlign = VT.getSizeInBits()/8;
5730 SDValue Chain = LD->getChain();
5731 // Make sure the stack object alignment is at least 16 or 32.
5732 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5733 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5734 if (MFI->isFixedObjectIndex(FI)) {
5735 // Can't change the alignment. FIXME: It's possible to compute
5736 // the exact stack offset and reference FI + adjust offset instead.
5737 // If someone *really* cares about this. That's the way to implement it.
5740 MFI->setObjectAlignment(FI, RequiredAlign);
5744 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5745 // Ptr + (Offset & ~15).
5748 if ((Offset % RequiredAlign) & 3)
5750 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5752 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5753 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5755 int EltNo = (Offset - StartOffset) >> 2;
5756 unsigned NumElems = VT.getVectorNumElements();
5758 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5759 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5760 LD->getPointerInfo().getWithOffset(StartOffset),
5761 false, false, false, 0);
5763 SmallVector<int, 8> Mask;
5764 for (unsigned i = 0; i != NumElems; ++i)
5765 Mask.push_back(EltNo);
5767 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5773 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5774 /// vector of type 'VT', see if the elements can be replaced by a single large
5775 /// load which has the same value as a build_vector whose operands are 'elts'.
5777 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5779 /// FIXME: we'd also like to handle the case where the last elements are zero
5780 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5781 /// There's even a handy isZeroNode for that purpose.
5782 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5783 SDLoc &DL, SelectionDAG &DAG,
5784 bool isAfterLegalize) {
5785 EVT EltVT = VT.getVectorElementType();
5786 unsigned NumElems = Elts.size();
5788 LoadSDNode *LDBase = nullptr;
5789 unsigned LastLoadedElt = -1U;
5791 // For each element in the initializer, see if we've found a load or an undef.
5792 // If we don't find an initial load element, or later load elements are
5793 // non-consecutive, bail out.
5794 for (unsigned i = 0; i < NumElems; ++i) {
5795 SDValue Elt = Elts[i];
5797 if (!Elt.getNode() ||
5798 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5801 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5803 LDBase = cast<LoadSDNode>(Elt.getNode());
5807 if (Elt.getOpcode() == ISD::UNDEF)
5810 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5811 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5816 // If we have found an entire vector of loads and undefs, then return a large
5817 // load of the entire vector width starting at the base pointer. If we found
5818 // consecutive loads for the low half, generate a vzext_load node.
5819 if (LastLoadedElt == NumElems - 1) {
5821 if (isAfterLegalize &&
5822 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5825 SDValue NewLd = SDValue();
5827 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5828 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5829 LDBase->getPointerInfo(),
5830 LDBase->isVolatile(), LDBase->isNonTemporal(),
5831 LDBase->isInvariant(), 0);
5832 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5833 LDBase->getPointerInfo(),
5834 LDBase->isVolatile(), LDBase->isNonTemporal(),
5835 LDBase->isInvariant(), LDBase->getAlignment());
5837 if (LDBase->hasAnyUseOfValue(1)) {
5838 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5840 SDValue(NewLd.getNode(), 1));
5841 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5842 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5843 SDValue(NewLd.getNode(), 1));
5848 if (NumElems == 4 && LastLoadedElt == 1 &&
5849 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5850 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5851 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5853 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5854 LDBase->getPointerInfo(),
5855 LDBase->getAlignment(),
5856 false/*isVolatile*/, true/*ReadMem*/,
5859 // Make sure the newly-created LOAD is in the same position as LDBase in
5860 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5861 // update uses of LDBase's output chain to use the TokenFactor.
5862 if (LDBase->hasAnyUseOfValue(1)) {
5863 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5864 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5865 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5866 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5867 SDValue(ResNode.getNode(), 1));
5870 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5875 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5876 /// to generate a splat value for the following cases:
5877 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5878 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5879 /// a scalar load, or a constant.
5880 /// The VBROADCAST node is returned when a pattern is found,
5881 /// or SDValue() otherwise.
5882 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5883 SelectionDAG &DAG) {
5884 if (!Subtarget->hasFp256())
5887 MVT VT = Op.getSimpleValueType();
5890 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5891 "Unsupported vector type for broadcast.");
5896 switch (Op.getOpcode()) {
5898 // Unknown pattern found.
5901 case ISD::BUILD_VECTOR: {
5902 auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5903 BitVector UndefElements;
5904 SDValue Splat = BVOp->getSplatValue(&UndefElements);
5906 // We need a splat of a single value to use broadcast, and it doesn't
5907 // make any sense if the value is only in one element of the vector.
5908 if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5912 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5913 Ld.getOpcode() == ISD::ConstantFP);
5915 // Make sure that all of the users of a non-constant load are from the
5916 // BUILD_VECTOR node.
5917 if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5922 case ISD::VECTOR_SHUFFLE: {
5923 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5925 // Shuffles must have a splat mask where the first element is
5927 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5930 SDValue Sc = Op.getOperand(0);
5931 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5932 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5934 if (!Subtarget->hasInt256())
5937 // Use the register form of the broadcast instruction available on AVX2.
5938 if (VT.getSizeInBits() >= 256)
5939 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5940 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5943 Ld = Sc.getOperand(0);
5944 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5945 Ld.getOpcode() == ISD::ConstantFP);
5947 // The scalar_to_vector node and the suspected
5948 // load node must have exactly one user.
5949 // Constants may have multiple users.
5951 // AVX-512 has register version of the broadcast
5952 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5953 Ld.getValueType().getSizeInBits() >= 32;
5954 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5961 bool IsGE256 = (VT.getSizeInBits() >= 256);
5963 // Handle the broadcasting a single constant scalar from the constant pool
5964 // into a vector. On Sandybridge it is still better to load a constant vector
5965 // from the constant pool and not to broadcast it from a scalar.
5966 if (ConstSplatVal && Subtarget->hasInt256()) {
5967 EVT CVT = Ld.getValueType();
5968 assert(!CVT.isVector() && "Must not broadcast a vector type");
5969 unsigned ScalarSize = CVT.getSizeInBits();
5971 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5972 const Constant *C = nullptr;
5973 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5974 C = CI->getConstantIntValue();
5975 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5976 C = CF->getConstantFPValue();
5978 assert(C && "Invalid constant type");
5980 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5981 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5982 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5983 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5984 MachinePointerInfo::getConstantPool(),
5985 false, false, false, Alignment);
5987 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5991 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5992 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5994 // Handle AVX2 in-register broadcasts.
5995 if (!IsLoad && Subtarget->hasInt256() &&
5996 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5997 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5999 // The scalar source must be a normal load.
6003 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6004 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6006 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6007 // double since there is no vbroadcastsd xmm
6008 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6009 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6010 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6013 // Unsupported broadcast.
6017 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6018 /// underlying vector and index.
6020 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6022 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6024 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6025 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6028 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6030 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6032 // (extract_vector_elt (vector_shuffle<2,u,u,u>
6033 // (extract_subvector (v8f32 %vreg0), Constant<4>),
6036 // In this case the vector is the extract_subvector expression and the index
6037 // is 2, as specified by the shuffle.
6038 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6039 SDValue ShuffleVec = SVOp->getOperand(0);
6040 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6041 assert(ShuffleVecVT.getVectorElementType() ==
6042 ExtractedFromVec.getSimpleValueType().getVectorElementType());
6044 int ShuffleIdx = SVOp->getMaskElt(Idx);
6045 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6046 ExtractedFromVec = ShuffleVec;
6052 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6053 MVT VT = Op.getSimpleValueType();
6055 // Skip if insert_vec_elt is not supported.
6056 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6057 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6061 unsigned NumElems = Op.getNumOperands();
6065 SmallVector<unsigned, 4> InsertIndices;
6066 SmallVector<int, 8> Mask(NumElems, -1);
6068 for (unsigned i = 0; i != NumElems; ++i) {
6069 unsigned Opc = Op.getOperand(i).getOpcode();
6071 if (Opc == ISD::UNDEF)
6074 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6075 // Quit if more than 1 elements need inserting.
6076 if (InsertIndices.size() > 1)
6079 InsertIndices.push_back(i);
6083 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6084 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6085 // Quit if non-constant index.
6086 if (!isa<ConstantSDNode>(ExtIdx))
6088 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6090 // Quit if extracted from vector of different type.
6091 if (ExtractedFromVec.getValueType() != VT)
6094 if (!VecIn1.getNode())
6095 VecIn1 = ExtractedFromVec;
6096 else if (VecIn1 != ExtractedFromVec) {
6097 if (!VecIn2.getNode())
6098 VecIn2 = ExtractedFromVec;
6099 else if (VecIn2 != ExtractedFromVec)
6100 // Quit if more than 2 vectors to shuffle
6104 if (ExtractedFromVec == VecIn1)
6106 else if (ExtractedFromVec == VecIn2)
6107 Mask[i] = Idx + NumElems;
6110 if (!VecIn1.getNode())
6113 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6114 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6115 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6116 unsigned Idx = InsertIndices[i];
6117 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6118 DAG.getIntPtrConstant(Idx));
6124 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6126 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6128 MVT VT = Op.getSimpleValueType();
6129 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6130 "Unexpected type in LowerBUILD_VECTORvXi1!");
6133 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6134 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6135 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6136 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6139 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6140 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6141 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6142 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6145 bool AllContants = true;
6146 uint64_t Immediate = 0;
6147 int NonConstIdx = -1;
6148 bool IsSplat = true;
6149 unsigned NumNonConsts = 0;
6150 unsigned NumConsts = 0;
6151 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6152 SDValue In = Op.getOperand(idx);
6153 if (In.getOpcode() == ISD::UNDEF)
6155 if (!isa<ConstantSDNode>(In)) {
6156 AllContants = false;
6162 if (cast<ConstantSDNode>(In)->getZExtValue())
6163 Immediate |= (1ULL << idx);
6165 if (In != Op.getOperand(0))
6170 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6171 DAG.getConstant(Immediate, MVT::i16));
6172 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6173 DAG.getIntPtrConstant(0));
6176 if (NumNonConsts == 1 && NonConstIdx != 0) {
6179 SDValue VecAsImm = DAG.getConstant(Immediate,
6180 MVT::getIntegerVT(VT.getSizeInBits()));
6181 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6184 DstVec = DAG.getUNDEF(VT);
6185 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6186 Op.getOperand(NonConstIdx),
6187 DAG.getIntPtrConstant(NonConstIdx));
6189 if (!IsSplat && (NonConstIdx != 0))
6190 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6191 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6194 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6195 DAG.getConstant(-1, SelectVT),
6196 DAG.getConstant(0, SelectVT));
6198 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6199 DAG.getConstant((Immediate | 1), SelectVT),
6200 DAG.getConstant(Immediate, SelectVT));
6201 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6204 /// \brief Return true if \p N implements a horizontal binop and return the
6205 /// operands for the horizontal binop into V0 and V1.
6207 /// This is a helper function of PerformBUILD_VECTORCombine.
6208 /// This function checks that the build_vector \p N in input implements a
6209 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6210 /// operation to match.
6211 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6212 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6213 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6216 /// This function only analyzes elements of \p N whose indices are
6217 /// in range [BaseIdx, LastIdx).
6218 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6220 unsigned BaseIdx, unsigned LastIdx,
6221 SDValue &V0, SDValue &V1) {
6222 EVT VT = N->getValueType(0);
6224 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6225 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6226 "Invalid Vector in input!");
6228 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6229 bool CanFold = true;
6230 unsigned ExpectedVExtractIdx = BaseIdx;
6231 unsigned NumElts = LastIdx - BaseIdx;
6232 V0 = DAG.getUNDEF(VT);
6233 V1 = DAG.getUNDEF(VT);
6235 // Check if N implements a horizontal binop.
6236 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6237 SDValue Op = N->getOperand(i + BaseIdx);
6240 if (Op->getOpcode() == ISD::UNDEF) {
6241 // Update the expected vector extract index.
6242 if (i * 2 == NumElts)
6243 ExpectedVExtractIdx = BaseIdx;
6244 ExpectedVExtractIdx += 2;
6248 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6253 SDValue Op0 = Op.getOperand(0);
6254 SDValue Op1 = Op.getOperand(1);
6256 // Try to match the following pattern:
6257 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6258 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6259 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6260 Op0.getOperand(0) == Op1.getOperand(0) &&
6261 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6262 isa<ConstantSDNode>(Op1.getOperand(1)));
6266 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6267 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6269 if (i * 2 < NumElts) {
6270 if (V0.getOpcode() == ISD::UNDEF)
6271 V0 = Op0.getOperand(0);
6273 if (V1.getOpcode() == ISD::UNDEF)
6274 V1 = Op0.getOperand(0);
6275 if (i * 2 == NumElts)
6276 ExpectedVExtractIdx = BaseIdx;
6279 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6280 if (I0 == ExpectedVExtractIdx)
6281 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6282 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6283 // Try to match the following dag sequence:
6284 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6285 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6289 ExpectedVExtractIdx += 2;
6295 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6296 /// a concat_vector.
6298 /// This is a helper function of PerformBUILD_VECTORCombine.
6299 /// This function expects two 256-bit vectors called V0 and V1.
6300 /// At first, each vector is split into two separate 128-bit vectors.
6301 /// Then, the resulting 128-bit vectors are used to implement two
6302 /// horizontal binary operations.
6304 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6306 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6307 /// the two new horizontal binop.
6308 /// When Mode is set, the first horizontal binop dag node would take as input
6309 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6310 /// horizontal binop dag node would take as input the lower 128-bit of V1
6311 /// and the upper 128-bit of V1.
6313 /// HADD V0_LO, V0_HI
6314 /// HADD V1_LO, V1_HI
6316 /// Otherwise, the first horizontal binop dag node takes as input the lower
6317 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6318 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6320 /// HADD V0_LO, V1_LO
6321 /// HADD V0_HI, V1_HI
6323 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6324 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6325 /// the upper 128-bits of the result.
6326 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6327 SDLoc DL, SelectionDAG &DAG,
6328 unsigned X86Opcode, bool Mode,
6329 bool isUndefLO, bool isUndefHI) {
6330 EVT VT = V0.getValueType();
6331 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6332 "Invalid nodes in input!");
6334 unsigned NumElts = VT.getVectorNumElements();
6335 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6336 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6337 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6338 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6339 EVT NewVT = V0_LO.getValueType();
6341 SDValue LO = DAG.getUNDEF(NewVT);
6342 SDValue HI = DAG.getUNDEF(NewVT);
6345 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6346 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6347 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6348 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6349 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6351 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6352 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6353 V1_LO->getOpcode() != ISD::UNDEF))
6354 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6356 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6357 V1_HI->getOpcode() != ISD::UNDEF))
6358 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6361 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6364 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6365 /// sequence of 'vadd + vsub + blendi'.
6366 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6367 const X86Subtarget *Subtarget) {
6369 EVT VT = BV->getValueType(0);
6370 unsigned NumElts = VT.getVectorNumElements();
6371 SDValue InVec0 = DAG.getUNDEF(VT);
6372 SDValue InVec1 = DAG.getUNDEF(VT);
6374 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6375 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6377 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6378 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6379 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6382 // Odd-numbered elements in the input build vector are obtained from
6383 // adding two integer/float elements.
6384 // Even-numbered elements in the input build vector are obtained from
6385 // subtracting two integer/float elements.
6386 unsigned ExpectedOpcode = ISD::FSUB;
6387 unsigned NextExpectedOpcode = ISD::FADD;
6388 bool AddFound = false;
6389 bool SubFound = false;
6391 for (unsigned i = 0, e = NumElts; i != e; i++) {
6392 SDValue Op = BV->getOperand(i);
6394 // Skip 'undef' values.
6395 unsigned Opcode = Op.getOpcode();
6396 if (Opcode == ISD::UNDEF) {
6397 std::swap(ExpectedOpcode, NextExpectedOpcode);
6401 // Early exit if we found an unexpected opcode.
6402 if (Opcode != ExpectedOpcode)
6405 SDValue Op0 = Op.getOperand(0);
6406 SDValue Op1 = Op.getOperand(1);
6408 // Try to match the following pattern:
6409 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6410 // Early exit if we cannot match that sequence.
6411 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6412 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6413 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6414 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6415 Op0.getOperand(1) != Op1.getOperand(1))
6418 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6422 // We found a valid add/sub node. Update the information accordingly.
6428 // Update InVec0 and InVec1.
6429 if (InVec0.getOpcode() == ISD::UNDEF)
6430 InVec0 = Op0.getOperand(0);
6431 if (InVec1.getOpcode() == ISD::UNDEF)
6432 InVec1 = Op1.getOperand(0);
6434 // Make sure that operands in input to each add/sub node always
6435 // come from a same pair of vectors.
6436 if (InVec0 != Op0.getOperand(0)) {
6437 if (ExpectedOpcode == ISD::FSUB)
6440 // FADD is commutable. Try to commute the operands
6441 // and then test again.
6442 std::swap(Op0, Op1);
6443 if (InVec0 != Op0.getOperand(0))
6447 if (InVec1 != Op1.getOperand(0))
6450 // Update the pair of expected opcodes.
6451 std::swap(ExpectedOpcode, NextExpectedOpcode);
6454 // Don't try to fold this build_vector into a VSELECT if it has
6455 // too many UNDEF operands.
6456 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6457 InVec1.getOpcode() != ISD::UNDEF) {
6458 // Emit a sequence of vector add and sub followed by a VSELECT.
6459 // The new VSELECT will be lowered into a BLENDI.
6460 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6461 // and emit a single ADDSUB instruction.
6462 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6463 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6465 // Construct the VSELECT mask.
6466 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6467 EVT SVT = MaskVT.getVectorElementType();
6468 unsigned SVTBits = SVT.getSizeInBits();
6469 SmallVector<SDValue, 8> Ops;
6471 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6472 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6473 APInt::getAllOnesValue(SVTBits);
6474 SDValue Constant = DAG.getConstant(Value, SVT);
6475 Ops.push_back(Constant);
6478 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6479 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6485 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6486 const X86Subtarget *Subtarget) {
6488 EVT VT = N->getValueType(0);
6489 unsigned NumElts = VT.getVectorNumElements();
6490 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6491 SDValue InVec0, InVec1;
6493 // Try to match an ADDSUB.
6494 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6495 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6496 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6497 if (Value.getNode())
6501 // Try to match horizontal ADD/SUB.
6502 unsigned NumUndefsLO = 0;
6503 unsigned NumUndefsHI = 0;
6504 unsigned Half = NumElts/2;
6506 // Count the number of UNDEF operands in the build_vector in input.
6507 for (unsigned i = 0, e = Half; i != e; ++i)
6508 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6511 for (unsigned i = Half, e = NumElts; i != e; ++i)
6512 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6515 // Early exit if this is either a build_vector of all UNDEFs or all the
6516 // operands but one are UNDEF.
6517 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6520 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6521 // Try to match an SSE3 float HADD/HSUB.
6522 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6523 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6525 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6526 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6527 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6528 // Try to match an SSSE3 integer HADD/HSUB.
6529 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6530 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6532 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6533 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6536 if (!Subtarget->hasAVX())
6539 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6540 // Try to match an AVX horizontal add/sub of packed single/double
6541 // precision floating point values from 256-bit vectors.
6542 SDValue InVec2, InVec3;
6543 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6544 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6545 ((InVec0.getOpcode() == ISD::UNDEF ||
6546 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6547 ((InVec1.getOpcode() == ISD::UNDEF ||
6548 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6549 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6551 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6552 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6553 ((InVec0.getOpcode() == ISD::UNDEF ||
6554 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6555 ((InVec1.getOpcode() == ISD::UNDEF ||
6556 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6557 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6558 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6559 // Try to match an AVX2 horizontal add/sub of signed integers.
6560 SDValue InVec2, InVec3;
6562 bool CanFold = true;
6564 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6565 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6566 ((InVec0.getOpcode() == ISD::UNDEF ||
6567 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6568 ((InVec1.getOpcode() == ISD::UNDEF ||
6569 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6570 X86Opcode = X86ISD::HADD;
6571 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6572 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6573 ((InVec0.getOpcode() == ISD::UNDEF ||
6574 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6575 ((InVec1.getOpcode() == ISD::UNDEF ||
6576 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6577 X86Opcode = X86ISD::HSUB;
6582 // Fold this build_vector into a single horizontal add/sub.
6583 // Do this only if the target has AVX2.
6584 if (Subtarget->hasAVX2())
6585 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6587 // Do not try to expand this build_vector into a pair of horizontal
6588 // add/sub if we can emit a pair of scalar add/sub.
6589 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6592 // Convert this build_vector into a pair of horizontal binop followed by
6594 bool isUndefLO = NumUndefsLO == Half;
6595 bool isUndefHI = NumUndefsHI == Half;
6596 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6597 isUndefLO, isUndefHI);
6601 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6602 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6604 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6605 X86Opcode = X86ISD::HADD;
6606 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6607 X86Opcode = X86ISD::HSUB;
6608 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6609 X86Opcode = X86ISD::FHADD;
6610 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6611 X86Opcode = X86ISD::FHSUB;
6615 // Don't try to expand this build_vector into a pair of horizontal add/sub
6616 // if we can simply emit a pair of scalar add/sub.
6617 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6620 // Convert this build_vector into two horizontal add/sub followed by
6622 bool isUndefLO = NumUndefsLO == Half;
6623 bool isUndefHI = NumUndefsHI == Half;
6624 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6625 isUndefLO, isUndefHI);
6632 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6635 MVT VT = Op.getSimpleValueType();
6636 MVT ExtVT = VT.getVectorElementType();
6637 unsigned NumElems = Op.getNumOperands();
6639 // Generate vectors for predicate vectors.
6640 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6641 return LowerBUILD_VECTORvXi1(Op, DAG);
6643 // Vectors containing all zeros can be matched by pxor and xorps later
6644 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6645 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6646 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6647 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6650 return getZeroVector(VT, Subtarget, DAG, dl);
6653 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6654 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6655 // vpcmpeqd on 256-bit vectors.
6656 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6657 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6660 if (!VT.is512BitVector())
6661 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6664 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6665 if (Broadcast.getNode())
6668 unsigned EVTBits = ExtVT.getSizeInBits();
6670 unsigned NumZero = 0;
6671 unsigned NumNonZero = 0;
6672 unsigned NonZeros = 0;
6673 bool IsAllConstants = true;
6674 SmallSet<SDValue, 8> Values;
6675 for (unsigned i = 0; i < NumElems; ++i) {
6676 SDValue Elt = Op.getOperand(i);
6677 if (Elt.getOpcode() == ISD::UNDEF)
6680 if (Elt.getOpcode() != ISD::Constant &&
6681 Elt.getOpcode() != ISD::ConstantFP)
6682 IsAllConstants = false;
6683 if (X86::isZeroNode(Elt))
6686 NonZeros |= (1 << i);
6691 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6692 if (NumNonZero == 0)
6693 return DAG.getUNDEF(VT);
6695 // Special case for single non-zero, non-undef, element.
6696 if (NumNonZero == 1) {
6697 unsigned Idx = countTrailingZeros(NonZeros);
6698 SDValue Item = Op.getOperand(Idx);
6700 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6701 // the value are obviously zero, truncate the value to i32 and do the
6702 // insertion that way. Only do this if the value is non-constant or if the
6703 // value is a constant being inserted into element 0. It is cheaper to do
6704 // a constant pool load than it is to do a movd + shuffle.
6705 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6706 (!IsAllConstants || Idx == 0)) {
6707 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6709 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6710 EVT VecVT = MVT::v4i32;
6711 unsigned VecElts = 4;
6713 // Truncate the value (which may itself be a constant) to i32, and
6714 // convert it to a vector with movd (S2V+shuffle to zero extend).
6715 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6716 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6717 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6719 // Now we have our 32-bit value zero extended in the low element of
6720 // a vector. If Idx != 0, swizzle it into place.
6722 SmallVector<int, 4> Mask;
6723 Mask.push_back(Idx);
6724 for (unsigned i = 1; i != VecElts; ++i)
6726 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6729 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6733 // If we have a constant or non-constant insertion into the low element of
6734 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6735 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6736 // depending on what the source datatype is.
6739 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6741 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6742 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6743 if (VT.is256BitVector() || VT.is512BitVector()) {
6744 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6745 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6746 Item, DAG.getIntPtrConstant(0));
6748 assert(VT.is128BitVector() && "Expected an SSE value type!");
6749 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6750 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6751 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6754 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6755 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6756 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6757 if (VT.is256BitVector()) {
6758 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6759 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6761 assert(VT.is128BitVector() && "Expected an SSE value type!");
6762 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6764 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6768 // Is it a vector logical left shift?
6769 if (NumElems == 2 && Idx == 1 &&
6770 X86::isZeroNode(Op.getOperand(0)) &&
6771 !X86::isZeroNode(Op.getOperand(1))) {
6772 unsigned NumBits = VT.getSizeInBits();
6773 return getVShift(true, VT,
6774 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6775 VT, Op.getOperand(1)),
6776 NumBits/2, DAG, *this, dl);
6779 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6782 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6783 // is a non-constant being inserted into an element other than the low one,
6784 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6785 // movd/movss) to move this into the low element, then shuffle it into
6787 if (EVTBits == 32) {
6788 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6790 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6791 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6792 SmallVector<int, 8> MaskVec;
6793 for (unsigned i = 0; i != NumElems; ++i)
6794 MaskVec.push_back(i == Idx ? 0 : 1);
6795 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6799 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6800 if (Values.size() == 1) {
6801 if (EVTBits == 32) {
6802 // Instead of a shuffle like this:
6803 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6804 // Check if it's possible to issue this instead.
6805 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6806 unsigned Idx = countTrailingZeros(NonZeros);
6807 SDValue Item = Op.getOperand(Idx);
6808 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6809 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6814 // A vector full of immediates; various special cases are already
6815 // handled, so this is best done with a single constant-pool load.
6819 // For AVX-length vectors, build the individual 128-bit pieces and use
6820 // shuffles to put them in place.
6821 if (VT.is256BitVector() || VT.is512BitVector()) {
6822 SmallVector<SDValue, 64> V;
6823 for (unsigned i = 0; i != NumElems; ++i)
6824 V.push_back(Op.getOperand(i));
6826 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6828 // Build both the lower and upper subvector.
6829 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6830 makeArrayRef(&V[0], NumElems/2));
6831 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6832 makeArrayRef(&V[NumElems / 2], NumElems/2));
6834 // Recreate the wider vector with the lower and upper part.
6835 if (VT.is256BitVector())
6836 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6837 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6840 // Let legalizer expand 2-wide build_vectors.
6841 if (EVTBits == 64) {
6842 if (NumNonZero == 1) {
6843 // One half is zero or undef.
6844 unsigned Idx = countTrailingZeros(NonZeros);
6845 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6846 Op.getOperand(Idx));
6847 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6852 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6853 if (EVTBits == 8 && NumElems == 16) {
6854 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6856 if (V.getNode()) return V;
6859 if (EVTBits == 16 && NumElems == 8) {
6860 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6862 if (V.getNode()) return V;
6865 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6866 if (EVTBits == 32 && NumElems == 4) {
6867 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6868 NumZero, DAG, Subtarget, *this);
6873 // If element VT is == 32 bits, turn it into a number of shuffles.
6874 SmallVector<SDValue, 8> V(NumElems);
6875 if (NumElems == 4 && NumZero > 0) {
6876 for (unsigned i = 0; i < 4; ++i) {
6877 bool isZero = !(NonZeros & (1 << i));
6879 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6881 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6884 for (unsigned i = 0; i < 2; ++i) {
6885 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6888 V[i] = V[i*2]; // Must be a zero vector.
6891 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6894 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6897 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6902 bool Reverse1 = (NonZeros & 0x3) == 2;
6903 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6907 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6908 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6910 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6913 if (Values.size() > 1 && VT.is128BitVector()) {
6914 // Check for a build vector of consecutive loads.
6915 for (unsigned i = 0; i < NumElems; ++i)
6916 V[i] = Op.getOperand(i);
6918 // Check for elements which are consecutive loads.
6919 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6923 // Check for a build vector from mostly shuffle plus few inserting.
6924 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6928 // For SSE 4.1, use insertps to put the high elements into the low element.
6929 if (getSubtarget()->hasSSE41()) {
6931 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6932 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6934 Result = DAG.getUNDEF(VT);
6936 for (unsigned i = 1; i < NumElems; ++i) {
6937 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6938 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6939 Op.getOperand(i), DAG.getIntPtrConstant(i));
6944 // Otherwise, expand into a number of unpckl*, start by extending each of
6945 // our (non-undef) elements to the full vector width with the element in the
6946 // bottom slot of the vector (which generates no code for SSE).
6947 for (unsigned i = 0; i < NumElems; ++i) {
6948 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6949 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6951 V[i] = DAG.getUNDEF(VT);
6954 // Next, we iteratively mix elements, e.g. for v4f32:
6955 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6956 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6957 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6958 unsigned EltStride = NumElems >> 1;
6959 while (EltStride != 0) {
6960 for (unsigned i = 0; i < EltStride; ++i) {
6961 // If V[i+EltStride] is undef and this is the first round of mixing,
6962 // then it is safe to just drop this shuffle: V[i] is already in the
6963 // right place, the one element (since it's the first round) being
6964 // inserted as undef can be dropped. This isn't safe for successive
6965 // rounds because they will permute elements within both vectors.
6966 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6967 EltStride == NumElems/2)
6970 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6979 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6980 // to create 256-bit vectors from two other 128-bit ones.
6981 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6983 MVT ResVT = Op.getSimpleValueType();
6985 assert((ResVT.is256BitVector() ||
6986 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6988 SDValue V1 = Op.getOperand(0);
6989 SDValue V2 = Op.getOperand(1);
6990 unsigned NumElems = ResVT.getVectorNumElements();
6991 if(ResVT.is256BitVector())
6992 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6994 if (Op.getNumOperands() == 4) {
6995 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6996 ResVT.getVectorNumElements()/2);
6997 SDValue V3 = Op.getOperand(2);
6998 SDValue V4 = Op.getOperand(3);
6999 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7000 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7002 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7005 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7006 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7007 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7008 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7009 Op.getNumOperands() == 4)));
7011 // AVX can use the vinsertf128 instruction to create 256-bit vectors
7012 // from two other 128-bit ones.
7014 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7015 return LowerAVXCONCAT_VECTORS(Op, DAG);
7019 //===----------------------------------------------------------------------===//
7020 // Vector shuffle lowering
7022 // This is an experimental code path for lowering vector shuffles on x86. It is
7023 // designed to handle arbitrary vector shuffles and blends, gracefully
7024 // degrading performance as necessary. It works hard to recognize idiomatic
7025 // shuffles and lower them to optimal instruction patterns without leaving
7026 // a framework that allows reasonably efficient handling of all vector shuffle
7028 //===----------------------------------------------------------------------===//
7030 /// \brief Tiny helper function to identify a no-op mask.
7032 /// This is a somewhat boring predicate function. It checks whether the mask
7033 /// array input, which is assumed to be a single-input shuffle mask of the kind
7034 /// used by the X86 shuffle instructions (not a fully general
7035 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7036 /// in-place shuffle are 'no-op's.
7037 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7038 for (int i = 0, Size = Mask.size(); i < Size; ++i)
7039 if (Mask[i] != -1 && Mask[i] != i)
7044 /// \brief Helper function to classify a mask as a single-input mask.
7046 /// This isn't a generic single-input test because in the vector shuffle
7047 /// lowering we canonicalize single inputs to be the first input operand. This
7048 /// means we can more quickly test for a single input by only checking whether
7049 /// an input from the second operand exists. We also assume that the size of
7050 /// mask corresponds to the size of the input vectors which isn't true in the
7051 /// fully general case.
7052 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7054 if (M >= (int)Mask.size())
7059 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7060 // 2013 will allow us to use it as a non-type template parameter.
7063 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7065 /// See its documentation for details.
7066 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7067 if (Mask.size() != Args.size())
7069 for (int i = 0, e = Mask.size(); i < e; ++i) {
7070 assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7071 assert(*Args[i] < (int)Args.size() * 2 &&
7072 "Argument outside the range of possible shuffle inputs!");
7073 if (Mask[i] != -1 && Mask[i] != *Args[i])
7081 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7084 /// This is a fast way to test a shuffle mask against a fixed pattern:
7086 /// if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7088 /// It returns true if the mask is exactly as wide as the argument list, and
7089 /// each element of the mask is either -1 (signifying undef) or the value given
7090 /// in the argument.
7091 static const VariadicFunction1<
7092 bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7094 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7096 /// This helper function produces an 8-bit shuffle immediate corresponding to
7097 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7098 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7101 /// NB: We rely heavily on "undef" masks preserving the input lane.
7102 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7103 SelectionDAG &DAG) {
7104 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7105 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7106 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7107 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7108 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7111 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7112 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7113 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7114 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7115 return DAG.getConstant(Imm, MVT::i8);
7118 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7120 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7121 /// support for floating point shuffles but not integer shuffles. These
7122 /// instructions will incur a domain crossing penalty on some chips though so
7123 /// it is better to avoid lowering through this for integer vectors where
7125 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7126 const X86Subtarget *Subtarget,
7127 SelectionDAG &DAG) {
7129 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7130 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7131 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7132 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7133 ArrayRef<int> Mask = SVOp->getMask();
7134 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7136 if (isSingleInputShuffleMask(Mask)) {
7137 // Straight shuffle of a single input vector. Simulate this by using the
7138 // single input as both of the "inputs" to this instruction..
7139 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7140 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7141 DAG.getConstant(SHUFPDMask, MVT::i8));
7143 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7144 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7146 // Use dedicated unpack instructions for masks that match their pattern.
7147 if (isShuffleEquivalent(Mask, 0, 2))
7148 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7149 if (isShuffleEquivalent(Mask, 1, 3))
7150 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7152 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7153 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7154 DAG.getConstant(SHUFPDMask, MVT::i8));
7157 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7159 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7160 /// the integer unit to minimize domain crossing penalties. However, for blends
7161 /// it falls back to the floating point shuffle operation with appropriate bit
7163 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7164 const X86Subtarget *Subtarget,
7165 SelectionDAG &DAG) {
7167 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7168 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7169 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7170 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7171 ArrayRef<int> Mask = SVOp->getMask();
7172 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7174 if (isSingleInputShuffleMask(Mask)) {
7175 // Straight shuffle of a single input vector. For everything from SSE2
7176 // onward this has a single fast instruction with no scary immediates.
7177 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7178 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7179 int WidenedMask[4] = {
7180 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7181 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7183 ISD::BITCAST, DL, MVT::v2i64,
7184 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7185 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7188 // Use dedicated unpack instructions for masks that match their pattern.
7189 if (isShuffleEquivalent(Mask, 0, 2))
7190 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7191 if (isShuffleEquivalent(Mask, 1, 3))
7192 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7194 // We implement this with SHUFPD which is pretty lame because it will likely
7195 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7196 // However, all the alternatives are still more cycles and newer chips don't
7197 // have this problem. It would be really nice if x86 had better shuffles here.
7198 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7199 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7200 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7201 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7204 /// \brief Lower 4-lane 32-bit floating point shuffles.
7206 /// Uses instructions exclusively from the floating point unit to minimize
7207 /// domain crossing penalties, as these are sufficient to implement all v4f32
7209 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7210 const X86Subtarget *Subtarget,
7211 SelectionDAG &DAG) {
7213 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7214 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7215 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7216 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7217 ArrayRef<int> Mask = SVOp->getMask();
7218 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7220 SDValue LowV = V1, HighV = V2;
7221 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7224 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7226 if (NumV2Elements == 0)
7227 // Straight shuffle of a single input vector. We pass the input vector to
7228 // both operands to simulate this with a SHUFPS.
7229 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7230 getV4X86ShuffleImm8ForMask(Mask, DAG));
7232 // Use dedicated unpack instructions for masks that match their pattern.
7233 if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7234 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7235 if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7236 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7238 if (NumV2Elements == 1) {
7240 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7242 // Compute the index adjacent to V2Index and in the same half by toggling
7244 int V2AdjIndex = V2Index ^ 1;
7246 if (Mask[V2AdjIndex] == -1) {
7247 // Handles all the cases where we have a single V2 element and an undef.
7248 // This will only ever happen in the high lanes because we commute the
7249 // vector otherwise.
7251 std::swap(LowV, HighV);
7252 NewMask[V2Index] -= 4;
7254 // Handle the case where the V2 element ends up adjacent to a V1 element.
7255 // To make this work, blend them together as the first step.
7256 int V1Index = V2AdjIndex;
7257 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7258 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7259 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7261 // Now proceed to reconstruct the final blend as we have the necessary
7262 // high or low half formed.
7269 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7270 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7272 } else if (NumV2Elements == 2) {
7273 if (Mask[0] < 4 && Mask[1] < 4) {
7274 // Handle the easy case where we have V1 in the low lanes and V2 in the
7275 // high lanes. We never see this reversed because we sort the shuffle.
7279 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7280 // trying to place elements directly, just blend them and set up the final
7281 // shuffle to place them.
7283 // The first two blend mask elements are for V1, the second two are for
7285 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7286 Mask[2] < 4 ? Mask[2] : Mask[3],
7287 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7288 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7289 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7290 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7292 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7295 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7296 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7297 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7298 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7301 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7302 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7305 /// \brief Lower 4-lane i32 vector shuffles.
7307 /// We try to handle these with integer-domain shuffles where we can, but for
7308 /// blends we use the floating point domain blend instructions.
7309 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7310 const X86Subtarget *Subtarget,
7311 SelectionDAG &DAG) {
7313 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7314 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7315 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7316 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7317 ArrayRef<int> Mask = SVOp->getMask();
7318 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7320 if (isSingleInputShuffleMask(Mask))
7321 // Straight shuffle of a single input vector. For everything from SSE2
7322 // onward this has a single fast instruction with no scary immediates.
7323 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7324 getV4X86ShuffleImm8ForMask(Mask, DAG));
7326 // Use dedicated unpack instructions for masks that match their pattern.
7327 if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7328 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7329 if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7330 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7332 // We implement this with SHUFPS because it can blend from two vectors.
7333 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7334 // up the inputs, bypassing domain shift penalties that we would encur if we
7335 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7337 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7338 DAG.getVectorShuffle(
7340 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7341 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7344 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7345 /// shuffle lowering, and the most complex part.
7347 /// The lowering strategy is to try to form pairs of input lanes which are
7348 /// targeted at the same half of the final vector, and then use a dword shuffle
7349 /// to place them onto the right half, and finally unpack the paired lanes into
7350 /// their final position.
7352 /// The exact breakdown of how to form these dword pairs and align them on the
7353 /// correct sides is really tricky. See the comments within the function for
7354 /// more of the details.
7355 static SDValue lowerV8I16SingleInputVectorShuffle(
7356 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7357 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7358 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7359 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7360 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7362 SmallVector<int, 4> LoInputs;
7363 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7364 [](int M) { return M >= 0; });
7365 std::sort(LoInputs.begin(), LoInputs.end());
7366 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7367 SmallVector<int, 4> HiInputs;
7368 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7369 [](int M) { return M >= 0; });
7370 std::sort(HiInputs.begin(), HiInputs.end());
7371 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7373 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7374 int NumHToL = LoInputs.size() - NumLToL;
7376 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7377 int NumHToH = HiInputs.size() - NumLToH;
7378 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7379 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7380 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7381 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7383 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7384 // such inputs we can swap two of the dwords across the half mark and end up
7385 // with <=2 inputs to each half in each half. Once there, we can fall through
7386 // to the generic code below. For example:
7388 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7389 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7391 // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7392 // and an existing 2-into-2 on the other half. In this case we may have to
7393 // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7394 // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7395 // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7396 // because any other situation (including a 3-into-1 or 1-into-3 in the other
7397 // half than the one we target for fixing) will be fixed when we re-enter this
7398 // path. We will also combine away any sequence of PSHUFD instructions that
7399 // result into a single instruction. Here is an example of the tricky case:
7401 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7402 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7404 // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7406 // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7407 // Mask: [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7409 // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7410 // Mask: [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7412 // The result is fine to be handled by the generic logic.
7413 auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7414 ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7415 int AOffset, int BOffset) {
7416 assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7417 "Must call this with A having 3 or 1 inputs from the A half.");
7418 assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7419 "Must call this with B having 1 or 3 inputs from the B half.");
7420 assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7421 "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7423 // Compute the index of dword with only one word among the three inputs in
7424 // a half by taking the sum of the half with three inputs and subtracting
7425 // the sum of the actual three inputs. The difference is the remaining
7428 int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7429 int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7430 int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7431 ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7432 int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7433 int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7434 int TripleNonInputIdx =
7435 TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7436 TripleDWord = TripleNonInputIdx / 2;
7438 // We use xor with one to compute the adjacent DWord to whichever one the
7440 OneInputDWord = (OneInput / 2) ^ 1;
7442 // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7443 // and BToA inputs. If there is also such a problem with the BToB and AToB
7444 // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7445 // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7446 // is essential that we don't *create* a 3<-1 as then we might oscillate.
7447 if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7448 // Compute how many inputs will be flipped by swapping these DWords. We
7450 // to balance this to ensure we don't form a 3-1 shuffle in the other
7452 int NumFlippedAToBInputs =
7453 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7454 std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7455 int NumFlippedBToBInputs =
7456 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7457 std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7458 if ((NumFlippedAToBInputs == 1 &&
7459 (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7460 (NumFlippedBToBInputs == 1 &&
7461 (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7462 // We choose whether to fix the A half or B half based on whether that
7463 // half has zero flipped inputs. At zero, we may not be able to fix it
7464 // with that half. We also bias towards fixing the B half because that
7465 // will more commonly be the high half, and we have to bias one way.
7466 auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7467 ArrayRef<int> Inputs) {
7468 int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7469 bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7470 PinnedIdx ^ 1) != Inputs.end();
7471 // Determine whether the free index is in the flipped dword or the
7472 // unflipped dword based on where the pinned index is. We use this bit
7473 // in an xor to conditionally select the adjacent dword.
7474 int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7475 bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7476 FixFreeIdx) != Inputs.end();
7477 if (IsFixIdxInput == IsFixFreeIdxInput)
7479 IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7480 FixFreeIdx) != Inputs.end();
7481 assert(IsFixIdxInput != IsFixFreeIdxInput &&
7482 "We need to be changing the number of flipped inputs!");
7483 int PSHUFHalfMask[] = {0, 1, 2, 3};
7484 std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7485 V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7487 getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7490 if (M != -1 && M == FixIdx)
7492 else if (M != -1 && M == FixFreeIdx)
7495 if (NumFlippedBToBInputs != 0) {
7497 BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7498 FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7500 assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7502 AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7503 FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7508 int PSHUFDMask[] = {0, 1, 2, 3};
7509 PSHUFDMask[ADWord] = BDWord;
7510 PSHUFDMask[BDWord] = ADWord;
7511 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7512 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7513 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7514 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7516 // Adjust the mask to match the new locations of A and B.
7518 if (M != -1 && M/2 == ADWord)
7519 M = 2 * BDWord + M % 2;
7520 else if (M != -1 && M/2 == BDWord)
7521 M = 2 * ADWord + M % 2;
7523 // Recurse back into this routine to re-compute state now that this isn't
7524 // a 3 and 1 problem.
7525 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7528 if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7529 return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7530 else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7531 return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7533 // At this point there are at most two inputs to the low and high halves from
7534 // each half. That means the inputs can always be grouped into dwords and
7535 // those dwords can then be moved to the correct half with a dword shuffle.
7536 // We use at most one low and one high word shuffle to collect these paired
7537 // inputs into dwords, and finally a dword shuffle to place them.
7538 int PSHUFLMask[4] = {-1, -1, -1, -1};
7539 int PSHUFHMask[4] = {-1, -1, -1, -1};
7540 int PSHUFDMask[4] = {-1, -1, -1, -1};
7542 // First fix the masks for all the inputs that are staying in their
7543 // original halves. This will then dictate the targets of the cross-half
7545 auto fixInPlaceInputs =
7546 [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7547 MutableArrayRef<int> SourceHalfMask,
7548 MutableArrayRef<int> HalfMask, int HalfOffset) {
7549 if (InPlaceInputs.empty())
7551 if (InPlaceInputs.size() == 1) {
7552 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7553 InPlaceInputs[0] - HalfOffset;
7554 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7557 if (IncomingInputs.empty()) {
7558 // Just fix all of the in place inputs.
7559 for (int Input : InPlaceInputs) {
7560 SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7561 PSHUFDMask[Input / 2] = Input / 2;
7566 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7567 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7568 InPlaceInputs[0] - HalfOffset;
7569 // Put the second input next to the first so that they are packed into
7570 // a dword. We find the adjacent index by toggling the low bit.
7571 int AdjIndex = InPlaceInputs[0] ^ 1;
7572 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7573 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7574 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7576 fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7577 fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7579 // Now gather the cross-half inputs and place them into a free dword of
7580 // their target half.
7581 // FIXME: This operation could almost certainly be simplified dramatically to
7582 // look more like the 3-1 fixing operation.
7583 auto moveInputsToRightHalf = [&PSHUFDMask](
7584 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7585 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7586 MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7588 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7589 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7591 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7593 int LowWord = Word & ~1;
7594 int HighWord = Word | 1;
7595 return isWordClobbered(SourceHalfMask, LowWord) ||
7596 isWordClobbered(SourceHalfMask, HighWord);
7599 if (IncomingInputs.empty())
7602 if (ExistingInputs.empty()) {
7603 // Map any dwords with inputs from them into the right half.
7604 for (int Input : IncomingInputs) {
7605 // If the source half mask maps over the inputs, turn those into
7606 // swaps and use the swapped lane.
7607 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7608 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7609 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7610 Input - SourceOffset;
7611 // We have to swap the uses in our half mask in one sweep.
7612 for (int &M : HalfMask)
7613 if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7615 else if (M == Input)
7616 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7618 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7619 Input - SourceOffset &&
7620 "Previous placement doesn't match!");
7622 // Note that this correctly re-maps both when we do a swap and when
7623 // we observe the other side of the swap above. We rely on that to
7624 // avoid swapping the members of the input list directly.
7625 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7628 // Map the input's dword into the correct half.
7629 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7630 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7632 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7634 "Previous placement doesn't match!");
7637 // And just directly shift any other-half mask elements to be same-half
7638 // as we will have mirrored the dword containing the element into the
7639 // same position within that half.
7640 for (int &M : HalfMask)
7641 if (M >= SourceOffset && M < SourceOffset + 4) {
7642 M = M - SourceOffset + DestOffset;
7643 assert(M >= 0 && "This should never wrap below zero!");
7648 // Ensure we have the input in a viable dword of its current half. This
7649 // is particularly tricky because the original position may be clobbered
7650 // by inputs being moved and *staying* in that half.
7651 if (IncomingInputs.size() == 1) {
7652 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7653 int InputFixed = std::find(std::begin(SourceHalfMask),
7654 std::end(SourceHalfMask), -1) -
7655 std::begin(SourceHalfMask) + SourceOffset;
7656 SourceHalfMask[InputFixed - SourceOffset] =
7657 IncomingInputs[0] - SourceOffset;
7658 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7660 IncomingInputs[0] = InputFixed;
7662 } else if (IncomingInputs.size() == 2) {
7663 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7664 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7665 // We have two non-adjacent or clobbered inputs we need to extract from
7666 // the source half. To do this, we need to map them into some adjacent
7667 // dword slot in the source mask.
7668 int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7669 IncomingInputs[1] - SourceOffset};
7671 // If there is a free slot in the source half mask adjacent to one of
7672 // the inputs, place the other input in it. We use (Index XOR 1) to
7673 // compute an adjacent index.
7674 if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7675 SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7676 SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7677 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7678 InputsFixed[1] = InputsFixed[0] ^ 1;
7679 } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7680 SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7681 SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7682 SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7683 InputsFixed[0] = InputsFixed[1] ^ 1;
7684 } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7685 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7686 // The two inputs are in the same DWord but it is clobbered and the
7687 // adjacent DWord isn't used at all. Move both inputs to the free
7689 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7690 SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
7691 InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
7692 InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
7694 // The only way we hit this point is if there is no clobbering
7695 // (because there are no off-half inputs to this half) and there is no
7696 // free slot adjacent to one of the inputs. In this case, we have to
7697 // swap an input with a non-input.
7698 for (int i = 0; i < 4; ++i)
7699 assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
7700 "We can't handle any clobbers here!");
7701 assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
7702 "Cannot have adjacent inputs here!");
7704 SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7705 SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
7707 // We also have to update the final source mask in this case because
7708 // it may need to undo the above swap.
7709 for (int &M : FinalSourceHalfMask)
7710 if (M == (InputsFixed[0] ^ 1) + SourceOffset)
7711 M = InputsFixed[1] + SourceOffset;
7712 else if (M == InputsFixed[1] + SourceOffset)
7713 M = (InputsFixed[0] ^ 1) + SourceOffset;
7715 InputsFixed[1] = InputsFixed[0] ^ 1;
7718 // Point everything at the fixed inputs.
7719 for (int &M : HalfMask)
7720 if (M == IncomingInputs[0])
7721 M = InputsFixed[0] + SourceOffset;
7722 else if (M == IncomingInputs[1])
7723 M = InputsFixed[1] + SourceOffset;
7725 IncomingInputs[0] = InputsFixed[0] + SourceOffset;
7726 IncomingInputs[1] = InputsFixed[1] + SourceOffset;
7729 llvm_unreachable("Unhandled input size!");
7732 // Now hoist the DWord down to the right half.
7733 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7734 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7735 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7736 for (int &M : HalfMask)
7737 for (int Input : IncomingInputs)
7739 M = FreeDWord * 2 + Input % 2;
7741 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
7742 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7743 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
7744 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7746 // Now enact all the shuffles we've computed to move the inputs into their
7748 if (!isNoopShuffleMask(PSHUFLMask))
7749 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7750 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7751 if (!isNoopShuffleMask(PSHUFHMask))
7752 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7753 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7754 if (!isNoopShuffleMask(PSHUFDMask))
7755 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7756 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7757 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7758 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7760 // At this point, each half should contain all its inputs, and we can then
7761 // just shuffle them into their final position.
7762 assert(std::count_if(LoMask.begin(), LoMask.end(),
7763 [](int M) { return M >= 4; }) == 0 &&
7764 "Failed to lift all the high half inputs to the low mask!");
7765 assert(std::count_if(HiMask.begin(), HiMask.end(),
7766 [](int M) { return M >= 0 && M < 4; }) == 0 &&
7767 "Failed to lift all the low half inputs to the high mask!");
7769 // Do a half shuffle for the low mask.
7770 if (!isNoopShuffleMask(LoMask))
7771 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7772 getV4X86ShuffleImm8ForMask(LoMask, DAG));
7774 // Do a half shuffle with the high mask after shifting its values down.
7775 for (int &M : HiMask)
7778 if (!isNoopShuffleMask(HiMask))
7779 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7780 getV4X86ShuffleImm8ForMask(HiMask, DAG));
7785 /// \brief Detect whether the mask pattern should be lowered through
7788 /// This essentially tests whether viewing the mask as an interleaving of two
7789 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7790 /// lowering it through interleaving is a significantly better strategy.
7791 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7792 int NumEvenInputs[2] = {0, 0};
7793 int NumOddInputs[2] = {0, 0};
7794 int NumLoInputs[2] = {0, 0};
7795 int NumHiInputs[2] = {0, 0};
7796 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7800 int InputIdx = Mask[i] >= Size;
7803 ++NumLoInputs[InputIdx];
7805 ++NumHiInputs[InputIdx];
7808 ++NumEvenInputs[InputIdx];
7810 ++NumOddInputs[InputIdx];
7813 // The minimum number of cross-input results for both the interleaved and
7814 // split cases. If interleaving results in fewer cross-input results, return
7816 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7817 NumEvenInputs[0] + NumOddInputs[1]);
7818 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7819 NumLoInputs[0] + NumHiInputs[1]);
7820 return InterleavedCrosses < SplitCrosses;
7823 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7825 /// This strategy only works when the inputs from each vector fit into a single
7826 /// half of that vector, and generally there are not so many inputs as to leave
7827 /// the in-place shuffles required highly constrained (and thus expensive). It
7828 /// shifts all the inputs into a single side of both input vectors and then
7829 /// uses an unpack to interleave these inputs in a single vector. At that
7830 /// point, we will fall back on the generic single input shuffle lowering.
7831 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7833 MutableArrayRef<int> Mask,
7834 const X86Subtarget *Subtarget,
7835 SelectionDAG &DAG) {
7836 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7837 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7838 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7839 for (int i = 0; i < 8; ++i)
7840 if (Mask[i] >= 0 && Mask[i] < 4)
7841 LoV1Inputs.push_back(i);
7842 else if (Mask[i] >= 4 && Mask[i] < 8)
7843 HiV1Inputs.push_back(i);
7844 else if (Mask[i] >= 8 && Mask[i] < 12)
7845 LoV2Inputs.push_back(i);
7846 else if (Mask[i] >= 12)
7847 HiV2Inputs.push_back(i);
7849 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7850 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7853 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7854 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7855 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7857 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7858 HiV1Inputs.size() + HiV2Inputs.size();
7860 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7861 ArrayRef<int> HiInputs, bool MoveToLo,
7863 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7864 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7865 if (BadInputs.empty())
7868 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7869 int MoveOffset = MoveToLo ? 0 : 4;
7871 if (GoodInputs.empty()) {
7872 for (int BadInput : BadInputs) {
7873 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7874 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7877 if (GoodInputs.size() == 2) {
7878 // If the low inputs are spread across two dwords, pack them into
7880 MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
7881 MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
7882 Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
7883 Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
7885 // Otherwise pin the good inputs.
7886 for (int GoodInput : GoodInputs)
7887 MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7890 if (BadInputs.size() == 2) {
7891 // If we have two bad inputs then there may be either one or two good
7892 // inputs fixed in place. Find a fixed input, and then find the *other*
7893 // two adjacent indices by using modular arithmetic.
7895 std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
7896 [](int M) { return M >= 0; }) -
7897 std::begin(MoveMask);
7899 ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
7900 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7901 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7902 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7903 MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
7904 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7905 Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
7907 assert(BadInputs.size() == 1 && "All sizes handled");
7908 int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
7909 std::end(MoveMask), -1) -
7910 std::begin(MoveMask);
7911 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7912 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7916 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7919 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7921 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7924 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7925 // cross-half traffic in the final shuffle.
7927 // Munge the mask to be a single-input mask after the unpack merges the
7931 M = 2 * (M % 4) + (M / 8);
7933 return DAG.getVectorShuffle(
7934 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7935 DL, MVT::v8i16, V1, V2),
7936 DAG.getUNDEF(MVT::v8i16), Mask);
7939 /// \brief Generic lowering of 8-lane i16 shuffles.
7941 /// This handles both single-input shuffles and combined shuffle/blends with
7942 /// two inputs. The single input shuffles are immediately delegated to
7943 /// a dedicated lowering routine.
7945 /// The blends are lowered in one of three fundamental ways. If there are few
7946 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7947 /// of the input is significantly cheaper when lowered as an interleaving of
7948 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7949 /// halves of the inputs separately (making them have relatively few inputs)
7950 /// and then concatenate them.
7951 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7952 const X86Subtarget *Subtarget,
7953 SelectionDAG &DAG) {
7955 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7956 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7957 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7958 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7959 ArrayRef<int> OrigMask = SVOp->getMask();
7960 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7961 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7962 MutableArrayRef<int> Mask(MaskStorage);
7964 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7966 auto isV1 = [](int M) { return M >= 0 && M < 8; };
7967 auto isV2 = [](int M) { return M >= 8; };
7969 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7970 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7972 if (NumV2Inputs == 0)
7973 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7975 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7976 "to be V1-input shuffles.");
7978 if (NumV1Inputs + NumV2Inputs <= 4)
7979 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7981 // Check whether an interleaving lowering is likely to be more efficient.
7982 // This isn't perfect but it is a strong heuristic that tends to work well on
7983 // the kinds of shuffles that show up in practice.
7985 // FIXME: Handle 1x, 2x, and 4x interleaving.
7986 if (shouldLowerAsInterleaving(Mask)) {
7987 // FIXME: Figure out whether we should pack these into the low or high
7990 int EMask[8], OMask[8];
7991 for (int i = 0; i < 4; ++i) {
7992 EMask[i] = Mask[2*i];
7993 OMask[i] = Mask[2*i + 1];
7998 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7999 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
8001 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
8004 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8005 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8007 for (int i = 0; i < 4; ++i) {
8008 LoBlendMask[i] = Mask[i];
8009 HiBlendMask[i] = Mask[i + 4];
8012 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8013 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8014 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
8015 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
8017 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8018 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
8021 /// \brief Check whether a compaction lowering can be done by dropping even
8022 /// elements and compute how many times even elements must be dropped.
8024 /// This handles shuffles which take every Nth element where N is a power of
8025 /// two. Example shuffle masks:
8027 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14
8028 /// N = 1: 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8029 /// N = 2: 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12, 0, 4, 8, 12
8030 /// N = 2: 0, 4, 8, 12, 16, 20, 24, 28, 0, 4, 8, 12, 16, 20, 24, 28
8031 /// N = 3: 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8, 0, 8
8032 /// N = 3: 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24, 0, 8, 16, 24
8034 /// Any of these lanes can of course be undef.
8036 /// This routine only supports N <= 3.
8037 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8040 /// \returns N above, or the number of times even elements must be dropped if
8041 /// there is such a number. Otherwise returns zero.
8042 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8043 // Figure out whether we're looping over two inputs or just one.
8044 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8046 // The modulus for the shuffle vector entries is based on whether this is
8047 // a single input or not.
8048 int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8049 assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8050 "We should only be called with masks with a power-of-2 size!");
8052 uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8054 // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8055 // and 2^3 simultaneously. This is because we may have ambiguity with
8056 // partially undef inputs.
8057 bool ViableForN[3] = {true, true, true};
8059 for (int i = 0, e = Mask.size(); i < e; ++i) {
8060 // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8065 bool IsAnyViable = false;
8066 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8067 if (ViableForN[j]) {
8070 // The shuffle mask must be equal to (i * 2^N) % M.
8071 if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8074 ViableForN[j] = false;
8076 // Early exit if we exhaust the possible powers of two.
8081 for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8085 // Return 0 as there is no viable power of two.
8089 /// \brief Generic lowering of v16i8 shuffles.
8091 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8092 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8093 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8094 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8096 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8097 const X86Subtarget *Subtarget,
8098 SelectionDAG &DAG) {
8100 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8101 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8102 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8103 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8104 ArrayRef<int> OrigMask = SVOp->getMask();
8105 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8106 int MaskStorage[16] = {
8107 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8108 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
8109 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
8110 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
8111 MutableArrayRef<int> Mask(MaskStorage);
8112 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
8113 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
8115 // For single-input shuffles, there are some nicer lowering tricks we can use.
8116 if (isSingleInputShuffleMask(Mask)) {
8117 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8118 // Notably, this handles splat and partial-splat shuffles more efficiently.
8119 // However, it only makes sense if the pre-duplication shuffle simplifies
8120 // things significantly. Currently, this means we need to be able to
8121 // express the pre-duplication shuffle as an i16 shuffle.
8123 // FIXME: We should check for other patterns which can be widened into an
8124 // i16 shuffle as well.
8125 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8126 for (int i = 0; i < 16; i += 2) {
8127 if (Mask[i] != Mask[i + 1])
8132 auto tryToWidenViaDuplication = [&]() -> SDValue {
8133 if (!canWidenViaDuplication(Mask))
8135 SmallVector<int, 4> LoInputs;
8136 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8137 [](int M) { return M >= 0 && M < 8; });
8138 std::sort(LoInputs.begin(), LoInputs.end());
8139 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8141 SmallVector<int, 4> HiInputs;
8142 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8143 [](int M) { return M >= 8; });
8144 std::sort(HiInputs.begin(), HiInputs.end());
8145 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8148 bool TargetLo = LoInputs.size() >= HiInputs.size();
8149 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8150 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8152 int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8153 SmallDenseMap<int, int, 8> LaneMap;
8154 for (int I : InPlaceInputs) {
8155 PreDupI16Shuffle[I/2] = I/2;
8158 int j = TargetLo ? 0 : 4, je = j + 4;
8159 for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8160 // Check if j is already a shuffle of this input. This happens when
8161 // there are two adjacent bytes after we move the low one.
8162 if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8163 // If we haven't yet mapped the input, search for a slot into which
8165 while (j < je && PreDupI16Shuffle[j] != -1)
8169 // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8172 // Map this input with the i16 shuffle.
8173 PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8176 // Update the lane map based on the mapping we ended up with.
8177 LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8180 ISD::BITCAST, DL, MVT::v16i8,
8181 DAG.getVectorShuffle(MVT::v8i16, DL,
8182 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8183 DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8185 // Unpack the bytes to form the i16s that will be shuffled into place.
8186 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8187 MVT::v16i8, V1, V1);
8189 int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8190 for (int i = 0; i < 16; i += 2) {
8192 PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8193 assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8196 ISD::BITCAST, DL, MVT::v16i8,
8197 DAG.getVectorShuffle(MVT::v8i16, DL,
8198 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8199 DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8201 if (SDValue V = tryToWidenViaDuplication())
8205 // Check whether an interleaving lowering is likely to be more efficient.
8206 // This isn't perfect but it is a strong heuristic that tends to work well on
8207 // the kinds of shuffles that show up in practice.
8209 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8210 if (shouldLowerAsInterleaving(Mask)) {
8211 // FIXME: Figure out whether we should pack these into the low or high
8214 int EMask[16], OMask[16];
8215 for (int i = 0; i < 8; ++i) {
8216 EMask[i] = Mask[2*i];
8217 OMask[i] = Mask[2*i + 1];
8222 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8223 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8225 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8228 // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8229 // with PSHUFB. It is important to do this before we attempt to generate any
8230 // blends but after all of the single-input lowerings. If the single input
8231 // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8232 // want to preserve that and we can DAG combine any longer sequences into
8233 // a PSHUFB in the end. But once we start blending from multiple inputs,
8234 // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8235 // and there are *very* few patterns that would actually be faster than the
8236 // PSHUFB approach because of its ability to zero lanes.
8238 // FIXME: The only exceptions to the above are blends which are exact
8239 // interleavings with direct instructions supporting them. We currently don't
8240 // handle those well here.
8241 if (Subtarget->hasSSSE3()) {
8244 for (int i = 0; i < 16; ++i)
8245 if (Mask[i] == -1) {
8246 V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8248 V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8250 DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8252 V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8253 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8254 if (isSingleInputShuffleMask(Mask))
8255 return V1; // Single inputs are easy.
8257 // Otherwise, blend the two.
8258 V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8259 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8260 return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8263 // Check whether a compaction lowering can be done. This handles shuffles
8264 // which take every Nth element for some even N. See the helper function for
8267 // We special case these as they can be particularly efficiently handled with
8268 // the PACKUSB instruction on x86 and they show up in common patterns of
8269 // rearranging bytes to truncate wide elements.
8270 if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8271 // NumEvenDrops is the power of two stride of the elements. Another way of
8272 // thinking about it is that we need to drop the even elements this many
8273 // times to get the original input.
8274 bool IsSingleInput = isSingleInputShuffleMask(Mask);
8276 // First we need to zero all the dropped bytes.
8277 assert(NumEvenDrops <= 3 &&
8278 "No support for dropping even elements more than 3 times.");
8279 // We use the mask type to pick which bytes are preserved based on how many
8280 // elements are dropped.
8281 MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8282 SDValue ByteClearMask =
8283 DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8284 DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8285 V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8287 V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8289 // Now pack things back together.
8290 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8291 V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8292 SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8293 for (int i = 1; i < NumEvenDrops; ++i) {
8294 Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8295 Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8301 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8302 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8303 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8304 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8306 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8307 MutableArrayRef<int> V1HalfBlendMask,
8308 MutableArrayRef<int> V2HalfBlendMask) {
8309 for (int i = 0; i < 8; ++i)
8310 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8311 V1HalfBlendMask[i] = HalfMask[i];
8313 } else if (HalfMask[i] >= 16) {
8314 V2HalfBlendMask[i] = HalfMask[i] - 16;
8315 HalfMask[i] = i + 8;
8318 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8319 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8321 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8323 auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8324 MutableArrayRef<int> HiBlendMask) {
8326 // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8327 // them out and avoid using UNPCK{L,H} to extract the elements of V as
8329 if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8330 [](int M) { return M >= 0 && M % 2 == 1; }) &&
8331 std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8332 [](int M) { return M >= 0 && M % 2 == 1; })) {
8333 // Use a mask to drop the high bytes.
8334 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8335 V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8336 DAG.getConstant(0x00FF, MVT::v8i16));
8338 // This will be a single vector shuffle instead of a blend so nuke V2.
8339 V2 = DAG.getUNDEF(MVT::v8i16);
8341 // Squash the masks to point directly into V1.
8342 for (int &M : LoBlendMask)
8345 for (int &M : HiBlendMask)
8349 // Otherwise just unpack the low half of V into V1 and the high half into
8350 // V2 so that we can blend them as i16s.
8351 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8352 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8353 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8354 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8357 SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8358 SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8359 return std::make_pair(BlendedLo, BlendedHi);
8361 SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8362 std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8363 std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8365 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8366 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8368 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8371 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8373 /// This routine breaks down the specific type of 128-bit shuffle and
8374 /// dispatches to the lowering routines accordingly.
8375 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8376 MVT VT, const X86Subtarget *Subtarget,
8377 SelectionDAG &DAG) {
8378 switch (VT.SimpleTy) {
8380 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8382 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8384 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8386 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8388 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8390 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8393 llvm_unreachable("Unimplemented!");
8397 static bool isHalfCrossingShuffleMask(ArrayRef<int> Mask) {
8398 int Size = Mask.size();
8399 for (int M : Mask.slice(0, Size / 2))
8400 if (M >= 0 && (M % Size) >= Size / 2)
8402 for (int M : Mask.slice(Size / 2, Size / 2))
8403 if (M >= 0 && (M % Size) < Size / 2)
8408 /// \brief Generic routine to split a 256-bit vector shuffle into 128-bit
8411 /// There is a severely limited set of shuffles available in AVX1 for 256-bit
8412 /// vectors resulting in routinely needing to split the shuffle into two 128-bit
8413 /// shuffles. This can be done generically for any 256-bit vector shuffle and so
8414 /// we encode the logic here for specific shuffle lowering routines to bail to
8415 /// when they exhaust the features avaible to more directly handle the shuffle.
8416 static SDValue splitAndLower256BitVectorShuffle(SDValue Op, SDValue V1,
8418 const X86Subtarget *Subtarget,
8419 SelectionDAG &DAG) {
8421 MVT VT = Op.getSimpleValueType();
8422 assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8423 assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8424 assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8425 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8426 ArrayRef<int> Mask = SVOp->getMask();
8428 ArrayRef<int> LoMask = Mask.slice(0, Mask.size()/2);
8429 ArrayRef<int> HiMask = Mask.slice(Mask.size()/2);
8431 int NumElements = VT.getVectorNumElements();
8432 int SplitNumElements = NumElements / 2;
8433 MVT ScalarVT = VT.getScalarType();
8434 MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8436 SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8437 DAG.getIntPtrConstant(0));
8438 SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8439 DAG.getIntPtrConstant(SplitNumElements));
8440 SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8441 DAG.getIntPtrConstant(0));
8442 SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8443 DAG.getIntPtrConstant(SplitNumElements));
8445 // Now create two 4-way blends of these half-width vectors.
8446 auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8447 SmallVector<int, 16> V1BlendMask, V2BlendMask, BlendMask;
8448 for (int i = 0; i < SplitNumElements; ++i) {
8449 int M = HalfMask[i];
8450 if (M >= NumElements) {
8451 V2BlendMask.push_back(M - NumElements);
8452 V1BlendMask.push_back(-1);
8453 BlendMask.push_back(SplitNumElements + i);
8454 } else if (M >= 0) {
8455 V2BlendMask.push_back(-1);
8456 V1BlendMask.push_back(M);
8457 BlendMask.push_back(i);
8459 V2BlendMask.push_back(-1);
8460 V1BlendMask.push_back(-1);
8461 BlendMask.push_back(-1);
8464 SDValue V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8465 SDValue V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8466 return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8468 SDValue Lo = HalfBlend(LoMask);
8469 SDValue Hi = HalfBlend(HiMask);
8470 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8473 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
8475 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
8476 /// isn't available.
8477 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8478 const X86Subtarget *Subtarget,
8479 SelectionDAG &DAG) {
8481 assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8482 assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8483 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8484 ArrayRef<int> Mask = SVOp->getMask();
8485 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8487 // FIXME: If we have AVX2, we should delegate to generic code as crossing
8488 // shuffles aren't a problem and FP and int have the same patterns.
8490 // FIXME: We can handle these more cleverly than splitting for v4f64.
8491 if (isHalfCrossingShuffleMask(Mask))
8492 return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8494 if (isSingleInputShuffleMask(Mask)) {
8495 // Non-half-crossing single input shuffles can be lowerid with an
8496 // interleaved permutation.
8497 unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
8498 ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
8499 return DAG.getNode(X86ISD::VPERMILP, DL, MVT::v4f64, V1,
8500 DAG.getConstant(VPERMILPMask, MVT::i8));
8503 // X86 has dedicated unpack instructions that can handle specific blend
8504 // operations: UNPCKH and UNPCKL.
8505 if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
8506 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
8507 if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
8508 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
8509 // FIXME: It would be nice to find a way to get canonicalization to commute
8511 if (isShuffleEquivalent(Mask, 4, 0, 6, 2))
8512 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
8513 if (isShuffleEquivalent(Mask, 5, 1, 7, 3))
8514 return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
8516 // Check if the blend happens to exactly fit that of SHUFPD.
8517 if (Mask[0] < 4 && (Mask[1] == -1 || Mask[1] >= 4) &&
8518 Mask[2] < 4 && (Mask[3] == -1 || Mask[3] >= 4)) {
8519 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
8520 ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
8521 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
8522 DAG.getConstant(SHUFPDMask, MVT::i8));
8524 if ((Mask[0] == -1 || Mask[0] >= 4) && Mask[1] < 4 &&
8525 (Mask[2] == -1 || Mask[2] >= 4) && Mask[3] < 4) {
8526 unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
8527 ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
8528 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
8529 DAG.getConstant(SHUFPDMask, MVT::i8));
8532 // Shuffle the input elements into the desired positions in V1 and V2 and
8533 // blend them together.
8534 int V1Mask[] = {-1, -1, -1, -1};
8535 int V2Mask[] = {-1, -1, -1, -1};
8536 for (int i = 0; i < 4; ++i)
8537 if (Mask[i] >= 0 && Mask[i] < 4)
8538 V1Mask[i] = Mask[i];
8539 else if (Mask[i] >= 4)
8540 V2Mask[i] = Mask[i] - 4;
8542 V1 = DAG.getVectorShuffle(MVT::v4f64, DL, V1, DAG.getUNDEF(MVT::v4f64), V1Mask);
8543 V2 = DAG.getVectorShuffle(MVT::v4f64, DL, V2, DAG.getUNDEF(MVT::v4f64), V2Mask);
8545 unsigned BlendMask = 0;
8546 for (int i = 0; i < 4; ++i)
8548 BlendMask |= 1 << i;
8550 return DAG.getNode(X86ISD::BLENDI, DL, MVT::v4f64, V1, V2,
8551 DAG.getConstant(BlendMask, MVT::i8));
8554 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
8556 /// Largely delegates to common code when we have AVX2 and to the floating-point
8557 /// code when we only have AVX.
8558 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8559 const X86Subtarget *Subtarget,
8560 SelectionDAG &DAG) {
8562 assert(Op.getSimpleValueType() == MVT::v4i64 && "Bad shuffle type!");
8563 assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8564 assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8565 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8566 ArrayRef<int> Mask = SVOp->getMask();
8567 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8569 // FIXME: If we have AVX2, we should delegate to generic code as crossing
8570 // shuffles aren't a problem and FP and int have the same patterns.
8572 if (isHalfCrossingShuffleMask(Mask))
8573 return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8575 // AVX1 doesn't provide any facilities for v4i64 shuffles, bitcast and
8576 // delegate to floating point code.
8577 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V1);
8578 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V2);
8579 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i64,
8580 lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG));
8583 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
8585 /// This routine either breaks down the specific type of a 256-bit x86 vector
8586 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
8587 /// together based on the available instructions.
8588 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8589 MVT VT, const X86Subtarget *Subtarget,
8590 SelectionDAG &DAG) {
8591 switch (VT.SimpleTy) {
8593 return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8595 return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8600 // Fall back to the basic pattern of extracting the high half and forming
8602 // FIXME: Add targeted lowering for each type that can document rationale
8603 // for delegating to this when necessary.
8604 return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8607 llvm_unreachable("Not a valid 256-bit x86 vector type!");
8611 /// \brief Tiny helper function to test whether a shuffle mask could be
8612 /// simplified by widening the elements being shuffled.
8613 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
8614 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8615 if (Mask[i] % 2 != 0 || Mask[i] + 1 != Mask[i+1])
8621 /// \brief Top-level lowering for x86 vector shuffles.
8623 /// This handles decomposition, canonicalization, and lowering of all x86
8624 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8625 /// above in helper routines. The canonicalization attempts to widen shuffles
8626 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8627 /// s.t. only one of the two inputs needs to be tested, etc.
8628 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8629 SelectionDAG &DAG) {
8630 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8631 ArrayRef<int> Mask = SVOp->getMask();
8632 SDValue V1 = Op.getOperand(0);
8633 SDValue V2 = Op.getOperand(1);
8634 MVT VT = Op.getSimpleValueType();
8635 int NumElements = VT.getVectorNumElements();
8638 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8640 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8641 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8642 if (V1IsUndef && V2IsUndef)
8643 return DAG.getUNDEF(VT);
8645 // When we create a shuffle node we put the UNDEF node to second operand,
8646 // but in some cases the first operand may be transformed to UNDEF.
8647 // In this case we should just commute the node.
8649 return DAG.getCommutedVectorShuffle(*SVOp);
8651 // Check for non-undef masks pointing at an undef vector and make the masks
8652 // undef as well. This makes it easier to match the shuffle based solely on
8656 if (M >= NumElements) {
8657 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8658 for (int &M : NewMask)
8659 if (M >= NumElements)
8661 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8664 // For integer vector shuffles, try to collapse them into a shuffle of fewer
8665 // lanes but wider integers. We cap this to not form integers larger than i64
8666 // but it might be interesting to form i128 integers to handle flipping the
8667 // low and high halves of AVX 256-bit vectors.
8668 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8669 canWidenShuffleElements(Mask)) {
8670 SmallVector<int, 8> NewMask;
8671 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8672 NewMask.push_back(Mask[i] / 2);
8674 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8675 VT.getVectorNumElements() / 2);
8676 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8677 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8678 return DAG.getNode(ISD::BITCAST, dl, VT,
8679 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8682 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8683 for (int M : SVOp->getMask())
8686 else if (M < NumElements)
8691 // Commute the shuffle as needed such that more elements come from V1 than
8692 // V2. This allows us to match the shuffle pattern strictly on how many
8693 // elements come from V1 without handling the symmetric cases.
8694 if (NumV2Elements > NumV1Elements)
8695 return DAG.getCommutedVectorShuffle(*SVOp);
8697 // When the number of V1 and V2 elements are the same, try to minimize the
8698 // number of uses of V2 in the low half of the vector.
8699 if (NumV1Elements == NumV2Elements) {
8700 int LowV1Elements = 0, LowV2Elements = 0;
8701 for (int M : SVOp->getMask().slice(0, NumElements / 2))
8702 if (M >= NumElements)
8706 if (LowV2Elements > LowV1Elements)
8707 return DAG.getCommutedVectorShuffle(*SVOp);
8710 // For each vector width, delegate to a specialized lowering routine.
8711 if (VT.getSizeInBits() == 128)
8712 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8714 if (VT.getSizeInBits() == 256)
8715 return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8717 llvm_unreachable("Unimplemented!");
8721 //===----------------------------------------------------------------------===//
8722 // Legacy vector shuffle lowering
8724 // This code is the legacy code handling vector shuffles until the above
8725 // replaces its functionality and performance.
8726 //===----------------------------------------------------------------------===//
8728 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8729 bool hasInt256, unsigned *MaskOut = nullptr) {
8730 MVT EltVT = VT.getVectorElementType();
8732 // There is no blend with immediate in AVX-512.
8733 if (VT.is512BitVector())
8736 if (!hasSSE41 || EltVT == MVT::i8)
8738 if (!hasInt256 && VT == MVT::v16i16)
8741 unsigned MaskValue = 0;
8742 unsigned NumElems = VT.getVectorNumElements();
8743 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8744 unsigned NumLanes = (NumElems - 1) / 8 + 1;
8745 unsigned NumElemsInLane = NumElems / NumLanes;
8747 // Blend for v16i16 should be symetric for the both lanes.
8748 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8750 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8751 int EltIdx = MaskVals[i];
8753 if ((EltIdx < 0 || EltIdx == (int)i) &&
8754 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8757 if (((unsigned)EltIdx == (i + NumElems)) &&
8758 (SndLaneEltIdx < 0 ||
8759 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8760 MaskValue |= (1 << i);
8766 *MaskOut = MaskValue;
8770 // Try to lower a shuffle node into a simple blend instruction.
8771 // This function assumes isBlendMask returns true for this
8772 // SuffleVectorSDNode
8773 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8775 const X86Subtarget *Subtarget,
8776 SelectionDAG &DAG) {
8777 MVT VT = SVOp->getSimpleValueType(0);
8778 MVT EltVT = VT.getVectorElementType();
8779 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8780 Subtarget->hasInt256() && "Trying to lower a "
8781 "VECTOR_SHUFFLE to a Blend but "
8782 "with the wrong mask"));
8783 SDValue V1 = SVOp->getOperand(0);
8784 SDValue V2 = SVOp->getOperand(1);
8786 unsigned NumElems = VT.getVectorNumElements();
8788 // Convert i32 vectors to floating point if it is not AVX2.
8789 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8791 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8792 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8794 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8795 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8798 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8799 DAG.getConstant(MaskValue, MVT::i32));
8800 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8803 /// In vector type \p VT, return true if the element at index \p InputIdx
8804 /// falls on a different 128-bit lane than \p OutputIdx.
8805 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8806 unsigned OutputIdx) {
8807 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8808 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8811 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
8812 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
8813 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
8814 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8816 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8817 SelectionDAG &DAG) {
8818 MVT VT = V1.getSimpleValueType();
8819 assert(VT.is128BitVector() || VT.is256BitVector());
8821 MVT EltVT = VT.getVectorElementType();
8822 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8823 unsigned NumElts = VT.getVectorNumElements();
8825 SmallVector<SDValue, 32> PshufbMask;
8826 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8827 int InputIdx = MaskVals[OutputIdx];
8828 unsigned InputByteIdx;
8830 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8831 InputByteIdx = 0x80;
8833 // Cross lane is not allowed.
8834 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8836 InputByteIdx = InputIdx * EltSizeInBytes;
8837 // Index is an byte offset within the 128-bit lane.
8838 InputByteIdx &= 0xf;
8841 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8842 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8843 if (InputByteIdx != 0x80)
8848 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8850 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8851 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8852 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8855 // v8i16 shuffles - Prefer shuffles in the following order:
8856 // 1. [all] pshuflw, pshufhw, optional move
8857 // 2. [ssse3] 1 x pshufb
8858 // 3. [ssse3] 2 x pshufb + 1 x por
8859 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8861 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8862 SelectionDAG &DAG) {
8863 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8864 SDValue V1 = SVOp->getOperand(0);
8865 SDValue V2 = SVOp->getOperand(1);
8867 SmallVector<int, 8> MaskVals;
8869 // Determine if more than 1 of the words in each of the low and high quadwords
8870 // of the result come from the same quadword of one of the two inputs. Undef
8871 // mask values count as coming from any quadword, for better codegen.
8873 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8874 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8875 unsigned LoQuad[] = { 0, 0, 0, 0 };
8876 unsigned HiQuad[] = { 0, 0, 0, 0 };
8877 // Indices of quads used.
8878 std::bitset<4> InputQuads;
8879 for (unsigned i = 0; i < 8; ++i) {
8880 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8881 int EltIdx = SVOp->getMaskElt(i);
8882 MaskVals.push_back(EltIdx);
8891 InputQuads.set(EltIdx / 4);
8894 int BestLoQuad = -1;
8895 unsigned MaxQuad = 1;
8896 for (unsigned i = 0; i < 4; ++i) {
8897 if (LoQuad[i] > MaxQuad) {
8899 MaxQuad = LoQuad[i];
8903 int BestHiQuad = -1;
8905 for (unsigned i = 0; i < 4; ++i) {
8906 if (HiQuad[i] > MaxQuad) {
8908 MaxQuad = HiQuad[i];
8912 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8913 // of the two input vectors, shuffle them into one input vector so only a
8914 // single pshufb instruction is necessary. If there are more than 2 input
8915 // quads, disable the next transformation since it does not help SSSE3.
8916 bool V1Used = InputQuads[0] || InputQuads[1];
8917 bool V2Used = InputQuads[2] || InputQuads[3];
8918 if (Subtarget->hasSSSE3()) {
8919 if (InputQuads.count() == 2 && V1Used && V2Used) {
8920 BestLoQuad = InputQuads[0] ? 0 : 1;
8921 BestHiQuad = InputQuads[2] ? 2 : 3;
8923 if (InputQuads.count() > 2) {
8929 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8930 // the shuffle mask. If a quad is scored as -1, that means that it contains
8931 // words from all 4 input quadwords.
8933 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8935 BestLoQuad < 0 ? 0 : BestLoQuad,
8936 BestHiQuad < 0 ? 1 : BestHiQuad
8938 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8939 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8940 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8941 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8943 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8944 // source words for the shuffle, to aid later transformations.
8945 bool AllWordsInNewV = true;
8946 bool InOrder[2] = { true, true };
8947 for (unsigned i = 0; i != 8; ++i) {
8948 int idx = MaskVals[i];
8950 InOrder[i/4] = false;
8951 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8953 AllWordsInNewV = false;
8957 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8958 if (AllWordsInNewV) {
8959 for (int i = 0; i != 8; ++i) {
8960 int idx = MaskVals[i];
8963 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8964 if ((idx != i) && idx < 4)
8966 if ((idx != i) && idx > 3)
8975 // If we've eliminated the use of V2, and the new mask is a pshuflw or
8976 // pshufhw, that's as cheap as it gets. Return the new shuffle.
8977 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8978 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8979 unsigned TargetMask = 0;
8980 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8981 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8982 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8983 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8984 getShufflePSHUFLWImmediate(SVOp);
8985 V1 = NewV.getOperand(0);
8986 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8990 // Promote splats to a larger type which usually leads to more efficient code.
8991 // FIXME: Is this true if pshufb is available?
8992 if (SVOp->isSplat())
8993 return PromoteSplat(SVOp, DAG);
8995 // If we have SSSE3, and all words of the result are from 1 input vector,
8996 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
8997 // is present, fall back to case 4.
8998 if (Subtarget->hasSSSE3()) {
8999 SmallVector<SDValue,16> pshufbMask;
9001 // If we have elements from both input vectors, set the high bit of the
9002 // shuffle mask element to zero out elements that come from V2 in the V1
9003 // mask, and elements that come from V1 in the V2 mask, so that the two
9004 // results can be OR'd together.
9005 bool TwoInputs = V1Used && V2Used;
9006 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
9008 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9010 // Calculate the shuffle mask for the second input, shuffle it, and
9011 // OR it with the first shuffled input.
9012 CommuteVectorShuffleMask(MaskVals, 8);
9013 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
9014 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9015 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9018 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
9019 // and update MaskVals with new element order.
9020 std::bitset<8> InOrder;
9021 if (BestLoQuad >= 0) {
9022 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
9023 for (int i = 0; i != 4; ++i) {
9024 int idx = MaskVals[i];
9027 } else if ((idx / 4) == BestLoQuad) {
9032 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9035 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9036 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9037 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
9039 getShufflePSHUFLWImmediate(SVOp), DAG);
9043 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
9044 // and update MaskVals with the new element order.
9045 if (BestHiQuad >= 0) {
9046 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
9047 for (unsigned i = 4; i != 8; ++i) {
9048 int idx = MaskVals[i];
9051 } else if ((idx / 4) == BestHiQuad) {
9052 MaskV[i] = (idx & 3) + 4;
9056 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9059 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9060 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9061 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
9063 getShufflePSHUFHWImmediate(SVOp), DAG);
9067 // In case BestHi & BestLo were both -1, which means each quadword has a word
9068 // from each of the four input quadwords, calculate the InOrder bitvector now
9069 // before falling through to the insert/extract cleanup.
9070 if (BestLoQuad == -1 && BestHiQuad == -1) {
9072 for (int i = 0; i != 8; ++i)
9073 if (MaskVals[i] < 0 || MaskVals[i] == i)
9077 // The other elements are put in the right place using pextrw and pinsrw.
9078 for (unsigned i = 0; i != 8; ++i) {
9081 int EltIdx = MaskVals[i];
9084 SDValue ExtOp = (EltIdx < 8) ?
9085 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
9086 DAG.getIntPtrConstant(EltIdx)) :
9087 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
9088 DAG.getIntPtrConstant(EltIdx - 8));
9089 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
9090 DAG.getIntPtrConstant(i));
9095 /// \brief v16i16 shuffles
9097 /// FIXME: We only support generation of a single pshufb currently. We can
9098 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
9099 /// well (e.g 2 x pshufb + 1 x por).
9101 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
9102 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9103 SDValue V1 = SVOp->getOperand(0);
9104 SDValue V2 = SVOp->getOperand(1);
9107 if (V2.getOpcode() != ISD::UNDEF)
9110 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9111 return getPSHUFB(MaskVals, V1, dl, DAG);
9114 // v16i8 shuffles - Prefer shuffles in the following order:
9115 // 1. [ssse3] 1 x pshufb
9116 // 2. [ssse3] 2 x pshufb + 1 x por
9117 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
9118 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
9119 const X86Subtarget* Subtarget,
9120 SelectionDAG &DAG) {
9121 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9122 SDValue V1 = SVOp->getOperand(0);
9123 SDValue V2 = SVOp->getOperand(1);
9125 ArrayRef<int> MaskVals = SVOp->getMask();
9127 // Promote splats to a larger type which usually leads to more efficient code.
9128 // FIXME: Is this true if pshufb is available?
9129 if (SVOp->isSplat())
9130 return PromoteSplat(SVOp, DAG);
9132 // If we have SSSE3, case 1 is generated when all result bytes come from
9133 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
9134 // present, fall back to case 3.
9136 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
9137 if (Subtarget->hasSSSE3()) {
9138 SmallVector<SDValue,16> pshufbMask;
9140 // If all result elements are from one input vector, then only translate
9141 // undef mask values to 0x80 (zero out result) in the pshufb mask.
9143 // Otherwise, we have elements from both input vectors, and must zero out
9144 // elements that come from V2 in the first mask, and V1 in the second mask
9145 // so that we can OR them together.
9146 for (unsigned i = 0; i != 16; ++i) {
9147 int EltIdx = MaskVals[i];
9148 if (EltIdx < 0 || EltIdx >= 16)
9150 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9152 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
9153 DAG.getNode(ISD::BUILD_VECTOR, dl,
9154 MVT::v16i8, pshufbMask));
9156 // As PSHUFB will zero elements with negative indices, it's safe to ignore
9157 // the 2nd operand if it's undefined or zero.
9158 if (V2.getOpcode() == ISD::UNDEF ||
9159 ISD::isBuildVectorAllZeros(V2.getNode()))
9162 // Calculate the shuffle mask for the second input, shuffle it, and
9163 // OR it with the first shuffled input.
9165 for (unsigned i = 0; i != 16; ++i) {
9166 int EltIdx = MaskVals[i];
9167 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
9168 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9170 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
9171 DAG.getNode(ISD::BUILD_VECTOR, dl,
9172 MVT::v16i8, pshufbMask));
9173 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9176 // No SSSE3 - Calculate in place words and then fix all out of place words
9177 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
9178 // the 16 different words that comprise the two doublequadword input vectors.
9179 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9180 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9182 for (int i = 0; i != 8; ++i) {
9183 int Elt0 = MaskVals[i*2];
9184 int Elt1 = MaskVals[i*2+1];
9186 // This word of the result is all undef, skip it.
9187 if (Elt0 < 0 && Elt1 < 0)
9190 // This word of the result is already in the correct place, skip it.
9191 if ((Elt0 == i*2) && (Elt1 == i*2+1))
9194 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
9195 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
9198 // If Elt0 and Elt1 are defined, are consecutive, and can be load
9199 // using a single extract together, load it and store it.
9200 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
9201 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9202 DAG.getIntPtrConstant(Elt1 / 2));
9203 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9204 DAG.getIntPtrConstant(i));
9208 // If Elt1 is defined, extract it from the appropriate source. If the
9209 // source byte is not also odd, shift the extracted word left 8 bits
9210 // otherwise clear the bottom 8 bits if we need to do an or.
9212 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9213 DAG.getIntPtrConstant(Elt1 / 2));
9214 if ((Elt1 & 1) == 0)
9215 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
9217 TLI.getShiftAmountTy(InsElt.getValueType())));
9219 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
9220 DAG.getConstant(0xFF00, MVT::i16));
9222 // If Elt0 is defined, extract it from the appropriate source. If the
9223 // source byte is not also even, shift the extracted word right 8 bits. If
9224 // Elt1 was also defined, OR the extracted values together before
9225 // inserting them in the result.
9227 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
9228 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
9229 if ((Elt0 & 1) != 0)
9230 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
9232 TLI.getShiftAmountTy(InsElt0.getValueType())));
9234 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
9235 DAG.getConstant(0x00FF, MVT::i16));
9236 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
9239 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9240 DAG.getIntPtrConstant(i));
9242 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
9245 // v32i8 shuffles - Translate to VPSHUFB if possible.
9247 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
9248 const X86Subtarget *Subtarget,
9249 SelectionDAG &DAG) {
9250 MVT VT = SVOp->getSimpleValueType(0);
9251 SDValue V1 = SVOp->getOperand(0);
9252 SDValue V2 = SVOp->getOperand(1);
9254 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9256 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9257 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
9258 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
9260 // VPSHUFB may be generated if
9261 // (1) one of input vector is undefined or zeroinitializer.
9262 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
9263 // And (2) the mask indexes don't cross the 128-bit lane.
9264 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
9265 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
9268 if (V1IsAllZero && !V2IsAllZero) {
9269 CommuteVectorShuffleMask(MaskVals, 32);
9272 return getPSHUFB(MaskVals, V1, dl, DAG);
9275 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
9276 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
9277 /// done when every pair / quad of shuffle mask elements point to elements in
9278 /// the right sequence. e.g.
9279 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
9281 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
9282 SelectionDAG &DAG) {
9283 MVT VT = SVOp->getSimpleValueType(0);
9285 unsigned NumElems = VT.getVectorNumElements();
9288 switch (VT.SimpleTy) {
9289 default: llvm_unreachable("Unexpected!");
9292 return SDValue(SVOp, 0);
9293 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
9294 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
9295 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
9296 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
9297 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
9298 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
9301 SmallVector<int, 8> MaskVec;
9302 for (unsigned i = 0; i != NumElems; i += Scale) {
9304 for (unsigned j = 0; j != Scale; ++j) {
9305 int EltIdx = SVOp->getMaskElt(i+j);
9309 StartIdx = (EltIdx / Scale);
9310 if (EltIdx != (int)(StartIdx*Scale + j))
9313 MaskVec.push_back(StartIdx);
9316 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
9317 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
9318 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
9321 /// getVZextMovL - Return a zero-extending vector move low node.
9323 static SDValue getVZextMovL(MVT VT, MVT OpVT,
9324 SDValue SrcOp, SelectionDAG &DAG,
9325 const X86Subtarget *Subtarget, SDLoc dl) {
9326 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
9327 LoadSDNode *LD = nullptr;
9328 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
9329 LD = dyn_cast<LoadSDNode>(SrcOp);
9331 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
9333 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
9334 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
9335 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9336 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
9337 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
9339 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
9340 return DAG.getNode(ISD::BITCAST, dl, VT,
9341 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9342 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9350 return DAG.getNode(ISD::BITCAST, dl, VT,
9351 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9352 DAG.getNode(ISD::BITCAST, dl,
9356 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
9357 /// which could not be matched by any known target speficic shuffle
9359 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9361 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
9362 if (NewOp.getNode())
9365 MVT VT = SVOp->getSimpleValueType(0);
9367 unsigned NumElems = VT.getVectorNumElements();
9368 unsigned NumLaneElems = NumElems / 2;
9371 MVT EltVT = VT.getVectorElementType();
9372 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
9375 SmallVector<int, 16> Mask;
9376 for (unsigned l = 0; l < 2; ++l) {
9377 // Build a shuffle mask for the output, discovering on the fly which
9378 // input vectors to use as shuffle operands (recorded in InputUsed).
9379 // If building a suitable shuffle vector proves too hard, then bail
9380 // out with UseBuildVector set.
9381 bool UseBuildVector = false;
9382 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9383 unsigned LaneStart = l * NumLaneElems;
9384 for (unsigned i = 0; i != NumLaneElems; ++i) {
9385 // The mask element. This indexes into the input.
9386 int Idx = SVOp->getMaskElt(i+LaneStart);
9388 // the mask element does not index into any input vector.
9393 // The input vector this mask element indexes into.
9394 int Input = Idx / NumLaneElems;
9396 // Turn the index into an offset from the start of the input vector.
9397 Idx -= Input * NumLaneElems;
9399 // Find or create a shuffle vector operand to hold this input.
9401 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9402 if (InputUsed[OpNo] == Input)
9403 // This input vector is already an operand.
9405 if (InputUsed[OpNo] < 0) {
9406 // Create a new operand for this input vector.
9407 InputUsed[OpNo] = Input;
9412 if (OpNo >= array_lengthof(InputUsed)) {
9413 // More than two input vectors used! Give up on trying to create a
9414 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
9415 UseBuildVector = true;
9419 // Add the mask index for the new shuffle vector.
9420 Mask.push_back(Idx + OpNo * NumLaneElems);
9423 if (UseBuildVector) {
9424 SmallVector<SDValue, 16> SVOps;
9425 for (unsigned i = 0; i != NumLaneElems; ++i) {
9426 // The mask element. This indexes into the input.
9427 int Idx = SVOp->getMaskElt(i+LaneStart);
9429 SVOps.push_back(DAG.getUNDEF(EltVT));
9433 // The input vector this mask element indexes into.
9434 int Input = Idx / NumElems;
9436 // Turn the index into an offset from the start of the input vector.
9437 Idx -= Input * NumElems;
9439 // Extract the vector element by hand.
9440 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9441 SVOp->getOperand(Input),
9442 DAG.getIntPtrConstant(Idx)));
9445 // Construct the output using a BUILD_VECTOR.
9446 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9447 } else if (InputUsed[0] < 0) {
9448 // No input vectors were used! The result is undefined.
9449 Output[l] = DAG.getUNDEF(NVT);
9451 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9452 (InputUsed[0] % 2) * NumLaneElems,
9454 // If only one input was used, use an undefined vector for the other.
9455 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9456 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9457 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9458 // At least one input vector was used. Create a new shuffle vector.
9459 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9465 // Concatenate the result back
9466 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9469 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9470 /// 4 elements, and match them with several different shuffle types.
9472 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9473 SDValue V1 = SVOp->getOperand(0);
9474 SDValue V2 = SVOp->getOperand(1);
9476 MVT VT = SVOp->getSimpleValueType(0);
9478 assert(VT.is128BitVector() && "Unsupported vector size");
9480 std::pair<int, int> Locs[4];
9481 int Mask1[] = { -1, -1, -1, -1 };
9482 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9486 for (unsigned i = 0; i != 4; ++i) {
9487 int Idx = PermMask[i];
9489 Locs[i] = std::make_pair(-1, -1);
9491 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9493 Locs[i] = std::make_pair(0, NumLo);
9497 Locs[i] = std::make_pair(1, NumHi);
9499 Mask1[2+NumHi] = Idx;
9505 if (NumLo <= 2 && NumHi <= 2) {
9506 // If no more than two elements come from either vector. This can be
9507 // implemented with two shuffles. First shuffle gather the elements.
9508 // The second shuffle, which takes the first shuffle as both of its
9509 // vector operands, put the elements into the right order.
9510 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9512 int Mask2[] = { -1, -1, -1, -1 };
9514 for (unsigned i = 0; i != 4; ++i)
9515 if (Locs[i].first != -1) {
9516 unsigned Idx = (i < 2) ? 0 : 4;
9517 Idx += Locs[i].first * 2 + Locs[i].second;
9521 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9524 if (NumLo == 3 || NumHi == 3) {
9525 // Otherwise, we must have three elements from one vector, call it X, and
9526 // one element from the other, call it Y. First, use a shufps to build an
9527 // intermediate vector with the one element from Y and the element from X
9528 // that will be in the same half in the final destination (the indexes don't
9529 // matter). Then, use a shufps to build the final vector, taking the half
9530 // containing the element from Y from the intermediate, and the other half
9533 // Normalize it so the 3 elements come from V1.
9534 CommuteVectorShuffleMask(PermMask, 4);
9538 // Find the element from V2.
9540 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9541 int Val = PermMask[HiIndex];
9548 Mask1[0] = PermMask[HiIndex];
9550 Mask1[2] = PermMask[HiIndex^1];
9552 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9555 Mask1[0] = PermMask[0];
9556 Mask1[1] = PermMask[1];
9557 Mask1[2] = HiIndex & 1 ? 6 : 4;
9558 Mask1[3] = HiIndex & 1 ? 4 : 6;
9559 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9562 Mask1[0] = HiIndex & 1 ? 2 : 0;
9563 Mask1[1] = HiIndex & 1 ? 0 : 2;
9564 Mask1[2] = PermMask[2];
9565 Mask1[3] = PermMask[3];
9570 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9573 // Break it into (shuffle shuffle_hi, shuffle_lo).
9574 int LoMask[] = { -1, -1, -1, -1 };
9575 int HiMask[] = { -1, -1, -1, -1 };
9577 int *MaskPtr = LoMask;
9578 unsigned MaskIdx = 0;
9581 for (unsigned i = 0; i != 4; ++i) {
9588 int Idx = PermMask[i];
9590 Locs[i] = std::make_pair(-1, -1);
9591 } else if (Idx < 4) {
9592 Locs[i] = std::make_pair(MaskIdx, LoIdx);
9593 MaskPtr[LoIdx] = Idx;
9596 Locs[i] = std::make_pair(MaskIdx, HiIdx);
9597 MaskPtr[HiIdx] = Idx;
9602 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9603 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9604 int MaskOps[] = { -1, -1, -1, -1 };
9605 for (unsigned i = 0; i != 4; ++i)
9606 if (Locs[i].first != -1)
9607 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9608 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9611 static bool MayFoldVectorLoad(SDValue V) {
9612 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9613 V = V.getOperand(0);
9615 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9616 V = V.getOperand(0);
9617 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9618 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9619 // BUILD_VECTOR (load), undef
9620 V = V.getOperand(0);
9622 return MayFoldLoad(V);
9626 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9627 MVT VT = Op.getSimpleValueType();
9629 // Canonizalize to v2f64.
9630 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9631 return DAG.getNode(ISD::BITCAST, dl, VT,
9632 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9637 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9639 SDValue V1 = Op.getOperand(0);
9640 SDValue V2 = Op.getOperand(1);
9641 MVT VT = Op.getSimpleValueType();
9643 assert(VT != MVT::v2i64 && "unsupported shuffle type");
9645 if (HasSSE2 && VT == MVT::v2f64)
9646 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9648 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9649 return DAG.getNode(ISD::BITCAST, dl, VT,
9650 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9651 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9652 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9656 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9657 SDValue V1 = Op.getOperand(0);
9658 SDValue V2 = Op.getOperand(1);
9659 MVT VT = Op.getSimpleValueType();
9661 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9662 "unsupported shuffle type");
9664 if (V2.getOpcode() == ISD::UNDEF)
9668 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9672 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9673 SDValue V1 = Op.getOperand(0);
9674 SDValue V2 = Op.getOperand(1);
9675 MVT VT = Op.getSimpleValueType();
9676 unsigned NumElems = VT.getVectorNumElements();
9678 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9679 // operand of these instructions is only memory, so check if there's a
9680 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9682 bool CanFoldLoad = false;
9684 // Trivial case, when V2 comes from a load.
9685 if (MayFoldVectorLoad(V2))
9688 // When V1 is a load, it can be folded later into a store in isel, example:
9689 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9691 // (MOVLPSmr addr:$src1, VR128:$src2)
9692 // So, recognize this potential and also use MOVLPS or MOVLPD
9693 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9696 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9698 if (HasSSE2 && NumElems == 2)
9699 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9702 // If we don't care about the second element, proceed to use movss.
9703 if (SVOp->getMaskElt(1) != -1)
9704 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9707 // movl and movlp will both match v2i64, but v2i64 is never matched by
9708 // movl earlier because we make it strict to avoid messing with the movlp load
9709 // folding logic (see the code above getMOVLP call). Match it here then,
9710 // this is horrible, but will stay like this until we move all shuffle
9711 // matching to x86 specific nodes. Note that for the 1st condition all
9712 // types are matched with movsd.
9714 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9715 // as to remove this logic from here, as much as possible
9716 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9717 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9718 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9721 assert(VT != MVT::v4i32 && "unsupported shuffle type");
9723 // Invert the operand order and use SHUFPS to match it.
9724 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9725 getShuffleSHUFImmediate(SVOp), DAG);
9728 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9729 SelectionDAG &DAG) {
9731 MVT VT = Load->getSimpleValueType(0);
9732 MVT EVT = VT.getVectorElementType();
9733 SDValue Addr = Load->getOperand(1);
9734 SDValue NewAddr = DAG.getNode(
9735 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9736 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9739 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9740 DAG.getMachineFunction().getMachineMemOperand(
9741 Load->getMemOperand(), 0, EVT.getStoreSize()));
9745 // It is only safe to call this function if isINSERTPSMask is true for
9746 // this shufflevector mask.
9747 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9748 SelectionDAG &DAG) {
9749 // Generate an insertps instruction when inserting an f32 from memory onto a
9750 // v4f32 or when copying a member from one v4f32 to another.
9751 // We also use it for transferring i32 from one register to another,
9752 // since it simply copies the same bits.
9753 // If we're transferring an i32 from memory to a specific element in a
9754 // register, we output a generic DAG that will match the PINSRD
9756 MVT VT = SVOp->getSimpleValueType(0);
9757 MVT EVT = VT.getVectorElementType();
9758 SDValue V1 = SVOp->getOperand(0);
9759 SDValue V2 = SVOp->getOperand(1);
9760 auto Mask = SVOp->getMask();
9761 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9762 "unsupported vector type for insertps/pinsrd");
9764 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9765 auto FromV2Predicate = [](const int &i) { return i >= 4; };
9766 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9774 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9777 // If we have 1 element from each vector, we have to check if we're
9778 // changing V1's element's place. If so, we're done. Otherwise, we
9779 // should assume we're changing V2's element's place and behave
9781 int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9782 assert(DestIndex <= INT32_MAX && "truncated destination index");
9783 if (FromV1 == FromV2 &&
9784 static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9788 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9791 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9792 "More than one element from V1 and from V2, or no elements from one "
9793 "of the vectors. This case should not have returned true from "
9798 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9801 // Get an index into the source vector in the range [0,4) (the mask is
9802 // in the range [0,8) because it can address V1 and V2)
9803 unsigned SrcIndex = Mask[DestIndex] % 4;
9804 if (MayFoldLoad(From)) {
9805 // Trivial case, when From comes from a load and is only used by the
9806 // shuffle. Make it use insertps from the vector that we need from that
9809 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9810 if (!NewLoad.getNode())
9813 if (EVT == MVT::f32) {
9814 // Create this as a scalar to vector to match the instruction pattern.
9815 SDValue LoadScalarToVector =
9816 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9817 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9818 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9820 } else { // EVT == MVT::i32
9821 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9822 // instruction, to match the PINSRD instruction, which loads an i32 to a
9823 // certain vector element.
9824 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9825 DAG.getConstant(DestIndex, MVT::i32));
9829 // Vector-element-to-vector
9830 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9831 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9834 // Reduce a vector shuffle to zext.
9835 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9836 SelectionDAG &DAG) {
9837 // PMOVZX is only available from SSE41.
9838 if (!Subtarget->hasSSE41())
9841 MVT VT = Op.getSimpleValueType();
9843 // Only AVX2 support 256-bit vector integer extending.
9844 if (!Subtarget->hasInt256() && VT.is256BitVector())
9847 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9849 SDValue V1 = Op.getOperand(0);
9850 SDValue V2 = Op.getOperand(1);
9851 unsigned NumElems = VT.getVectorNumElements();
9853 // Extending is an unary operation and the element type of the source vector
9854 // won't be equal to or larger than i64.
9855 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9856 VT.getVectorElementType() == MVT::i64)
9859 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9860 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9861 while ((1U << Shift) < NumElems) {
9862 if (SVOp->getMaskElt(1U << Shift) == 1)
9865 // The maximal ratio is 8, i.e. from i8 to i64.
9870 // Check the shuffle mask.
9871 unsigned Mask = (1U << Shift) - 1;
9872 for (unsigned i = 0; i != NumElems; ++i) {
9873 int EltIdx = SVOp->getMaskElt(i);
9874 if ((i & Mask) != 0 && EltIdx != -1)
9876 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9880 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9881 MVT NeVT = MVT::getIntegerVT(NBits);
9882 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9884 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9887 // Simplify the operand as it's prepared to be fed into shuffle.
9888 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9889 if (V1.getOpcode() == ISD::BITCAST &&
9890 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9891 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9892 V1.getOperand(0).getOperand(0)
9893 .getSimpleValueType().getSizeInBits() == SignificantBits) {
9894 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9895 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9896 ConstantSDNode *CIdx =
9897 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9898 // If it's foldable, i.e. normal load with single use, we will let code
9899 // selection to fold it. Otherwise, we will short the conversion sequence.
9900 if (CIdx && CIdx->getZExtValue() == 0 &&
9901 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9902 MVT FullVT = V.getSimpleValueType();
9903 MVT V1VT = V1.getSimpleValueType();
9904 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9905 // The "ext_vec_elt" node is wider than the result node.
9906 // In this case we should extract subvector from V.
9907 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9908 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9909 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9910 FullVT.getVectorNumElements()/Ratio);
9911 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9912 DAG.getIntPtrConstant(0));
9914 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9918 return DAG.getNode(ISD::BITCAST, DL, VT,
9919 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9922 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9923 SelectionDAG &DAG) {
9924 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9925 MVT VT = Op.getSimpleValueType();
9927 SDValue V1 = Op.getOperand(0);
9928 SDValue V2 = Op.getOperand(1);
9930 if (isZeroShuffle(SVOp))
9931 return getZeroVector(VT, Subtarget, DAG, dl);
9933 // Handle splat operations
9934 if (SVOp->isSplat()) {
9935 // Use vbroadcast whenever the splat comes from a foldable load
9936 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9937 if (Broadcast.getNode())
9941 // Check integer expanding shuffles.
9942 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9943 if (NewOp.getNode())
9946 // If the shuffle can be profitably rewritten as a narrower shuffle, then
9948 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9950 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9951 if (NewOp.getNode())
9952 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9953 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9954 // FIXME: Figure out a cleaner way to do this.
9955 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9956 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9957 if (NewOp.getNode()) {
9958 MVT NewVT = NewOp.getSimpleValueType();
9959 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9960 NewVT, true, false))
9961 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9964 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9965 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9966 if (NewOp.getNode()) {
9967 MVT NewVT = NewOp.getSimpleValueType();
9968 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9969 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9978 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9979 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9980 SDValue V1 = Op.getOperand(0);
9981 SDValue V2 = Op.getOperand(1);
9982 MVT VT = Op.getSimpleValueType();
9984 unsigned NumElems = VT.getVectorNumElements();
9985 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9986 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9987 bool V1IsSplat = false;
9988 bool V2IsSplat = false;
9989 bool HasSSE2 = Subtarget->hasSSE2();
9990 bool HasFp256 = Subtarget->hasFp256();
9991 bool HasInt256 = Subtarget->hasInt256();
9992 MachineFunction &MF = DAG.getMachineFunction();
9993 bool OptForSize = MF.getFunction()->getAttributes().
9994 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9996 // Check if we should use the experimental vector shuffle lowering. If so,
9997 // delegate completely to that code path.
9998 if (ExperimentalVectorShuffleLowering)
9999 return lowerVectorShuffle(Op, Subtarget, DAG);
10001 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10003 if (V1IsUndef && V2IsUndef)
10004 return DAG.getUNDEF(VT);
10006 // When we create a shuffle node we put the UNDEF node to second operand,
10007 // but in some cases the first operand may be transformed to UNDEF.
10008 // In this case we should just commute the node.
10010 return DAG.getCommutedVectorShuffle(*SVOp);
10012 // Vector shuffle lowering takes 3 steps:
10014 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
10015 // narrowing and commutation of operands should be handled.
10016 // 2) Matching of shuffles with known shuffle masks to x86 target specific
10018 // 3) Rewriting of unmatched masks into new generic shuffle operations,
10019 // so the shuffle can be broken into other shuffles and the legalizer can
10020 // try the lowering again.
10022 // The general idea is that no vector_shuffle operation should be left to
10023 // be matched during isel, all of them must be converted to a target specific
10026 // Normalize the input vectors. Here splats, zeroed vectors, profitable
10027 // narrowing and commutation of operands should be handled. The actual code
10028 // doesn't include all of those, work in progress...
10029 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
10030 if (NewOp.getNode())
10033 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
10035 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
10036 // unpckh_undef). Only use pshufd if speed is more important than size.
10037 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10038 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10039 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10040 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10042 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
10043 V2IsUndef && MayFoldVectorLoad(V1))
10044 return getMOVDDup(Op, dl, V1, DAG);
10046 if (isMOVHLPS_v_undef_Mask(M, VT))
10047 return getMOVHighToLow(Op, dl, DAG);
10049 // Use to match splats
10050 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
10051 (VT == MVT::v2f64 || VT == MVT::v2i64))
10052 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10054 if (isPSHUFDMask(M, VT)) {
10055 // The actual implementation will match the mask in the if above and then
10056 // during isel it can match several different instructions, not only pshufd
10057 // as its name says, sad but true, emulate the behavior for now...
10058 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
10059 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
10061 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
10063 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
10064 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
10066 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
10067 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
10070 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
10074 if (isPALIGNRMask(M, VT, Subtarget))
10075 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
10076 getShufflePALIGNRImmediate(SVOp),
10079 if (isVALIGNMask(M, VT, Subtarget))
10080 return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
10081 getShuffleVALIGNImmediate(SVOp),
10084 // Check if this can be converted into a logical shift.
10085 bool isLeft = false;
10086 unsigned ShAmt = 0;
10088 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
10089 if (isShift && ShVal.hasOneUse()) {
10090 // If the shifted value has multiple uses, it may be cheaper to use
10091 // v_set0 + movlhps or movhlps, etc.
10092 MVT EltVT = VT.getVectorElementType();
10093 ShAmt *= EltVT.getSizeInBits();
10094 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10097 if (isMOVLMask(M, VT)) {
10098 if (ISD::isBuildVectorAllZeros(V1.getNode()))
10099 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
10100 if (!isMOVLPMask(M, VT)) {
10101 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
10102 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10104 if (VT == MVT::v4i32 || VT == MVT::v4f32)
10105 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10109 // FIXME: fold these into legal mask.
10110 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
10111 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
10113 if (isMOVHLPSMask(M, VT))
10114 return getMOVHighToLow(Op, dl, DAG);
10116 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
10117 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
10119 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
10120 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
10122 if (isMOVLPMask(M, VT))
10123 return getMOVLP(Op, dl, DAG, HasSSE2);
10125 if (ShouldXformToMOVHLPS(M, VT) ||
10126 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
10127 return DAG.getCommutedVectorShuffle(*SVOp);
10130 // No better options. Use a vshldq / vsrldq.
10131 MVT EltVT = VT.getVectorElementType();
10132 ShAmt *= EltVT.getSizeInBits();
10133 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10136 bool Commuted = false;
10137 // FIXME: This should also accept a bitcast of a splat? Be careful, not
10138 // 1,1,1,1 -> v8i16 though.
10139 BitVector UndefElements;
10140 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
10141 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10143 if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
10144 if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10147 // Canonicalize the splat or undef, if present, to be on the RHS.
10148 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
10149 CommuteVectorShuffleMask(M, NumElems);
10151 std::swap(V1IsSplat, V2IsSplat);
10155 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
10156 // Shuffling low element of v1 into undef, just return v1.
10159 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
10160 // the instruction selector will not match, so get a canonical MOVL with
10161 // swapped operands to undo the commute.
10162 return getMOVL(DAG, dl, VT, V2, V1);
10165 if (isUNPCKLMask(M, VT, HasInt256))
10166 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10168 if (isUNPCKHMask(M, VT, HasInt256))
10169 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10172 // Normalize mask so all entries that point to V2 points to its first
10173 // element then try to match unpck{h|l} again. If match, return a
10174 // new vector_shuffle with the corrected mask.p
10175 SmallVector<int, 8> NewMask(M.begin(), M.end());
10176 NormalizeMask(NewMask, NumElems);
10177 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
10178 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10179 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
10180 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10184 // Commute is back and try unpck* again.
10185 // FIXME: this seems wrong.
10186 CommuteVectorShuffleMask(M, NumElems);
10188 std::swap(V1IsSplat, V2IsSplat);
10190 if (isUNPCKLMask(M, VT, HasInt256))
10191 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10193 if (isUNPCKHMask(M, VT, HasInt256))
10194 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10197 // Normalize the node to match x86 shuffle ops if needed
10198 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
10199 return DAG.getCommutedVectorShuffle(*SVOp);
10201 // The checks below are all present in isShuffleMaskLegal, but they are
10202 // inlined here right now to enable us to directly emit target specific
10203 // nodes, and remove one by one until they don't return Op anymore.
10205 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
10206 SVOp->getSplatIndex() == 0 && V2IsUndef) {
10207 if (VT == MVT::v2f64 || VT == MVT::v2i64)
10208 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10211 if (isPSHUFHWMask(M, VT, HasInt256))
10212 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
10213 getShufflePSHUFHWImmediate(SVOp),
10216 if (isPSHUFLWMask(M, VT, HasInt256))
10217 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
10218 getShufflePSHUFLWImmediate(SVOp),
10221 unsigned MaskValue;
10222 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
10224 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
10226 if (isSHUFPMask(M, VT))
10227 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
10228 getShuffleSHUFImmediate(SVOp), DAG);
10230 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10231 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10232 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10233 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10235 //===--------------------------------------------------------------------===//
10236 // Generate target specific nodes for 128 or 256-bit shuffles only
10237 // supported in the AVX instruction set.
10240 // Handle VMOVDDUPY permutations
10241 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
10242 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
10244 // Handle VPERMILPS/D* permutations
10245 if (isVPERMILPMask(M, VT)) {
10246 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
10247 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
10248 getShuffleSHUFImmediate(SVOp), DAG);
10249 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
10250 getShuffleSHUFImmediate(SVOp), DAG);
10254 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
10255 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
10256 Idx*(NumElems/2), DAG, dl);
10258 // Handle VPERM2F128/VPERM2I128 permutations
10259 if (isVPERM2X128Mask(M, VT, HasFp256))
10260 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
10261 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
10263 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
10264 return getINSERTPS(SVOp, dl, DAG);
10267 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
10268 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
10270 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
10271 VT.is512BitVector()) {
10272 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
10273 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
10274 SmallVector<SDValue, 16> permclMask;
10275 for (unsigned i = 0; i != NumElems; ++i) {
10276 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
10279 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
10281 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
10282 return DAG.getNode(X86ISD::VPERMV, dl, VT,
10283 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
10284 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
10285 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
10288 //===--------------------------------------------------------------------===//
10289 // Since no target specific shuffle was selected for this generic one,
10290 // lower it into other known shuffles. FIXME: this isn't true yet, but
10291 // this is the plan.
10294 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
10295 if (VT == MVT::v8i16) {
10296 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
10297 if (NewOp.getNode())
10301 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
10302 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
10303 if (NewOp.getNode())
10307 if (VT == MVT::v16i8) {
10308 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
10309 if (NewOp.getNode())
10313 if (VT == MVT::v32i8) {
10314 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
10315 if (NewOp.getNode())
10319 // Handle all 128-bit wide vectors with 4 elements, and match them with
10320 // several different shuffle types.
10321 if (NumElems == 4 && VT.is128BitVector())
10322 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
10324 // Handle general 256-bit shuffles
10325 if (VT.is256BitVector())
10326 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
10331 // This function assumes its argument is a BUILD_VECTOR of constants or
10332 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10334 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10335 unsigned &MaskValue) {
10337 unsigned NumElems = BuildVector->getNumOperands();
10338 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10339 unsigned NumLanes = (NumElems - 1) / 8 + 1;
10340 unsigned NumElemsInLane = NumElems / NumLanes;
10342 // Blend for v16i16 should be symetric for the both lanes.
10343 for (unsigned i = 0; i < NumElemsInLane; ++i) {
10344 SDValue EltCond = BuildVector->getOperand(i);
10345 SDValue SndLaneEltCond =
10346 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10348 int Lane1Cond = -1, Lane2Cond = -1;
10349 if (isa<ConstantSDNode>(EltCond))
10350 Lane1Cond = !isZero(EltCond);
10351 if (isa<ConstantSDNode>(SndLaneEltCond))
10352 Lane2Cond = !isZero(SndLaneEltCond);
10354 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10355 // Lane1Cond != 0, means we want the first argument.
10356 // Lane1Cond == 0, means we want the second argument.
10357 // The encoding of this argument is 0 for the first argument, 1
10358 // for the second. Therefore, invert the condition.
10359 MaskValue |= !Lane1Cond << i;
10360 else if (Lane1Cond < 0)
10361 MaskValue |= !Lane2Cond << i;
10368 // Try to lower a vselect node into a simple blend instruction.
10369 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
10370 SelectionDAG &DAG) {
10371 SDValue Cond = Op.getOperand(0);
10372 SDValue LHS = Op.getOperand(1);
10373 SDValue RHS = Op.getOperand(2);
10375 MVT VT = Op.getSimpleValueType();
10376 MVT EltVT = VT.getVectorElementType();
10377 unsigned NumElems = VT.getVectorNumElements();
10379 // There is no blend with immediate in AVX-512.
10380 if (VT.is512BitVector())
10383 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10385 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10388 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10391 // Check the mask for BLEND and build the value.
10392 unsigned MaskValue = 0;
10393 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10396 // Convert i32 vectors to floating point if it is not AVX2.
10397 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10399 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10400 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10402 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10403 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10406 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10407 DAG.getConstant(MaskValue, MVT::i32));
10408 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10411 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10412 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10413 if (BlendOp.getNode())
10416 // Some types for vselect were previously set to Expand, not Legal or
10417 // Custom. Return an empty SDValue so we fall-through to Expand, after
10418 // the Custom lowering phase.
10419 MVT VT = Op.getSimpleValueType();
10420 switch (VT.SimpleTy) {
10428 // We couldn't create a "Blend with immediate" node.
10429 // This node should still be legal, but we'll have to emit a blendv*
10434 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10435 MVT VT = Op.getSimpleValueType();
10438 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10441 if (VT.getSizeInBits() == 8) {
10442 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10443 Op.getOperand(0), Op.getOperand(1));
10444 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10445 DAG.getValueType(VT));
10446 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10449 if (VT.getSizeInBits() == 16) {
10450 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10451 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10453 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10454 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10455 DAG.getNode(ISD::BITCAST, dl,
10458 Op.getOperand(1)));
10459 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10460 Op.getOperand(0), Op.getOperand(1));
10461 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10462 DAG.getValueType(VT));
10463 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10466 if (VT == MVT::f32) {
10467 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10468 // the result back to FR32 register. It's only worth matching if the
10469 // result has a single use which is a store or a bitcast to i32. And in
10470 // the case of a store, it's not worth it if the index is a constant 0,
10471 // because a MOVSSmr can be used instead, which is smaller and faster.
10472 if (!Op.hasOneUse())
10474 SDNode *User = *Op.getNode()->use_begin();
10475 if ((User->getOpcode() != ISD::STORE ||
10476 (isa<ConstantSDNode>(Op.getOperand(1)) &&
10477 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10478 (User->getOpcode() != ISD::BITCAST ||
10479 User->getValueType(0) != MVT::i32))
10481 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10482 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10485 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10488 if (VT == MVT::i32 || VT == MVT::i64) {
10489 // ExtractPS/pextrq works with constant index.
10490 if (isa<ConstantSDNode>(Op.getOperand(1)))
10496 /// Extract one bit from mask vector, like v16i1 or v8i1.
10497 /// AVX-512 feature.
10499 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10500 SDValue Vec = Op.getOperand(0);
10502 MVT VecVT = Vec.getSimpleValueType();
10503 SDValue Idx = Op.getOperand(1);
10504 MVT EltVT = Op.getSimpleValueType();
10506 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10508 // variable index can't be handled in mask registers,
10509 // extend vector to VR512
10510 if (!isa<ConstantSDNode>(Idx)) {
10511 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10512 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10513 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10514 ExtVT.getVectorElementType(), Ext, Idx);
10515 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10518 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10519 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10520 unsigned MaxSift = rc->getSize()*8 - 1;
10521 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10522 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10523 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10524 DAG.getConstant(MaxSift, MVT::i8));
10525 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10526 DAG.getIntPtrConstant(0));
10530 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10531 SelectionDAG &DAG) const {
10533 SDValue Vec = Op.getOperand(0);
10534 MVT VecVT = Vec.getSimpleValueType();
10535 SDValue Idx = Op.getOperand(1);
10537 if (Op.getSimpleValueType() == MVT::i1)
10538 return ExtractBitFromMaskVector(Op, DAG);
10540 if (!isa<ConstantSDNode>(Idx)) {
10541 if (VecVT.is512BitVector() ||
10542 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10543 VecVT.getVectorElementType().getSizeInBits() == 32)) {
10546 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10547 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10548 MaskEltVT.getSizeInBits());
10550 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10551 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10552 getZeroVector(MaskVT, Subtarget, DAG, dl),
10553 Idx, DAG.getConstant(0, getPointerTy()));
10554 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10555 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10556 Perm, DAG.getConstant(0, getPointerTy()));
10561 // If this is a 256-bit vector result, first extract the 128-bit vector and
10562 // then extract the element from the 128-bit vector.
10563 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10565 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10566 // Get the 128-bit vector.
10567 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10568 MVT EltVT = VecVT.getVectorElementType();
10570 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10572 //if (IdxVal >= NumElems/2)
10573 // IdxVal -= NumElems/2;
10574 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10575 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10576 DAG.getConstant(IdxVal, MVT::i32));
10579 assert(VecVT.is128BitVector() && "Unexpected vector length");
10581 if (Subtarget->hasSSE41()) {
10582 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10587 MVT VT = Op.getSimpleValueType();
10588 // TODO: handle v16i8.
10589 if (VT.getSizeInBits() == 16) {
10590 SDValue Vec = Op.getOperand(0);
10591 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10593 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10594 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10595 DAG.getNode(ISD::BITCAST, dl,
10597 Op.getOperand(1)));
10598 // Transform it so it match pextrw which produces a 32-bit result.
10599 MVT EltVT = MVT::i32;
10600 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10601 Op.getOperand(0), Op.getOperand(1));
10602 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10603 DAG.getValueType(VT));
10604 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10607 if (VT.getSizeInBits() == 32) {
10608 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10612 // SHUFPS the element to the lowest double word, then movss.
10613 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10614 MVT VVT = Op.getOperand(0).getSimpleValueType();
10615 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10616 DAG.getUNDEF(VVT), Mask);
10617 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10618 DAG.getIntPtrConstant(0));
10621 if (VT.getSizeInBits() == 64) {
10622 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10623 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10624 // to match extract_elt for f64.
10625 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10629 // UNPCKHPD the element to the lowest double word, then movsd.
10630 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10631 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10632 int Mask[2] = { 1, -1 };
10633 MVT VVT = Op.getOperand(0).getSimpleValueType();
10634 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10635 DAG.getUNDEF(VVT), Mask);
10636 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10637 DAG.getIntPtrConstant(0));
10643 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10644 MVT VT = Op.getSimpleValueType();
10645 MVT EltVT = VT.getVectorElementType();
10648 SDValue N0 = Op.getOperand(0);
10649 SDValue N1 = Op.getOperand(1);
10650 SDValue N2 = Op.getOperand(2);
10652 if (!VT.is128BitVector())
10655 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
10656 isa<ConstantSDNode>(N2)) {
10658 if (VT == MVT::v8i16)
10659 Opc = X86ISD::PINSRW;
10660 else if (VT == MVT::v16i8)
10661 Opc = X86ISD::PINSRB;
10663 Opc = X86ISD::PINSRB;
10665 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10667 if (N1.getValueType() != MVT::i32)
10668 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10669 if (N2.getValueType() != MVT::i32)
10670 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10671 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10674 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
10675 // Bits [7:6] of the constant are the source select. This will always be
10676 // zero here. The DAG Combiner may combine an extract_elt index into these
10677 // bits. For example (insert (extract, 3), 2) could be matched by putting
10678 // the '3' into bits [7:6] of X86ISD::INSERTPS.
10679 // Bits [5:4] of the constant are the destination select. This is the
10680 // value of the incoming immediate.
10681 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10682 // combine either bitwise AND or insert of float 0.0 to set these bits.
10683 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10684 // Create this as a scalar to vector..
10685 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10686 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10689 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10690 // PINSR* works with constant index.
10696 /// Insert one bit to mask vector, like v16i1 or v8i1.
10697 /// AVX-512 feature.
10699 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10701 SDValue Vec = Op.getOperand(0);
10702 SDValue Elt = Op.getOperand(1);
10703 SDValue Idx = Op.getOperand(2);
10704 MVT VecVT = Vec.getSimpleValueType();
10706 if (!isa<ConstantSDNode>(Idx)) {
10707 // Non constant index. Extend source and destination,
10708 // insert element and then truncate the result.
10709 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
10710 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
10711 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10712 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10713 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10714 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10717 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10718 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10719 if (Vec.getOpcode() == ISD::UNDEF)
10720 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10721 DAG.getConstant(IdxVal, MVT::i8));
10722 const TargetRegisterClass* rc = getRegClassFor(VecVT);
10723 unsigned MaxSift = rc->getSize()*8 - 1;
10724 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10725 DAG.getConstant(MaxSift, MVT::i8));
10726 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10727 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10728 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10731 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10732 MVT VT = Op.getSimpleValueType();
10733 MVT EltVT = VT.getVectorElementType();
10735 if (EltVT == MVT::i1)
10736 return InsertBitToMaskVector(Op, DAG);
10739 SDValue N0 = Op.getOperand(0);
10740 SDValue N1 = Op.getOperand(1);
10741 SDValue N2 = Op.getOperand(2);
10743 // If this is a 256-bit vector result, first extract the 128-bit vector,
10744 // insert the element into the extracted half and then place it back.
10745 if (VT.is256BitVector() || VT.is512BitVector()) {
10746 if (!isa<ConstantSDNode>(N2))
10749 // Get the desired 128-bit vector half.
10750 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10751 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10753 // Insert the element into the desired half.
10754 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10755 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10757 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10758 DAG.getConstant(IdxIn128, MVT::i32));
10760 // Insert the changed part back to the 256-bit vector
10761 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10764 if (Subtarget->hasSSE41())
10765 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10767 if (EltVT == MVT::i8)
10770 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10771 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10772 // as its second argument.
10773 if (N1.getValueType() != MVT::i32)
10774 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10775 if (N2.getValueType() != MVT::i32)
10776 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10777 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10782 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10784 MVT OpVT = Op.getSimpleValueType();
10786 // If this is a 256-bit vector result, first insert into a 128-bit
10787 // vector and then insert into the 256-bit vector.
10788 if (!OpVT.is128BitVector()) {
10789 // Insert into a 128-bit vector.
10790 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10791 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10792 OpVT.getVectorNumElements() / SizeFactor);
10794 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10796 // Insert the 128-bit vector.
10797 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10800 if (OpVT == MVT::v1i64 &&
10801 Op.getOperand(0).getValueType() == MVT::i64)
10802 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10804 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10805 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10806 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10807 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10810 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10811 // a simple subregister reference or explicit instructions to grab
10812 // upper bits of a vector.
10813 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10814 SelectionDAG &DAG) {
10816 SDValue In = Op.getOperand(0);
10817 SDValue Idx = Op.getOperand(1);
10818 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10819 MVT ResVT = Op.getSimpleValueType();
10820 MVT InVT = In.getSimpleValueType();
10822 if (Subtarget->hasFp256()) {
10823 if (ResVT.is128BitVector() &&
10824 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10825 isa<ConstantSDNode>(Idx)) {
10826 return Extract128BitVector(In, IdxVal, DAG, dl);
10828 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10829 isa<ConstantSDNode>(Idx)) {
10830 return Extract256BitVector(In, IdxVal, DAG, dl);
10836 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10837 // simple superregister reference or explicit instructions to insert
10838 // the upper bits of a vector.
10839 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10840 SelectionDAG &DAG) {
10841 if (Subtarget->hasFp256()) {
10842 SDLoc dl(Op.getNode());
10843 SDValue Vec = Op.getNode()->getOperand(0);
10844 SDValue SubVec = Op.getNode()->getOperand(1);
10845 SDValue Idx = Op.getNode()->getOperand(2);
10847 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10848 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10849 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10850 isa<ConstantSDNode>(Idx)) {
10851 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10852 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10855 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10856 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10857 isa<ConstantSDNode>(Idx)) {
10858 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10859 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10865 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10866 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10867 // one of the above mentioned nodes. It has to be wrapped because otherwise
10868 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10869 // be used to form addressing mode. These wrapped nodes will be selected
10872 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10873 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10875 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10876 // global base reg.
10877 unsigned char OpFlag = 0;
10878 unsigned WrapperKind = X86ISD::Wrapper;
10879 CodeModel::Model M = DAG.getTarget().getCodeModel();
10881 if (Subtarget->isPICStyleRIPRel() &&
10882 (M == CodeModel::Small || M == CodeModel::Kernel))
10883 WrapperKind = X86ISD::WrapperRIP;
10884 else if (Subtarget->isPICStyleGOT())
10885 OpFlag = X86II::MO_GOTOFF;
10886 else if (Subtarget->isPICStyleStubPIC())
10887 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10889 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10890 CP->getAlignment(),
10891 CP->getOffset(), OpFlag);
10893 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10894 // With PIC, the address is actually $g + Offset.
10896 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10897 DAG.getNode(X86ISD::GlobalBaseReg,
10898 SDLoc(), getPointerTy()),
10905 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10906 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10908 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10909 // global base reg.
10910 unsigned char OpFlag = 0;
10911 unsigned WrapperKind = X86ISD::Wrapper;
10912 CodeModel::Model M = DAG.getTarget().getCodeModel();
10914 if (Subtarget->isPICStyleRIPRel() &&
10915 (M == CodeModel::Small || M == CodeModel::Kernel))
10916 WrapperKind = X86ISD::WrapperRIP;
10917 else if (Subtarget->isPICStyleGOT())
10918 OpFlag = X86II::MO_GOTOFF;
10919 else if (Subtarget->isPICStyleStubPIC())
10920 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10922 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10925 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10927 // With PIC, the address is actually $g + Offset.
10929 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10930 DAG.getNode(X86ISD::GlobalBaseReg,
10931 SDLoc(), getPointerTy()),
10938 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10939 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10941 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10942 // global base reg.
10943 unsigned char OpFlag = 0;
10944 unsigned WrapperKind = X86ISD::Wrapper;
10945 CodeModel::Model M = DAG.getTarget().getCodeModel();
10947 if (Subtarget->isPICStyleRIPRel() &&
10948 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10949 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10950 OpFlag = X86II::MO_GOTPCREL;
10951 WrapperKind = X86ISD::WrapperRIP;
10952 } else if (Subtarget->isPICStyleGOT()) {
10953 OpFlag = X86II::MO_GOT;
10954 } else if (Subtarget->isPICStyleStubPIC()) {
10955 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10956 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10957 OpFlag = X86II::MO_DARWIN_NONLAZY;
10960 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10963 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10965 // With PIC, the address is actually $g + Offset.
10966 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10967 !Subtarget->is64Bit()) {
10968 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10969 DAG.getNode(X86ISD::GlobalBaseReg,
10970 SDLoc(), getPointerTy()),
10974 // For symbols that require a load from a stub to get the address, emit the
10976 if (isGlobalStubReference(OpFlag))
10977 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10978 MachinePointerInfo::getGOT(), false, false, false, 0);
10984 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10985 // Create the TargetBlockAddressAddress node.
10986 unsigned char OpFlags =
10987 Subtarget->ClassifyBlockAddressReference();
10988 CodeModel::Model M = DAG.getTarget().getCodeModel();
10989 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10990 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10992 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10995 if (Subtarget->isPICStyleRIPRel() &&
10996 (M == CodeModel::Small || M == CodeModel::Kernel))
10997 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10999 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11001 // With PIC, the address is actually $g + Offset.
11002 if (isGlobalRelativeToPICBase(OpFlags)) {
11003 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11004 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11012 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11013 int64_t Offset, SelectionDAG &DAG) const {
11014 // Create the TargetGlobalAddress node, folding in the constant
11015 // offset if it is legal.
11016 unsigned char OpFlags =
11017 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11018 CodeModel::Model M = DAG.getTarget().getCodeModel();
11020 if (OpFlags == X86II::MO_NO_FLAG &&
11021 X86::isOffsetSuitableForCodeModel(Offset, M)) {
11022 // A direct static reference to a global.
11023 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11026 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11029 if (Subtarget->isPICStyleRIPRel() &&
11030 (M == CodeModel::Small || M == CodeModel::Kernel))
11031 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11033 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11035 // With PIC, the address is actually $g + Offset.
11036 if (isGlobalRelativeToPICBase(OpFlags)) {
11037 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11038 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11042 // For globals that require a load from a stub to get the address, emit the
11044 if (isGlobalStubReference(OpFlags))
11045 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11046 MachinePointerInfo::getGOT(), false, false, false, 0);
11048 // If there was a non-zero offset that we didn't fold, create an explicit
11049 // addition for it.
11051 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11052 DAG.getConstant(Offset, getPointerTy()));
11058 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11059 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11060 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11061 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11065 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11066 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11067 unsigned char OperandFlags, bool LocalDynamic = false) {
11068 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11069 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11071 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11072 GA->getValueType(0),
11076 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11080 SDValue Ops[] = { Chain, TGA, *InFlag };
11081 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11083 SDValue Ops[] = { Chain, TGA };
11084 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11087 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11088 MFI->setAdjustsStack(true);
11090 SDValue Flag = Chain.getValue(1);
11091 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11094 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11096 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11099 SDLoc dl(GA); // ? function entry point might be better
11100 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11101 DAG.getNode(X86ISD::GlobalBaseReg,
11102 SDLoc(), PtrVT), InFlag);
11103 InFlag = Chain.getValue(1);
11105 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11108 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11110 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11112 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11113 X86::RAX, X86II::MO_TLSGD);
11116 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11122 // Get the start address of the TLS block for this module.
11123 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11124 .getInfo<X86MachineFunctionInfo>();
11125 MFI->incNumLocalDynamicTLSAccesses();
11129 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11130 X86II::MO_TLSLD, /*LocalDynamic=*/true);
11133 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11134 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11135 InFlag = Chain.getValue(1);
11136 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11137 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11140 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11144 unsigned char OperandFlags = X86II::MO_DTPOFF;
11145 unsigned WrapperKind = X86ISD::Wrapper;
11146 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11147 GA->getValueType(0),
11148 GA->getOffset(), OperandFlags);
11149 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11151 // Add x@dtpoff with the base.
11152 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11155 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11156 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11157 const EVT PtrVT, TLSModel::Model model,
11158 bool is64Bit, bool isPIC) {
11161 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11162 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11163 is64Bit ? 257 : 256));
11165 SDValue ThreadPointer =
11166 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11167 MachinePointerInfo(Ptr), false, false, false, 0);
11169 unsigned char OperandFlags = 0;
11170 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
11172 unsigned WrapperKind = X86ISD::Wrapper;
11173 if (model == TLSModel::LocalExec) {
11174 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11175 } else if (model == TLSModel::InitialExec) {
11177 OperandFlags = X86II::MO_GOTTPOFF;
11178 WrapperKind = X86ISD::WrapperRIP;
11180 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11183 llvm_unreachable("Unexpected model");
11186 // emit "addl x@ntpoff,%eax" (local exec)
11187 // or "addl x@indntpoff,%eax" (initial exec)
11188 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11190 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11191 GA->getOffset(), OperandFlags);
11192 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11194 if (model == TLSModel::InitialExec) {
11195 if (isPIC && !is64Bit) {
11196 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11197 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11201 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11202 MachinePointerInfo::getGOT(), false, false, false, 0);
11205 // The address of the thread local variable is the add of the thread
11206 // pointer with the offset of the variable.
11207 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11211 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11213 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11214 const GlobalValue *GV = GA->getGlobal();
11216 if (Subtarget->isTargetELF()) {
11217 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11220 case TLSModel::GeneralDynamic:
11221 if (Subtarget->is64Bit())
11222 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11223 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11224 case TLSModel::LocalDynamic:
11225 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11226 Subtarget->is64Bit());
11227 case TLSModel::InitialExec:
11228 case TLSModel::LocalExec:
11229 return LowerToTLSExecModel(
11230 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11231 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11233 llvm_unreachable("Unknown TLS model.");
11236 if (Subtarget->isTargetDarwin()) {
11237 // Darwin only has one model of TLS. Lower to that.
11238 unsigned char OpFlag = 0;
11239 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11240 X86ISD::WrapperRIP : X86ISD::Wrapper;
11242 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11243 // global base reg.
11244 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11245 !Subtarget->is64Bit();
11247 OpFlag = X86II::MO_TLVP_PIC_BASE;
11249 OpFlag = X86II::MO_TLVP;
11251 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11252 GA->getValueType(0),
11253 GA->getOffset(), OpFlag);
11254 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11256 // With PIC32, the address is actually $g + Offset.
11258 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11259 DAG.getNode(X86ISD::GlobalBaseReg,
11260 SDLoc(), getPointerTy()),
11263 // Lowering the machine isd will make sure everything is in the right
11265 SDValue Chain = DAG.getEntryNode();
11266 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11267 SDValue Args[] = { Chain, Offset };
11268 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11270 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11271 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11272 MFI->setAdjustsStack(true);
11274 // And our return value (tls address) is in the standard call return value
11276 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11277 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11278 Chain.getValue(1));
11281 if (Subtarget->isTargetKnownWindowsMSVC() ||
11282 Subtarget->isTargetWindowsGNU()) {
11283 // Just use the implicit TLS architecture
11284 // Need to generate someting similar to:
11285 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11287 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
11288 // mov rcx, qword [rdx+rcx*8]
11289 // mov eax, .tls$:tlsvar
11290 // [rax+rcx] contains the address
11291 // Windows 64bit: gs:0x58
11292 // Windows 32bit: fs:__tls_array
11295 SDValue Chain = DAG.getEntryNode();
11297 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11298 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11299 // use its literal value of 0x2C.
11300 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11301 ? Type::getInt8PtrTy(*DAG.getContext(),
11303 : Type::getInt32PtrTy(*DAG.getContext(),
11307 Subtarget->is64Bit()
11308 ? DAG.getIntPtrConstant(0x58)
11309 : (Subtarget->isTargetWindowsGNU()
11310 ? DAG.getIntPtrConstant(0x2C)
11311 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11313 SDValue ThreadPointer =
11314 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11315 MachinePointerInfo(Ptr), false, false, false, 0);
11317 // Load the _tls_index variable
11318 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11319 if (Subtarget->is64Bit())
11320 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11321 IDX, MachinePointerInfo(), MVT::i32,
11322 false, false, false, 0);
11324 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11325 false, false, false, 0);
11327 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11329 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11331 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11332 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11333 false, false, false, 0);
11335 // Get the offset of start of .tls section
11336 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11337 GA->getValueType(0),
11338 GA->getOffset(), X86II::MO_SECREL);
11339 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11341 // The address of the thread local variable is the add of the thread
11342 // pointer with the offset of the variable.
11343 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11346 llvm_unreachable("TLS not implemented for this target.");
11349 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11350 /// and take a 2 x i32 value to shift plus a shift amount.
11351 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11352 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11353 MVT VT = Op.getSimpleValueType();
11354 unsigned VTBits = VT.getSizeInBits();
11356 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11357 SDValue ShOpLo = Op.getOperand(0);
11358 SDValue ShOpHi = Op.getOperand(1);
11359 SDValue ShAmt = Op.getOperand(2);
11360 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11361 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11363 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11364 DAG.getConstant(VTBits - 1, MVT::i8));
11365 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11366 DAG.getConstant(VTBits - 1, MVT::i8))
11367 : DAG.getConstant(0, VT);
11369 SDValue Tmp2, Tmp3;
11370 if (Op.getOpcode() == ISD::SHL_PARTS) {
11371 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11372 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11374 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11375 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11378 // If the shift amount is larger or equal than the width of a part we can't
11379 // rely on the results of shld/shrd. Insert a test and select the appropriate
11380 // values for large shift amounts.
11381 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11382 DAG.getConstant(VTBits, MVT::i8));
11383 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11384 AndNode, DAG.getConstant(0, MVT::i8));
11387 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11388 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11389 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11391 if (Op.getOpcode() == ISD::SHL_PARTS) {
11392 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11393 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11395 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11396 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11399 SDValue Ops[2] = { Lo, Hi };
11400 return DAG.getMergeValues(Ops, dl);
11403 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11404 SelectionDAG &DAG) const {
11405 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11407 if (SrcVT.isVector())
11410 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11411 "Unknown SINT_TO_FP to lower!");
11413 // These are really Legal; return the operand so the caller accepts it as
11415 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11417 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11418 Subtarget->is64Bit()) {
11423 unsigned Size = SrcVT.getSizeInBits()/8;
11424 MachineFunction &MF = DAG.getMachineFunction();
11425 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11426 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11427 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11429 MachinePointerInfo::getFixedStack(SSFI),
11431 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11434 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11436 SelectionDAG &DAG) const {
11440 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11442 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11444 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11446 unsigned ByteSize = SrcVT.getSizeInBits()/8;
11448 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11449 MachineMemOperand *MMO;
11451 int SSFI = FI->getIndex();
11453 DAG.getMachineFunction()
11454 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11455 MachineMemOperand::MOLoad, ByteSize, ByteSize);
11457 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11458 StackSlot = StackSlot.getOperand(1);
11460 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11461 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11463 Tys, Ops, SrcVT, MMO);
11466 Chain = Result.getValue(1);
11467 SDValue InFlag = Result.getValue(2);
11469 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11470 // shouldn't be necessary except that RFP cannot be live across
11471 // multiple blocks. When stackifier is fixed, they can be uncoupled.
11472 MachineFunction &MF = DAG.getMachineFunction();
11473 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11474 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11475 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11476 Tys = DAG.getVTList(MVT::Other);
11478 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11480 MachineMemOperand *MMO =
11481 DAG.getMachineFunction()
11482 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11483 MachineMemOperand::MOStore, SSFISize, SSFISize);
11485 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11486 Ops, Op.getValueType(), MMO);
11487 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11488 MachinePointerInfo::getFixedStack(SSFI),
11489 false, false, false, 0);
11495 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11496 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11497 SelectionDAG &DAG) const {
11498 // This algorithm is not obvious. Here it is what we're trying to output:
11501 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11502 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11504 haddpd %xmm0, %xmm0
11506 pshufd $0x4e, %xmm0, %xmm1
11512 LLVMContext *Context = DAG.getContext();
11514 // Build some magic constants.
11515 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11516 Constant *C0 = ConstantDataVector::get(*Context, CV0);
11517 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11519 SmallVector<Constant*,2> CV1;
11521 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11522 APInt(64, 0x4330000000000000ULL))));
11524 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11525 APInt(64, 0x4530000000000000ULL))));
11526 Constant *C1 = ConstantVector::get(CV1);
11527 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11529 // Load the 64-bit value into an XMM register.
11530 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11532 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11533 MachinePointerInfo::getConstantPool(),
11534 false, false, false, 16);
11535 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11536 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11539 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11540 MachinePointerInfo::getConstantPool(),
11541 false, false, false, 16);
11542 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11543 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11546 if (Subtarget->hasSSE3()) {
11547 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11548 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11550 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11551 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11553 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11554 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11558 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11559 DAG.getIntPtrConstant(0));
11562 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11563 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11564 SelectionDAG &DAG) const {
11566 // FP constant to bias correct the final result.
11567 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11570 // Load the 32-bit value into an XMM register.
11571 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11574 // Zero out the upper parts of the register.
11575 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11577 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11578 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11579 DAG.getIntPtrConstant(0));
11581 // Or the load with the bias.
11582 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11583 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11584 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11585 MVT::v2f64, Load)),
11586 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11587 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11588 MVT::v2f64, Bias)));
11589 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11590 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11591 DAG.getIntPtrConstant(0));
11593 // Subtract the bias.
11594 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11596 // Handle final rounding.
11597 EVT DestVT = Op.getValueType();
11599 if (DestVT.bitsLT(MVT::f64))
11600 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11601 DAG.getIntPtrConstant(0));
11602 if (DestVT.bitsGT(MVT::f64))
11603 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11605 // Handle final rounding.
11609 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11610 SelectionDAG &DAG) const {
11611 SDValue N0 = Op.getOperand(0);
11612 MVT SVT = N0.getSimpleValueType();
11615 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11616 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11617 "Custom UINT_TO_FP is not supported!");
11619 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11620 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11621 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11624 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11625 SelectionDAG &DAG) const {
11626 SDValue N0 = Op.getOperand(0);
11629 if (Op.getValueType().isVector())
11630 return lowerUINT_TO_FP_vec(Op, DAG);
11632 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11633 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11634 // the optimization here.
11635 if (DAG.SignBitIsZero(N0))
11636 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11638 MVT SrcVT = N0.getSimpleValueType();
11639 MVT DstVT = Op.getSimpleValueType();
11640 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11641 return LowerUINT_TO_FP_i64(Op, DAG);
11642 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11643 return LowerUINT_TO_FP_i32(Op, DAG);
11644 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11647 // Make a 64-bit buffer, and use it to build an FILD.
11648 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11649 if (SrcVT == MVT::i32) {
11650 SDValue WordOff = DAG.getConstant(4, getPointerTy());
11651 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11652 getPointerTy(), StackSlot, WordOff);
11653 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11654 StackSlot, MachinePointerInfo(),
11656 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11657 OffsetSlot, MachinePointerInfo(),
11659 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11663 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11664 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11665 StackSlot, MachinePointerInfo(),
11667 // For i64 source, we need to add the appropriate power of 2 if the input
11668 // was negative. This is the same as the optimization in
11669 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11670 // we must be careful to do the computation in x87 extended precision, not
11671 // in SSE. (The generic code can't know it's OK to do this, or how to.)
11672 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11673 MachineMemOperand *MMO =
11674 DAG.getMachineFunction()
11675 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11676 MachineMemOperand::MOLoad, 8, 8);
11678 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11679 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11680 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11683 APInt FF(32, 0x5F800000ULL);
11685 // Check whether the sign bit is set.
11686 SDValue SignSet = DAG.getSetCC(dl,
11687 getSetCCResultType(*DAG.getContext(), MVT::i64),
11688 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11691 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11692 SDValue FudgePtr = DAG.getConstantPool(
11693 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11696 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11697 SDValue Zero = DAG.getIntPtrConstant(0);
11698 SDValue Four = DAG.getIntPtrConstant(4);
11699 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11701 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11703 // Load the value out, extending it from f32 to f80.
11704 // FIXME: Avoid the extend by constructing the right constant pool?
11705 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11706 FudgePtr, MachinePointerInfo::getConstantPool(),
11707 MVT::f32, false, false, false, 4);
11708 // Extend everything to 80 bits to force it to be done on x87.
11709 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11710 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11713 std::pair<SDValue,SDValue>
11714 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11715 bool IsSigned, bool IsReplace) const {
11718 EVT DstTy = Op.getValueType();
11720 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11721 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11725 assert(DstTy.getSimpleVT() <= MVT::i64 &&
11726 DstTy.getSimpleVT() >= MVT::i16 &&
11727 "Unknown FP_TO_INT to lower!");
11729 // These are really Legal.
11730 if (DstTy == MVT::i32 &&
11731 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11732 return std::make_pair(SDValue(), SDValue());
11733 if (Subtarget->is64Bit() &&
11734 DstTy == MVT::i64 &&
11735 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11736 return std::make_pair(SDValue(), SDValue());
11738 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11739 // stack slot, or into the FTOL runtime function.
11740 MachineFunction &MF = DAG.getMachineFunction();
11741 unsigned MemSize = DstTy.getSizeInBits()/8;
11742 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11743 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11746 if (!IsSigned && isIntegerTypeFTOL(DstTy))
11747 Opc = X86ISD::WIN_FTOL;
11749 switch (DstTy.getSimpleVT().SimpleTy) {
11750 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11751 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11752 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11753 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11756 SDValue Chain = DAG.getEntryNode();
11757 SDValue Value = Op.getOperand(0);
11758 EVT TheVT = Op.getOperand(0).getValueType();
11759 // FIXME This causes a redundant load/store if the SSE-class value is already
11760 // in memory, such as if it is on the callstack.
11761 if (isScalarFPTypeInSSEReg(TheVT)) {
11762 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11763 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11764 MachinePointerInfo::getFixedStack(SSFI),
11766 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11768 Chain, StackSlot, DAG.getValueType(TheVT)
11771 MachineMemOperand *MMO =
11772 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11773 MachineMemOperand::MOLoad, MemSize, MemSize);
11774 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11775 Chain = Value.getValue(1);
11776 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11777 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11780 MachineMemOperand *MMO =
11781 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11782 MachineMemOperand::MOStore, MemSize, MemSize);
11784 if (Opc != X86ISD::WIN_FTOL) {
11785 // Build the FP_TO_INT*_IN_MEM
11786 SDValue Ops[] = { Chain, Value, StackSlot };
11787 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11789 return std::make_pair(FIST, StackSlot);
11791 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11792 DAG.getVTList(MVT::Other, MVT::Glue),
11794 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11795 MVT::i32, ftol.getValue(1));
11796 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11797 MVT::i32, eax.getValue(2));
11798 SDValue Ops[] = { eax, edx };
11799 SDValue pair = IsReplace
11800 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11801 : DAG.getMergeValues(Ops, DL);
11802 return std::make_pair(pair, SDValue());
11806 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11807 const X86Subtarget *Subtarget) {
11808 MVT VT = Op->getSimpleValueType(0);
11809 SDValue In = Op->getOperand(0);
11810 MVT InVT = In.getSimpleValueType();
11813 // Optimize vectors in AVX mode:
11816 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11817 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11818 // Concat upper and lower parts.
11821 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11822 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11823 // Concat upper and lower parts.
11826 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11827 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11828 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11831 if (Subtarget->hasInt256())
11832 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11834 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11835 SDValue Undef = DAG.getUNDEF(InVT);
11836 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11837 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11838 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11840 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11841 VT.getVectorNumElements()/2);
11843 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11844 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11846 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11849 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11850 SelectionDAG &DAG) {
11851 MVT VT = Op->getSimpleValueType(0);
11852 SDValue In = Op->getOperand(0);
11853 MVT InVT = In.getSimpleValueType();
11855 unsigned int NumElts = VT.getVectorNumElements();
11856 if (NumElts != 8 && NumElts != 16)
11859 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11860 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11862 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11863 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11864 // Now we have only mask extension
11865 assert(InVT.getVectorElementType() == MVT::i1);
11866 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11867 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11868 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11869 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11870 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11871 MachinePointerInfo::getConstantPool(),
11872 false, false, false, Alignment);
11874 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11875 if (VT.is512BitVector())
11877 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11880 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11881 SelectionDAG &DAG) {
11882 if (Subtarget->hasFp256()) {
11883 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11891 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11892 SelectionDAG &DAG) {
11894 MVT VT = Op.getSimpleValueType();
11895 SDValue In = Op.getOperand(0);
11896 MVT SVT = In.getSimpleValueType();
11898 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11899 return LowerZERO_EXTEND_AVX512(Op, DAG);
11901 if (Subtarget->hasFp256()) {
11902 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11907 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11908 VT.getVectorNumElements() != SVT.getVectorNumElements());
11912 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11914 MVT VT = Op.getSimpleValueType();
11915 SDValue In = Op.getOperand(0);
11916 MVT InVT = In.getSimpleValueType();
11918 if (VT == MVT::i1) {
11919 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11920 "Invalid scalar TRUNCATE operation");
11921 if (InVT == MVT::i32)
11923 if (InVT.getSizeInBits() == 64)
11924 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11925 else if (InVT.getSizeInBits() < 32)
11926 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11927 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11929 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11930 "Invalid TRUNCATE operation");
11932 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11933 if (VT.getVectorElementType().getSizeInBits() >=8)
11934 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11936 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11937 unsigned NumElts = InVT.getVectorNumElements();
11938 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11939 if (InVT.getSizeInBits() < 512) {
11940 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11941 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11945 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11946 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11947 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11948 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11949 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11950 MachinePointerInfo::getConstantPool(),
11951 false, false, false, Alignment);
11952 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11953 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11954 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11957 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11958 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11959 if (Subtarget->hasInt256()) {
11960 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11961 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11962 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11964 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11965 DAG.getIntPtrConstant(0));
11968 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11969 DAG.getIntPtrConstant(0));
11970 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11971 DAG.getIntPtrConstant(2));
11972 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11973 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11974 static const int ShufMask[] = {0, 2, 4, 6};
11975 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11978 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11979 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11980 if (Subtarget->hasInt256()) {
11981 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11983 SmallVector<SDValue,32> pshufbMask;
11984 for (unsigned i = 0; i < 2; ++i) {
11985 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11986 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11987 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11988 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11989 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11990 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11991 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11992 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11993 for (unsigned j = 0; j < 8; ++j)
11994 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11996 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11997 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11998 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12000 static const int ShufMask[] = {0, 2, -1, -1};
12001 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
12003 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12004 DAG.getIntPtrConstant(0));
12005 return DAG.getNode(ISD::BITCAST, DL, VT, In);
12008 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12009 DAG.getIntPtrConstant(0));
12011 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12012 DAG.getIntPtrConstant(4));
12014 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12015 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12017 // The PSHUFB mask:
12018 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
12019 -1, -1, -1, -1, -1, -1, -1, -1};
12021 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12022 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12023 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12025 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12026 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12028 // The MOVLHPS Mask:
12029 static const int ShufMask2[] = {0, 1, 4, 5};
12030 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12031 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12034 // Handle truncation of V256 to V128 using shuffles.
12035 if (!VT.is128BitVector() || !InVT.is256BitVector())
12038 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12040 unsigned NumElems = VT.getVectorNumElements();
12041 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12043 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12044 // Prepare truncation shuffle mask
12045 for (unsigned i = 0; i != NumElems; ++i)
12046 MaskVec[i] = i * 2;
12047 SDValue V = DAG.getVectorShuffle(NVT, DL,
12048 DAG.getNode(ISD::BITCAST, DL, NVT, In),
12049 DAG.getUNDEF(NVT), &MaskVec[0]);
12050 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12051 DAG.getIntPtrConstant(0));
12054 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12055 SelectionDAG &DAG) const {
12056 assert(!Op.getSimpleValueType().isVector());
12058 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12059 /*IsSigned=*/ true, /*IsReplace=*/ false);
12060 SDValue FIST = Vals.first, StackSlot = Vals.second;
12061 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12062 if (!FIST.getNode()) return Op;
12064 if (StackSlot.getNode())
12065 // Load the result.
12066 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12067 FIST, StackSlot, MachinePointerInfo(),
12068 false, false, false, 0);
12070 // The node is the result.
12074 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12075 SelectionDAG &DAG) const {
12076 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12077 /*IsSigned=*/ false, /*IsReplace=*/ false);
12078 SDValue FIST = Vals.first, StackSlot = Vals.second;
12079 assert(FIST.getNode() && "Unexpected failure");
12081 if (StackSlot.getNode())
12082 // Load the result.
12083 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12084 FIST, StackSlot, MachinePointerInfo(),
12085 false, false, false, 0);
12087 // The node is the result.
12091 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12093 MVT VT = Op.getSimpleValueType();
12094 SDValue In = Op.getOperand(0);
12095 MVT SVT = In.getSimpleValueType();
12097 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12099 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12100 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12101 In, DAG.getUNDEF(SVT)));
12104 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
12105 LLVMContext *Context = DAG.getContext();
12107 MVT VT = Op.getSimpleValueType();
12109 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12110 if (VT.isVector()) {
12111 EltVT = VT.getVectorElementType();
12112 NumElts = VT.getVectorNumElements();
12115 if (EltVT == MVT::f64)
12116 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12117 APInt(64, ~(1ULL << 63))));
12119 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12120 APInt(32, ~(1U << 31))));
12121 C = ConstantVector::getSplat(NumElts, C);
12122 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12123 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12124 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12125 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12126 MachinePointerInfo::getConstantPool(),
12127 false, false, false, Alignment);
12128 if (VT.isVector()) {
12129 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12130 return DAG.getNode(ISD::BITCAST, dl, VT,
12131 DAG.getNode(ISD::AND, dl, ANDVT,
12132 DAG.getNode(ISD::BITCAST, dl, ANDVT,
12134 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
12136 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
12139 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
12140 LLVMContext *Context = DAG.getContext();
12142 MVT VT = Op.getSimpleValueType();
12144 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12145 if (VT.isVector()) {
12146 EltVT = VT.getVectorElementType();
12147 NumElts = VT.getVectorNumElements();
12150 if (EltVT == MVT::f64)
12151 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12152 APInt(64, 1ULL << 63)));
12154 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
12155 APInt(32, 1U << 31)));
12156 C = ConstantVector::getSplat(NumElts, C);
12157 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12158 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12159 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12160 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12161 MachinePointerInfo::getConstantPool(),
12162 false, false, false, Alignment);
12163 if (VT.isVector()) {
12164 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
12165 return DAG.getNode(ISD::BITCAST, dl, VT,
12166 DAG.getNode(ISD::XOR, dl, XORVT,
12167 DAG.getNode(ISD::BITCAST, dl, XORVT,
12169 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
12172 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
12175 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12176 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12177 LLVMContext *Context = DAG.getContext();
12178 SDValue Op0 = Op.getOperand(0);
12179 SDValue Op1 = Op.getOperand(1);
12181 MVT VT = Op.getSimpleValueType();
12182 MVT SrcVT = Op1.getSimpleValueType();
12184 // If second operand is smaller, extend it first.
12185 if (SrcVT.bitsLT(VT)) {
12186 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12189 // And if it is bigger, shrink it first.
12190 if (SrcVT.bitsGT(VT)) {
12191 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12195 // At this point the operands and the result should have the same
12196 // type, and that won't be f80 since that is not custom lowered.
12198 // First get the sign bit of second operand.
12199 SmallVector<Constant*,4> CV;
12200 if (SrcVT == MVT::f64) {
12201 const fltSemantics &Sem = APFloat::IEEEdouble;
12202 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
12203 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12205 const fltSemantics &Sem = APFloat::IEEEsingle;
12206 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
12207 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12208 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12209 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12211 Constant *C = ConstantVector::get(CV);
12212 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12213 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12214 MachinePointerInfo::getConstantPool(),
12215 false, false, false, 16);
12216 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12218 // Shift sign bit right or left if the two operands have different types.
12219 if (SrcVT.bitsGT(VT)) {
12220 // Op0 is MVT::f32, Op1 is MVT::f64.
12221 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
12222 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
12223 DAG.getConstant(32, MVT::i32));
12224 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
12225 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
12226 DAG.getIntPtrConstant(0));
12229 // Clear first operand sign bit.
12231 if (VT == MVT::f64) {
12232 const fltSemantics &Sem = APFloat::IEEEdouble;
12233 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12234 APInt(64, ~(1ULL << 63)))));
12235 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12237 const fltSemantics &Sem = APFloat::IEEEsingle;
12238 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12239 APInt(32, ~(1U << 31)))));
12240 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12241 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12242 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12244 C = ConstantVector::get(CV);
12245 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12246 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12247 MachinePointerInfo::getConstantPool(),
12248 false, false, false, 16);
12249 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
12251 // Or the value with the sign bit.
12252 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12255 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12256 SDValue N0 = Op.getOperand(0);
12258 MVT VT = Op.getSimpleValueType();
12260 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12261 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12262 DAG.getConstant(1, VT));
12263 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12266 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
12268 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12269 SelectionDAG &DAG) {
12270 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12272 if (!Subtarget->hasSSE41())
12275 if (!Op->hasOneUse())
12278 SDNode *N = Op.getNode();
12281 SmallVector<SDValue, 8> Opnds;
12282 DenseMap<SDValue, unsigned> VecInMap;
12283 SmallVector<SDValue, 8> VecIns;
12284 EVT VT = MVT::Other;
12286 // Recognize a special case where a vector is casted into wide integer to
12288 Opnds.push_back(N->getOperand(0));
12289 Opnds.push_back(N->getOperand(1));
12291 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12292 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12293 // BFS traverse all OR'd operands.
12294 if (I->getOpcode() == ISD::OR) {
12295 Opnds.push_back(I->getOperand(0));
12296 Opnds.push_back(I->getOperand(1));
12297 // Re-evaluate the number of nodes to be traversed.
12298 e += 2; // 2 more nodes (LHS and RHS) are pushed.
12302 // Quit if a non-EXTRACT_VECTOR_ELT
12303 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12306 // Quit if without a constant index.
12307 SDValue Idx = I->getOperand(1);
12308 if (!isa<ConstantSDNode>(Idx))
12311 SDValue ExtractedFromVec = I->getOperand(0);
12312 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12313 if (M == VecInMap.end()) {
12314 VT = ExtractedFromVec.getValueType();
12315 // Quit if not 128/256-bit vector.
12316 if (!VT.is128BitVector() && !VT.is256BitVector())
12318 // Quit if not the same type.
12319 if (VecInMap.begin() != VecInMap.end() &&
12320 VT != VecInMap.begin()->first.getValueType())
12322 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12323 VecIns.push_back(ExtractedFromVec);
12325 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12328 assert((VT.is128BitVector() || VT.is256BitVector()) &&
12329 "Not extracted from 128-/256-bit vector.");
12331 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12333 for (DenseMap<SDValue, unsigned>::const_iterator
12334 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12335 // Quit if not all elements are used.
12336 if (I->second != FullMask)
12340 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12342 // Cast all vectors into TestVT for PTEST.
12343 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12344 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12346 // If more than one full vectors are evaluated, OR them first before PTEST.
12347 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12348 // Each iteration will OR 2 nodes and append the result until there is only
12349 // 1 node left, i.e. the final OR'd value of all vectors.
12350 SDValue LHS = VecIns[Slot];
12351 SDValue RHS = VecIns[Slot + 1];
12352 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12355 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12356 VecIns.back(), VecIns.back());
12359 /// \brief return true if \c Op has a use that doesn't just read flags.
12360 static bool hasNonFlagsUse(SDValue Op) {
12361 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12363 SDNode *User = *UI;
12364 unsigned UOpNo = UI.getOperandNo();
12365 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12366 // Look pass truncate.
12367 UOpNo = User->use_begin().getOperandNo();
12368 User = *User->use_begin();
12371 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12372 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12378 /// Emit nodes that will be selected as "test Op0,Op0", or something
12380 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12381 SelectionDAG &DAG) const {
12382 if (Op.getValueType() == MVT::i1)
12383 // KORTEST instruction should be selected
12384 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12385 DAG.getConstant(0, Op.getValueType()));
12387 // CF and OF aren't always set the way we want. Determine which
12388 // of these we need.
12389 bool NeedCF = false;
12390 bool NeedOF = false;
12393 case X86::COND_A: case X86::COND_AE:
12394 case X86::COND_B: case X86::COND_BE:
12397 case X86::COND_G: case X86::COND_GE:
12398 case X86::COND_L: case X86::COND_LE:
12399 case X86::COND_O: case X86::COND_NO: {
12400 // Check if we really need to set the
12401 // Overflow flag. If NoSignedWrap is present
12402 // that is not actually needed.
12403 switch (Op->getOpcode()) {
12408 const BinaryWithFlagsSDNode *BinNode =
12409 cast<BinaryWithFlagsSDNode>(Op.getNode());
12410 if (BinNode->hasNoSignedWrap())
12420 // See if we can use the EFLAGS value from the operand instead of
12421 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12422 // we prove that the arithmetic won't overflow, we can't use OF or CF.
12423 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12424 // Emit a CMP with 0, which is the TEST pattern.
12425 //if (Op.getValueType() == MVT::i1)
12426 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12427 // DAG.getConstant(0, MVT::i1));
12428 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12429 DAG.getConstant(0, Op.getValueType()));
12431 unsigned Opcode = 0;
12432 unsigned NumOperands = 0;
12434 // Truncate operations may prevent the merge of the SETCC instruction
12435 // and the arithmetic instruction before it. Attempt to truncate the operands
12436 // of the arithmetic instruction and use a reduced bit-width instruction.
12437 bool NeedTruncation = false;
12438 SDValue ArithOp = Op;
12439 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12440 SDValue Arith = Op->getOperand(0);
12441 // Both the trunc and the arithmetic op need to have one user each.
12442 if (Arith->hasOneUse())
12443 switch (Arith.getOpcode()) {
12450 NeedTruncation = true;
12456 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12457 // which may be the result of a CAST. We use the variable 'Op', which is the
12458 // non-casted variable when we check for possible users.
12459 switch (ArithOp.getOpcode()) {
12461 // Due to an isel shortcoming, be conservative if this add is likely to be
12462 // selected as part of a load-modify-store instruction. When the root node
12463 // in a match is a store, isel doesn't know how to remap non-chain non-flag
12464 // uses of other nodes in the match, such as the ADD in this case. This
12465 // leads to the ADD being left around and reselected, with the result being
12466 // two adds in the output. Alas, even if none our users are stores, that
12467 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
12468 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
12469 // climbing the DAG back to the root, and it doesn't seem to be worth the
12471 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12472 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12473 if (UI->getOpcode() != ISD::CopyToReg &&
12474 UI->getOpcode() != ISD::SETCC &&
12475 UI->getOpcode() != ISD::STORE)
12478 if (ConstantSDNode *C =
12479 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12480 // An add of one will be selected as an INC.
12481 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12482 Opcode = X86ISD::INC;
12487 // An add of negative one (subtract of one) will be selected as a DEC.
12488 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12489 Opcode = X86ISD::DEC;
12495 // Otherwise use a regular EFLAGS-setting add.
12496 Opcode = X86ISD::ADD;
12501 // If we have a constant logical shift that's only used in a comparison
12502 // against zero turn it into an equivalent AND. This allows turning it into
12503 // a TEST instruction later.
12504 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12505 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12506 EVT VT = Op.getValueType();
12507 unsigned BitWidth = VT.getSizeInBits();
12508 unsigned ShAmt = Op->getConstantOperandVal(1);
12509 if (ShAmt >= BitWidth) // Avoid undefined shifts.
12511 APInt Mask = ArithOp.getOpcode() == ISD::SRL
12512 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12513 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12514 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12516 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12517 DAG.getConstant(Mask, VT));
12518 DAG.ReplaceAllUsesWith(Op, New);
12524 // If the primary and result isn't used, don't bother using X86ISD::AND,
12525 // because a TEST instruction will be better.
12526 if (!hasNonFlagsUse(Op))
12532 // Due to the ISEL shortcoming noted above, be conservative if this op is
12533 // likely to be selected as part of a load-modify-store instruction.
12534 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12535 UE = Op.getNode()->use_end(); UI != UE; ++UI)
12536 if (UI->getOpcode() == ISD::STORE)
12539 // Otherwise use a regular EFLAGS-setting instruction.
12540 switch (ArithOp.getOpcode()) {
12541 default: llvm_unreachable("unexpected operator!");
12542 case ISD::SUB: Opcode = X86ISD::SUB; break;
12543 case ISD::XOR: Opcode = X86ISD::XOR; break;
12544 case ISD::AND: Opcode = X86ISD::AND; break;
12546 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12547 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12548 if (EFLAGS.getNode())
12551 Opcode = X86ISD::OR;
12565 return SDValue(Op.getNode(), 1);
12571 // If we found that truncation is beneficial, perform the truncation and
12573 if (NeedTruncation) {
12574 EVT VT = Op.getValueType();
12575 SDValue WideVal = Op->getOperand(0);
12576 EVT WideVT = WideVal.getValueType();
12577 unsigned ConvertedOp = 0;
12578 // Use a target machine opcode to prevent further DAGCombine
12579 // optimizations that may separate the arithmetic operations
12580 // from the setcc node.
12581 switch (WideVal.getOpcode()) {
12583 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12584 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12585 case ISD::AND: ConvertedOp = X86ISD::AND; break;
12586 case ISD::OR: ConvertedOp = X86ISD::OR; break;
12587 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12591 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12592 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12593 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12594 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12595 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12601 // Emit a CMP with 0, which is the TEST pattern.
12602 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12603 DAG.getConstant(0, Op.getValueType()));
12605 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12606 SmallVector<SDValue, 4> Ops;
12607 for (unsigned i = 0; i != NumOperands; ++i)
12608 Ops.push_back(Op.getOperand(i));
12610 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12611 DAG.ReplaceAllUsesWith(Op, New);
12612 return SDValue(New.getNode(), 1);
12615 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12617 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12618 SDLoc dl, SelectionDAG &DAG) const {
12619 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12620 if (C->getAPIntValue() == 0)
12621 return EmitTest(Op0, X86CC, dl, DAG);
12623 if (Op0.getValueType() == MVT::i1)
12624 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12627 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12628 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12629 // Do the comparison at i32 if it's smaller, besides the Atom case.
12630 // This avoids subregister aliasing issues. Keep the smaller reference
12631 // if we're optimizing for size, however, as that'll allow better folding
12632 // of memory operations.
12633 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12634 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12635 AttributeSet::FunctionIndex, Attribute::MinSize) &&
12636 !Subtarget->isAtom()) {
12637 unsigned ExtendOp =
12638 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12639 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12640 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12642 // Use SUB instead of CMP to enable CSE between SUB and CMP.
12643 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12644 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12646 return SDValue(Sub.getNode(), 1);
12648 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12651 /// Convert a comparison if required by the subtarget.
12652 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12653 SelectionDAG &DAG) const {
12654 // If the subtarget does not support the FUCOMI instruction, floating-point
12655 // comparisons have to be converted.
12656 if (Subtarget->hasCMov() ||
12657 Cmp.getOpcode() != X86ISD::CMP ||
12658 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12659 !Cmp.getOperand(1).getValueType().isFloatingPoint())
12662 // The instruction selector will select an FUCOM instruction instead of
12663 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12664 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12665 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12667 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12668 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12669 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12670 DAG.getConstant(8, MVT::i8));
12671 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12672 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12675 static bool isAllOnes(SDValue V) {
12676 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12677 return C && C->isAllOnesValue();
12680 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12681 /// if it's possible.
12682 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12683 SDLoc dl, SelectionDAG &DAG) const {
12684 SDValue Op0 = And.getOperand(0);
12685 SDValue Op1 = And.getOperand(1);
12686 if (Op0.getOpcode() == ISD::TRUNCATE)
12687 Op0 = Op0.getOperand(0);
12688 if (Op1.getOpcode() == ISD::TRUNCATE)
12689 Op1 = Op1.getOperand(0);
12692 if (Op1.getOpcode() == ISD::SHL)
12693 std::swap(Op0, Op1);
12694 if (Op0.getOpcode() == ISD::SHL) {
12695 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12696 if (And00C->getZExtValue() == 1) {
12697 // If we looked past a truncate, check that it's only truncating away
12699 unsigned BitWidth = Op0.getValueSizeInBits();
12700 unsigned AndBitWidth = And.getValueSizeInBits();
12701 if (BitWidth > AndBitWidth) {
12703 DAG.computeKnownBits(Op0, Zeros, Ones);
12704 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12708 RHS = Op0.getOperand(1);
12710 } else if (Op1.getOpcode() == ISD::Constant) {
12711 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12712 uint64_t AndRHSVal = AndRHS->getZExtValue();
12713 SDValue AndLHS = Op0;
12715 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12716 LHS = AndLHS.getOperand(0);
12717 RHS = AndLHS.getOperand(1);
12720 // Use BT if the immediate can't be encoded in a TEST instruction.
12721 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12723 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12727 if (LHS.getNode()) {
12728 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
12729 // instruction. Since the shift amount is in-range-or-undefined, we know
12730 // that doing a bittest on the i32 value is ok. We extend to i32 because
12731 // the encoding for the i16 version is larger than the i32 version.
12732 // Also promote i16 to i32 for performance / code size reason.
12733 if (LHS.getValueType() == MVT::i8 ||
12734 LHS.getValueType() == MVT::i16)
12735 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12737 // If the operand types disagree, extend the shift amount to match. Since
12738 // BT ignores high bits (like shifts) we can use anyextend.
12739 if (LHS.getValueType() != RHS.getValueType())
12740 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12742 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12743 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12744 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12745 DAG.getConstant(Cond, MVT::i8), BT);
12751 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12753 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12758 // SSE Condition code mapping:
12767 switch (SetCCOpcode) {
12768 default: llvm_unreachable("Unexpected SETCC condition");
12770 case ISD::SETEQ: SSECC = 0; break;
12772 case ISD::SETGT: Swap = true; // Fallthrough
12774 case ISD::SETOLT: SSECC = 1; break;
12776 case ISD::SETGE: Swap = true; // Fallthrough
12778 case ISD::SETOLE: SSECC = 2; break;
12779 case ISD::SETUO: SSECC = 3; break;
12781 case ISD::SETNE: SSECC = 4; break;
12782 case ISD::SETULE: Swap = true; // Fallthrough
12783 case ISD::SETUGE: SSECC = 5; break;
12784 case ISD::SETULT: Swap = true; // Fallthrough
12785 case ISD::SETUGT: SSECC = 6; break;
12786 case ISD::SETO: SSECC = 7; break;
12788 case ISD::SETONE: SSECC = 8; break;
12791 std::swap(Op0, Op1);
12796 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12797 // ones, and then concatenate the result back.
12798 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12799 MVT VT = Op.getSimpleValueType();
12801 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12802 "Unsupported value type for operation");
12804 unsigned NumElems = VT.getVectorNumElements();
12806 SDValue CC = Op.getOperand(2);
12808 // Extract the LHS vectors
12809 SDValue LHS = Op.getOperand(0);
12810 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12811 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12813 // Extract the RHS vectors
12814 SDValue RHS = Op.getOperand(1);
12815 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12816 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12818 // Issue the operation on the smaller types and concatenate the result back
12819 MVT EltVT = VT.getVectorElementType();
12820 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12821 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12822 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12823 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12826 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12827 const X86Subtarget *Subtarget) {
12828 SDValue Op0 = Op.getOperand(0);
12829 SDValue Op1 = Op.getOperand(1);
12830 SDValue CC = Op.getOperand(2);
12831 MVT VT = Op.getSimpleValueType();
12834 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12835 Op.getValueType().getScalarType() == MVT::i1 &&
12836 "Cannot set masked compare for this operation");
12838 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12840 bool Unsigned = false;
12843 switch (SetCCOpcode) {
12844 default: llvm_unreachable("Unexpected SETCC condition");
12845 case ISD::SETNE: SSECC = 4; break;
12846 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12847 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12848 case ISD::SETLT: Swap = true; //fall-through
12849 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12850 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12851 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12852 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12853 case ISD::SETULE: Unsigned = true; //fall-through
12854 case ISD::SETLE: SSECC = 2; break;
12858 std::swap(Op0, Op1);
12860 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12861 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12862 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12863 DAG.getConstant(SSECC, MVT::i8));
12866 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12867 /// operand \p Op1. If non-trivial (for example because it's not constant)
12868 /// return an empty value.
12869 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12871 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12875 MVT VT = Op1.getSimpleValueType();
12876 MVT EVT = VT.getVectorElementType();
12877 unsigned n = VT.getVectorNumElements();
12878 SmallVector<SDValue, 8> ULTOp1;
12880 for (unsigned i = 0; i < n; ++i) {
12881 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12882 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12885 // Avoid underflow.
12886 APInt Val = Elt->getAPIntValue();
12890 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12893 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12896 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12897 SelectionDAG &DAG) {
12898 SDValue Op0 = Op.getOperand(0);
12899 SDValue Op1 = Op.getOperand(1);
12900 SDValue CC = Op.getOperand(2);
12901 MVT VT = Op.getSimpleValueType();
12902 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12903 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12908 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12909 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12912 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12913 unsigned Opc = X86ISD::CMPP;
12914 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12915 assert(VT.getVectorNumElements() <= 16);
12916 Opc = X86ISD::CMPM;
12918 // In the two special cases we can't handle, emit two comparisons.
12921 unsigned CombineOpc;
12922 if (SetCCOpcode == ISD::SETUEQ) {
12923 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12925 assert(SetCCOpcode == ISD::SETONE);
12926 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12929 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12930 DAG.getConstant(CC0, MVT::i8));
12931 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12932 DAG.getConstant(CC1, MVT::i8));
12933 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12935 // Handle all other FP comparisons here.
12936 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12937 DAG.getConstant(SSECC, MVT::i8));
12940 // Break 256-bit integer vector compare into smaller ones.
12941 if (VT.is256BitVector() && !Subtarget->hasInt256())
12942 return Lower256IntVSETCC(Op, DAG);
12944 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12945 EVT OpVT = Op1.getValueType();
12946 if (Subtarget->hasAVX512()) {
12947 if (Op1.getValueType().is512BitVector() ||
12948 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12949 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12951 // In AVX-512 architecture setcc returns mask with i1 elements,
12952 // But there is no compare instruction for i8 and i16 elements.
12953 // We are not talking about 512-bit operands in this case, these
12954 // types are illegal.
12956 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12957 OpVT.getVectorElementType().getSizeInBits() >= 8))
12958 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12959 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12962 // We are handling one of the integer comparisons here. Since SSE only has
12963 // GT and EQ comparisons for integer, swapping operands and multiple
12964 // operations may be required for some comparisons.
12966 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12967 bool Subus = false;
12969 switch (SetCCOpcode) {
12970 default: llvm_unreachable("Unexpected SETCC condition");
12971 case ISD::SETNE: Invert = true;
12972 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12973 case ISD::SETLT: Swap = true;
12974 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12975 case ISD::SETGE: Swap = true;
12976 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12977 Invert = true; break;
12978 case ISD::SETULT: Swap = true;
12979 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12980 FlipSigns = true; break;
12981 case ISD::SETUGE: Swap = true;
12982 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12983 FlipSigns = true; Invert = true; break;
12986 // Special case: Use min/max operations for SETULE/SETUGE
12987 MVT VET = VT.getVectorElementType();
12989 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12990 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12993 switch (SetCCOpcode) {
12995 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12996 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12999 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13002 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13003 if (!MinMax && hasSubus) {
13004 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13006 // t = psubus Op0, Op1
13007 // pcmpeq t, <0..0>
13008 switch (SetCCOpcode) {
13010 case ISD::SETULT: {
13011 // If the comparison is against a constant we can turn this into a
13012 // setule. With psubus, setule does not require a swap. This is
13013 // beneficial because the constant in the register is no longer
13014 // destructed as the destination so it can be hoisted out of a loop.
13015 // Only do this pre-AVX since vpcmp* is no longer destructive.
13016 if (Subtarget->hasAVX())
13018 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13019 if (ULEOp1.getNode()) {
13021 Subus = true; Invert = false; Swap = false;
13025 // Psubus is better than flip-sign because it requires no inversion.
13026 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
13027 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13031 Opc = X86ISD::SUBUS;
13037 std::swap(Op0, Op1);
13039 // Check that the operation in question is available (most are plain SSE2,
13040 // but PCMPGTQ and PCMPEQQ have different requirements).
13041 if (VT == MVT::v2i64) {
13042 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13043 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13045 // First cast everything to the right type.
13046 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13047 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13049 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13050 // bits of the inputs before performing those operations. The lower
13051 // compare is always unsigned.
13054 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13056 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13057 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13058 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13059 Sign, Zero, Sign, Zero);
13061 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13062 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13064 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13065 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13066 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13068 // Create masks for only the low parts/high parts of the 64 bit integers.
13069 static const int MaskHi[] = { 1, 1, 3, 3 };
13070 static const int MaskLo[] = { 0, 0, 2, 2 };
13071 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13072 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13073 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13075 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13076 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13079 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13081 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13084 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13085 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13086 // pcmpeqd + pshufd + pand.
13087 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13089 // First cast everything to the right type.
13090 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13091 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13094 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13096 // Make sure the lower and upper halves are both all-ones.
13097 static const int Mask[] = { 1, 0, 3, 2 };
13098 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13099 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13102 Result = DAG.getNOT(dl, Result, MVT::v4i32);
13104 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13108 // Since SSE has no unsigned integer comparisons, we need to flip the sign
13109 // bits of the inputs before performing those operations.
13111 EVT EltVT = VT.getVectorElementType();
13112 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13113 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13114 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13117 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13119 // If the logical-not of the result is required, perform that now.
13121 Result = DAG.getNOT(dl, Result, VT);
13124 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13127 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13128 getZeroVector(VT, Subtarget, DAG, dl));
13133 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13135 MVT VT = Op.getSimpleValueType();
13137 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13139 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13140 && "SetCC type must be 8-bit or 1-bit integer");
13141 SDValue Op0 = Op.getOperand(0);
13142 SDValue Op1 = Op.getOperand(1);
13144 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13146 // Optimize to BT if possible.
13147 // Lower (X & (1 << N)) == 0 to BT(X, N).
13148 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13149 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13150 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13151 Op1.getOpcode() == ISD::Constant &&
13152 cast<ConstantSDNode>(Op1)->isNullValue() &&
13153 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13154 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13155 if (NewSetCC.getNode())
13159 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
13161 if (Op1.getOpcode() == ISD::Constant &&
13162 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13163 cast<ConstantSDNode>(Op1)->isNullValue()) &&
13164 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13166 // If the input is a setcc, then reuse the input setcc or use a new one with
13167 // the inverted condition.
13168 if (Op0.getOpcode() == X86ISD::SETCC) {
13169 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13170 bool Invert = (CC == ISD::SETNE) ^
13171 cast<ConstantSDNode>(Op1)->isNullValue();
13175 CCode = X86::GetOppositeBranchCondition(CCode);
13176 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13177 DAG.getConstant(CCode, MVT::i8),
13178 Op0.getOperand(1));
13180 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13184 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13185 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13186 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13188 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13189 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13192 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13193 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13194 if (X86CC == X86::COND_INVALID)
13197 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13198 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13199 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13200 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13202 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13206 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13207 static bool isX86LogicalCmp(SDValue Op) {
13208 unsigned Opc = Op.getNode()->getOpcode();
13209 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13210 Opc == X86ISD::SAHF)
13212 if (Op.getResNo() == 1 &&
13213 (Opc == X86ISD::ADD ||
13214 Opc == X86ISD::SUB ||
13215 Opc == X86ISD::ADC ||
13216 Opc == X86ISD::SBB ||
13217 Opc == X86ISD::SMUL ||
13218 Opc == X86ISD::UMUL ||
13219 Opc == X86ISD::INC ||
13220 Opc == X86ISD::DEC ||
13221 Opc == X86ISD::OR ||
13222 Opc == X86ISD::XOR ||
13223 Opc == X86ISD::AND))
13226 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13232 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13233 if (V.getOpcode() != ISD::TRUNCATE)
13236 SDValue VOp0 = V.getOperand(0);
13237 unsigned InBits = VOp0.getValueSizeInBits();
13238 unsigned Bits = V.getValueSizeInBits();
13239 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13242 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13243 bool addTest = true;
13244 SDValue Cond = Op.getOperand(0);
13245 SDValue Op1 = Op.getOperand(1);
13246 SDValue Op2 = Op.getOperand(2);
13248 EVT VT = Op1.getValueType();
13251 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13252 // are available. Otherwise fp cmovs get lowered into a less efficient branch
13253 // sequence later on.
13254 if (Cond.getOpcode() == ISD::SETCC &&
13255 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13256 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13257 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13258 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13259 int SSECC = translateX86FSETCC(
13260 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13263 if (Subtarget->hasAVX512()) {
13264 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13265 DAG.getConstant(SSECC, MVT::i8));
13266 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13268 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13269 DAG.getConstant(SSECC, MVT::i8));
13270 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13271 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13272 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13276 if (Cond.getOpcode() == ISD::SETCC) {
13277 SDValue NewCond = LowerSETCC(Cond, DAG);
13278 if (NewCond.getNode())
13282 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13283 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13284 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13285 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13286 if (Cond.getOpcode() == X86ISD::SETCC &&
13287 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13288 isZero(Cond.getOperand(1).getOperand(1))) {
13289 SDValue Cmp = Cond.getOperand(1);
13291 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13293 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13294 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13295 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13297 SDValue CmpOp0 = Cmp.getOperand(0);
13298 // Apply further optimizations for special cases
13299 // (select (x != 0), -1, 0) -> neg & sbb
13300 // (select (x == 0), 0, -1) -> neg & sbb
13301 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13302 if (YC->isNullValue() &&
13303 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13304 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13305 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13306 DAG.getConstant(0, CmpOp0.getValueType()),
13308 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13309 DAG.getConstant(X86::COND_B, MVT::i8),
13310 SDValue(Neg.getNode(), 1));
13314 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13315 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13316 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13318 SDValue Res = // Res = 0 or -1.
13319 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13320 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13322 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13323 Res = DAG.getNOT(DL, Res, Res.getValueType());
13325 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13326 if (!N2C || !N2C->isNullValue())
13327 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13332 // Look past (and (setcc_carry (cmp ...)), 1).
13333 if (Cond.getOpcode() == ISD::AND &&
13334 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13335 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13336 if (C && C->getAPIntValue() == 1)
13337 Cond = Cond.getOperand(0);
13340 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13341 // setting operand in place of the X86ISD::SETCC.
13342 unsigned CondOpcode = Cond.getOpcode();
13343 if (CondOpcode == X86ISD::SETCC ||
13344 CondOpcode == X86ISD::SETCC_CARRY) {
13345 CC = Cond.getOperand(0);
13347 SDValue Cmp = Cond.getOperand(1);
13348 unsigned Opc = Cmp.getOpcode();
13349 MVT VT = Op.getSimpleValueType();
13351 bool IllegalFPCMov = false;
13352 if (VT.isFloatingPoint() && !VT.isVector() &&
13353 !isScalarFPTypeInSSEReg(VT)) // FPStack?
13354 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13356 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13357 Opc == X86ISD::BT) { // FIXME
13361 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13362 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13363 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13364 Cond.getOperand(0).getValueType() != MVT::i8)) {
13365 SDValue LHS = Cond.getOperand(0);
13366 SDValue RHS = Cond.getOperand(1);
13367 unsigned X86Opcode;
13370 switch (CondOpcode) {
13371 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13372 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13373 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13374 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13375 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13376 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13377 default: llvm_unreachable("unexpected overflowing operator");
13379 if (CondOpcode == ISD::UMULO)
13380 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13383 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13385 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13387 if (CondOpcode == ISD::UMULO)
13388 Cond = X86Op.getValue(2);
13390 Cond = X86Op.getValue(1);
13392 CC = DAG.getConstant(X86Cond, MVT::i8);
13397 // Look pass the truncate if the high bits are known zero.
13398 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13399 Cond = Cond.getOperand(0);
13401 // We know the result of AND is compared against zero. Try to match
13403 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13404 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13405 if (NewSetCC.getNode()) {
13406 CC = NewSetCC.getOperand(0);
13407 Cond = NewSetCC.getOperand(1);
13414 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13415 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13418 // a < b ? -1 : 0 -> RES = ~setcc_carry
13419 // a < b ? 0 : -1 -> RES = setcc_carry
13420 // a >= b ? -1 : 0 -> RES = setcc_carry
13421 // a >= b ? 0 : -1 -> RES = ~setcc_carry
13422 if (Cond.getOpcode() == X86ISD::SUB) {
13423 Cond = ConvertCmpIfNecessary(Cond, DAG);
13424 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13426 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13427 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13428 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13429 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13430 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13431 return DAG.getNOT(DL, Res, Res.getValueType());
13436 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13437 // widen the cmov and push the truncate through. This avoids introducing a new
13438 // branch during isel and doesn't add any extensions.
13439 if (Op.getValueType() == MVT::i8 &&
13440 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13441 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13442 if (T1.getValueType() == T2.getValueType() &&
13443 // Blacklist CopyFromReg to avoid partial register stalls.
13444 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13445 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13446 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13447 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13451 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13452 // condition is true.
13453 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13454 SDValue Ops[] = { Op2, Op1, CC, Cond };
13455 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13458 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13459 MVT VT = Op->getSimpleValueType(0);
13460 SDValue In = Op->getOperand(0);
13461 MVT InVT = In.getSimpleValueType();
13464 unsigned int NumElts = VT.getVectorNumElements();
13465 if (NumElts != 8 && NumElts != 16)
13468 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13469 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13471 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13472 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13474 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13475 Constant *C = ConstantInt::get(*DAG.getContext(),
13476 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13478 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13479 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13480 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13481 MachinePointerInfo::getConstantPool(),
13482 false, false, false, Alignment);
13483 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13484 if (VT.is512BitVector())
13486 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13489 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13490 SelectionDAG &DAG) {
13491 MVT VT = Op->getSimpleValueType(0);
13492 SDValue In = Op->getOperand(0);
13493 MVT InVT = In.getSimpleValueType();
13496 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13497 return LowerSIGN_EXTEND_AVX512(Op, DAG);
13499 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13500 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13501 (VT != MVT::v16i16 || InVT != MVT::v16i8))
13504 if (Subtarget->hasInt256())
13505 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13507 // Optimize vectors in AVX mode
13508 // Sign extend v8i16 to v8i32 and
13511 // Divide input vector into two parts
13512 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13513 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13514 // concat the vectors to original VT
13516 unsigned NumElems = InVT.getVectorNumElements();
13517 SDValue Undef = DAG.getUNDEF(InVT);
13519 SmallVector<int,8> ShufMask1(NumElems, -1);
13520 for (unsigned i = 0; i != NumElems/2; ++i)
13523 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13525 SmallVector<int,8> ShufMask2(NumElems, -1);
13526 for (unsigned i = 0; i != NumElems/2; ++i)
13527 ShufMask2[i] = i + NumElems/2;
13529 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13531 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13532 VT.getVectorNumElements()/2);
13534 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13535 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13537 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13540 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13541 // may emit an illegal shuffle but the expansion is still better than scalar
13542 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13543 // we'll emit a shuffle and a arithmetic shift.
13544 // TODO: It is possible to support ZExt by zeroing the undef values during
13545 // the shuffle phase or after the shuffle.
13546 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13547 SelectionDAG &DAG) {
13548 MVT RegVT = Op.getSimpleValueType();
13549 assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13550 assert(RegVT.isInteger() &&
13551 "We only custom lower integer vector sext loads.");
13553 // Nothing useful we can do without SSE2 shuffles.
13554 assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13556 LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13558 EVT MemVT = Ld->getMemoryVT();
13559 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13560 unsigned RegSz = RegVT.getSizeInBits();
13562 ISD::LoadExtType Ext = Ld->getExtensionType();
13564 assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13565 && "Only anyext and sext are currently implemented.");
13566 assert(MemVT != RegVT && "Cannot extend to the same type");
13567 assert(MemVT.isVector() && "Must load a vector from memory");
13569 unsigned NumElems = RegVT.getVectorNumElements();
13570 unsigned MemSz = MemVT.getSizeInBits();
13571 assert(RegSz > MemSz && "Register size must be greater than the mem size");
13573 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13574 // The only way in which we have a legal 256-bit vector result but not the
13575 // integer 256-bit operations needed to directly lower a sextload is if we
13576 // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13577 // a 128-bit vector and a normal sign_extend to 256-bits that should get
13578 // correctly legalized. We do this late to allow the canonical form of
13579 // sextload to persist throughout the rest of the DAG combiner -- it wants
13580 // to fold together any extensions it can, and so will fuse a sign_extend
13581 // of an sextload into a sextload targeting a wider value.
13583 if (MemSz == 128) {
13584 // Just switch this to a normal load.
13585 assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13586 "it must be a legal 128-bit vector "
13588 Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13589 Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13590 Ld->isInvariant(), Ld->getAlignment());
13592 assert(MemSz < 128 &&
13593 "Can't extend a type wider than 128 bits to a 256 bit vector!");
13594 // Do an sext load to a 128-bit vector type. We want to use the same
13595 // number of elements, but elements half as wide. This will end up being
13596 // recursively lowered by this routine, but will succeed as we definitely
13597 // have all the necessary features if we're using AVX1.
13599 EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13600 EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13602 DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13603 Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13604 Ld->isNonTemporal(), Ld->isInvariant(),
13605 Ld->getAlignment());
13608 // Replace chain users with the new chain.
13609 assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13610 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13612 // Finally, do a normal sign-extend to the desired register.
13613 return DAG.getSExtOrTrunc(Load, dl, RegVT);
13616 // All sizes must be a power of two.
13617 assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13618 "Non-power-of-two elements are not custom lowered!");
13620 // Attempt to load the original value using scalar loads.
13621 // Find the largest scalar type that divides the total loaded size.
13622 MVT SclrLoadTy = MVT::i8;
13623 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13624 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13625 MVT Tp = (MVT::SimpleValueType)tp;
13626 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13631 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13632 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13634 SclrLoadTy = MVT::f64;
13636 // Calculate the number of scalar loads that we need to perform
13637 // in order to load our vector from memory.
13638 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13640 assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13641 "Can only lower sext loads with a single scalar load!");
13643 unsigned loadRegZize = RegSz;
13644 if (Ext == ISD::SEXTLOAD && RegSz == 256)
13647 // Represent our vector as a sequence of elements which are the
13648 // largest scalar that we can load.
13649 EVT LoadUnitVecVT = EVT::getVectorVT(
13650 *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13652 // Represent the data using the same element type that is stored in
13653 // memory. In practice, we ''widen'' MemVT.
13655 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13656 loadRegZize / MemVT.getScalarType().getSizeInBits());
13658 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13659 "Invalid vector type");
13661 // We can't shuffle using an illegal type.
13662 assert(TLI.isTypeLegal(WideVecVT) &&
13663 "We only lower types that form legal widened vector types");
13665 SmallVector<SDValue, 8> Chains;
13666 SDValue Ptr = Ld->getBasePtr();
13667 SDValue Increment =
13668 DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13669 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13671 for (unsigned i = 0; i < NumLoads; ++i) {
13672 // Perform a single load.
13673 SDValue ScalarLoad =
13674 DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13675 Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13676 Ld->getAlignment());
13677 Chains.push_back(ScalarLoad.getValue(1));
13678 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13679 // another round of DAGCombining.
13681 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13683 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13684 ScalarLoad, DAG.getIntPtrConstant(i));
13686 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13689 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13691 // Bitcast the loaded value to a vector of the original element type, in
13692 // the size of the target vector type.
13693 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13694 unsigned SizeRatio = RegSz / MemSz;
13696 if (Ext == ISD::SEXTLOAD) {
13697 // If we have SSE4.1, we can directly emit a VSEXT node.
13698 if (Subtarget->hasSSE41()) {
13699 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13700 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13704 // Otherwise we'll shuffle the small elements in the high bits of the
13705 // larger type and perform an arithmetic shift. If the shift is not legal
13706 // it's better to scalarize.
13707 assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13708 "We can't implement a sext load without an arithmetic right shift!");
13710 // Redistribute the loaded elements into the different locations.
13711 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13712 for (unsigned i = 0; i != NumElems; ++i)
13713 ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13715 SDValue Shuff = DAG.getVectorShuffle(
13716 WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13718 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13720 // Build the arithmetic shift.
13721 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13722 MemVT.getVectorElementType().getSizeInBits();
13724 DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13726 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13730 // Redistribute the loaded elements into the different locations.
13731 SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
13732 for (unsigned i = 0; i != NumElems; ++i)
13733 ShuffleVec[i * SizeRatio] = i;
13735 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13736 DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13738 // Bitcast to the requested type.
13739 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13740 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13744 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13745 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13746 // from the AND / OR.
13747 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13748 Opc = Op.getOpcode();
13749 if (Opc != ISD::OR && Opc != ISD::AND)
13751 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13752 Op.getOperand(0).hasOneUse() &&
13753 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13754 Op.getOperand(1).hasOneUse());
13757 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13758 // 1 and that the SETCC node has a single use.
13759 static bool isXor1OfSetCC(SDValue Op) {
13760 if (Op.getOpcode() != ISD::XOR)
13762 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13763 if (N1C && N1C->getAPIntValue() == 1) {
13764 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13765 Op.getOperand(0).hasOneUse();
13770 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13771 bool addTest = true;
13772 SDValue Chain = Op.getOperand(0);
13773 SDValue Cond = Op.getOperand(1);
13774 SDValue Dest = Op.getOperand(2);
13777 bool Inverted = false;
13779 if (Cond.getOpcode() == ISD::SETCC) {
13780 // Check for setcc([su]{add,sub,mul}o == 0).
13781 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13782 isa<ConstantSDNode>(Cond.getOperand(1)) &&
13783 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13784 Cond.getOperand(0).getResNo() == 1 &&
13785 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13786 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13787 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13788 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13789 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13790 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13792 Cond = Cond.getOperand(0);
13794 SDValue NewCond = LowerSETCC(Cond, DAG);
13795 if (NewCond.getNode())
13800 // FIXME: LowerXALUO doesn't handle these!!
13801 else if (Cond.getOpcode() == X86ISD::ADD ||
13802 Cond.getOpcode() == X86ISD::SUB ||
13803 Cond.getOpcode() == X86ISD::SMUL ||
13804 Cond.getOpcode() == X86ISD::UMUL)
13805 Cond = LowerXALUO(Cond, DAG);
13808 // Look pass (and (setcc_carry (cmp ...)), 1).
13809 if (Cond.getOpcode() == ISD::AND &&
13810 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13811 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13812 if (C && C->getAPIntValue() == 1)
13813 Cond = Cond.getOperand(0);
13816 // If condition flag is set by a X86ISD::CMP, then use it as the condition
13817 // setting operand in place of the X86ISD::SETCC.
13818 unsigned CondOpcode = Cond.getOpcode();
13819 if (CondOpcode == X86ISD::SETCC ||
13820 CondOpcode == X86ISD::SETCC_CARRY) {
13821 CC = Cond.getOperand(0);
13823 SDValue Cmp = Cond.getOperand(1);
13824 unsigned Opc = Cmp.getOpcode();
13825 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13826 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13830 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13834 // These can only come from an arithmetic instruction with overflow,
13835 // e.g. SADDO, UADDO.
13836 Cond = Cond.getNode()->getOperand(1);
13842 CondOpcode = Cond.getOpcode();
13843 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13844 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13845 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13846 Cond.getOperand(0).getValueType() != MVT::i8)) {
13847 SDValue LHS = Cond.getOperand(0);
13848 SDValue RHS = Cond.getOperand(1);
13849 unsigned X86Opcode;
13852 // Keep this in sync with LowerXALUO, otherwise we might create redundant
13853 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13855 switch (CondOpcode) {
13856 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13858 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13860 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13863 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13864 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13866 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13868 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13871 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13872 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13873 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13874 default: llvm_unreachable("unexpected overflowing operator");
13877 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13878 if (CondOpcode == ISD::UMULO)
13879 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13882 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13884 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13886 if (CondOpcode == ISD::UMULO)
13887 Cond = X86Op.getValue(2);
13889 Cond = X86Op.getValue(1);
13891 CC = DAG.getConstant(X86Cond, MVT::i8);
13895 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13896 SDValue Cmp = Cond.getOperand(0).getOperand(1);
13897 if (CondOpc == ISD::OR) {
13898 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13899 // two branches instead of an explicit OR instruction with a
13901 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13902 isX86LogicalCmp(Cmp)) {
13903 CC = Cond.getOperand(0).getOperand(0);
13904 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13905 Chain, Dest, CC, Cmp);
13906 CC = Cond.getOperand(1).getOperand(0);
13910 } else { // ISD::AND
13911 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13912 // two branches instead of an explicit AND instruction with a
13913 // separate test. However, we only do this if this block doesn't
13914 // have a fall-through edge, because this requires an explicit
13915 // jmp when the condition is false.
13916 if (Cmp == Cond.getOperand(1).getOperand(1) &&
13917 isX86LogicalCmp(Cmp) &&
13918 Op.getNode()->hasOneUse()) {
13919 X86::CondCode CCode =
13920 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13921 CCode = X86::GetOppositeBranchCondition(CCode);
13922 CC = DAG.getConstant(CCode, MVT::i8);
13923 SDNode *User = *Op.getNode()->use_begin();
13924 // Look for an unconditional branch following this conditional branch.
13925 // We need this because we need to reverse the successors in order
13926 // to implement FCMP_OEQ.
13927 if (User->getOpcode() == ISD::BR) {
13928 SDValue FalseBB = User->getOperand(1);
13930 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13931 assert(NewBR == User);
13935 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13936 Chain, Dest, CC, Cmp);
13937 X86::CondCode CCode =
13938 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13939 CCode = X86::GetOppositeBranchCondition(CCode);
13940 CC = DAG.getConstant(CCode, MVT::i8);
13946 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13947 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13948 // It should be transformed during dag combiner except when the condition
13949 // is set by a arithmetics with overflow node.
13950 X86::CondCode CCode =
13951 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13952 CCode = X86::GetOppositeBranchCondition(CCode);
13953 CC = DAG.getConstant(CCode, MVT::i8);
13954 Cond = Cond.getOperand(0).getOperand(1);
13956 } else if (Cond.getOpcode() == ISD::SETCC &&
13957 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13958 // For FCMP_OEQ, we can emit
13959 // two branches instead of an explicit AND instruction with a
13960 // separate test. However, we only do this if this block doesn't
13961 // have a fall-through edge, because this requires an explicit
13962 // jmp when the condition is false.
13963 if (Op.getNode()->hasOneUse()) {
13964 SDNode *User = *Op.getNode()->use_begin();
13965 // Look for an unconditional branch following this conditional branch.
13966 // We need this because we need to reverse the successors in order
13967 // to implement FCMP_OEQ.
13968 if (User->getOpcode() == ISD::BR) {
13969 SDValue FalseBB = User->getOperand(1);
13971 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13972 assert(NewBR == User);
13976 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13977 Cond.getOperand(0), Cond.getOperand(1));
13978 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13979 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13980 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13981 Chain, Dest, CC, Cmp);
13982 CC = DAG.getConstant(X86::COND_P, MVT::i8);
13987 } else if (Cond.getOpcode() == ISD::SETCC &&
13988 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13989 // For FCMP_UNE, we can emit
13990 // two branches instead of an explicit AND instruction with a
13991 // separate test. However, we only do this if this block doesn't
13992 // have a fall-through edge, because this requires an explicit
13993 // jmp when the condition is false.
13994 if (Op.getNode()->hasOneUse()) {
13995 SDNode *User = *Op.getNode()->use_begin();
13996 // Look for an unconditional branch following this conditional branch.
13997 // We need this because we need to reverse the successors in order
13998 // to implement FCMP_UNE.
13999 if (User->getOpcode() == ISD::BR) {
14000 SDValue FalseBB = User->getOperand(1);
14002 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14003 assert(NewBR == User);
14006 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14007 Cond.getOperand(0), Cond.getOperand(1));
14008 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14009 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14010 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14011 Chain, Dest, CC, Cmp);
14012 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14022 // Look pass the truncate if the high bits are known zero.
14023 if (isTruncWithZeroHighBitsInput(Cond, DAG))
14024 Cond = Cond.getOperand(0);
14026 // We know the result of AND is compared against zero. Try to match
14028 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14029 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14030 if (NewSetCC.getNode()) {
14031 CC = NewSetCC.getOperand(0);
14032 Cond = NewSetCC.getOperand(1);
14039 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14040 CC = DAG.getConstant(X86Cond, MVT::i8);
14041 Cond = EmitTest(Cond, X86Cond, dl, DAG);
14043 Cond = ConvertCmpIfNecessary(Cond, DAG);
14044 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14045 Chain, Dest, CC, Cond);
14048 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14049 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14050 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14051 // that the guard pages used by the OS virtual memory manager are allocated in
14052 // correct sequence.
14054 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14055 SelectionDAG &DAG) const {
14056 MachineFunction &MF = DAG.getMachineFunction();
14057 bool SplitStack = MF.shouldSplitStack();
14058 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
14063 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14064 SDNode* Node = Op.getNode();
14066 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14067 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14068 " not tell us which reg is the stack pointer!");
14069 EVT VT = Node->getValueType(0);
14070 SDValue Tmp1 = SDValue(Node, 0);
14071 SDValue Tmp2 = SDValue(Node, 1);
14072 SDValue Tmp3 = Node->getOperand(2);
14073 SDValue Chain = Tmp1.getOperand(0);
14075 // Chain the dynamic stack allocation so that it doesn't modify the stack
14076 // pointer when other instructions are using the stack.
14077 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14080 SDValue Size = Tmp2.getOperand(1);
14081 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14082 Chain = SP.getValue(1);
14083 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14084 const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
14085 unsigned StackAlign = TFI.getStackAlignment();
14086 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14087 if (Align > StackAlign)
14088 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14089 DAG.getConstant(-(uint64_t)Align, VT));
14090 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14092 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14093 DAG.getIntPtrConstant(0, true), SDValue(),
14096 SDValue Ops[2] = { Tmp1, Tmp2 };
14097 return DAG.getMergeValues(Ops, dl);
14101 SDValue Chain = Op.getOperand(0);
14102 SDValue Size = Op.getOperand(1);
14103 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14104 EVT VT = Op.getNode()->getValueType(0);
14106 bool Is64Bit = Subtarget->is64Bit();
14107 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
14110 MachineRegisterInfo &MRI = MF.getRegInfo();
14113 // The 64 bit implementation of segmented stacks needs to clobber both r10
14114 // r11. This makes it impossible to use it along with nested parameters.
14115 const Function *F = MF.getFunction();
14117 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14119 if (I->hasNestAttr())
14120 report_fatal_error("Cannot use segmented stacks with functions that "
14121 "have nested arguments.");
14124 const TargetRegisterClass *AddrRegClass =
14125 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
14126 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14127 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14128 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14129 DAG.getRegister(Vreg, SPTy));
14130 SDValue Ops1[2] = { Value, Chain };
14131 return DAG.getMergeValues(Ops1, dl);
14134 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
14136 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14137 Flag = Chain.getValue(1);
14138 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14140 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14142 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
14143 DAG.getSubtarget().getRegisterInfo());
14144 unsigned SPReg = RegInfo->getStackRegister();
14145 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14146 Chain = SP.getValue(1);
14149 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14150 DAG.getConstant(-(uint64_t)Align, VT));
14151 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14154 SDValue Ops1[2] = { SP, Chain };
14155 return DAG.getMergeValues(Ops1, dl);
14159 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14160 MachineFunction &MF = DAG.getMachineFunction();
14161 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14163 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14166 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14167 // vastart just stores the address of the VarArgsFrameIndex slot into the
14168 // memory location argument.
14169 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14171 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14172 MachinePointerInfo(SV), false, false, 0);
14176 // gp_offset (0 - 6 * 8)
14177 // fp_offset (48 - 48 + 8 * 16)
14178 // overflow_arg_area (point to parameters coming in memory).
14180 SmallVector<SDValue, 8> MemOps;
14181 SDValue FIN = Op.getOperand(1);
14183 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14184 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14186 FIN, MachinePointerInfo(SV), false, false, 0);
14187 MemOps.push_back(Store);
14190 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14191 FIN, DAG.getIntPtrConstant(4));
14192 Store = DAG.getStore(Op.getOperand(0), DL,
14193 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14195 FIN, MachinePointerInfo(SV, 4), false, false, 0);
14196 MemOps.push_back(Store);
14198 // Store ptr to overflow_arg_area
14199 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14200 FIN, DAG.getIntPtrConstant(4));
14201 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14203 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14204 MachinePointerInfo(SV, 8),
14206 MemOps.push_back(Store);
14208 // Store ptr to reg_save_area.
14209 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14210 FIN, DAG.getIntPtrConstant(8));
14211 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14213 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14214 MachinePointerInfo(SV, 16), false, false, 0);
14215 MemOps.push_back(Store);
14216 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14219 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14220 assert(Subtarget->is64Bit() &&
14221 "LowerVAARG only handles 64-bit va_arg!");
14222 assert((Subtarget->isTargetLinux() ||
14223 Subtarget->isTargetDarwin()) &&
14224 "Unhandled target in LowerVAARG");
14225 assert(Op.getNode()->getNumOperands() == 4);
14226 SDValue Chain = Op.getOperand(0);
14227 SDValue SrcPtr = Op.getOperand(1);
14228 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14229 unsigned Align = Op.getConstantOperandVal(3);
14232 EVT ArgVT = Op.getNode()->getValueType(0);
14233 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14234 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14237 // Decide which area this value should be read from.
14238 // TODO: Implement the AMD64 ABI in its entirety. This simple
14239 // selection mechanism works only for the basic types.
14240 if (ArgVT == MVT::f80) {
14241 llvm_unreachable("va_arg for f80 not yet implemented");
14242 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14243 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
14244 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14245 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
14247 llvm_unreachable("Unhandled argument type in LowerVAARG");
14250 if (ArgMode == 2) {
14251 // Sanity Check: Make sure using fp_offset makes sense.
14252 assert(!DAG.getTarget().Options.UseSoftFloat &&
14253 !(DAG.getMachineFunction()
14254 .getFunction()->getAttributes()
14255 .hasAttribute(AttributeSet::FunctionIndex,
14256 Attribute::NoImplicitFloat)) &&
14257 Subtarget->hasSSE1());
14260 // Insert VAARG_64 node into the DAG
14261 // VAARG_64 returns two values: Variable Argument Address, Chain
14262 SmallVector<SDValue, 11> InstOps;
14263 InstOps.push_back(Chain);
14264 InstOps.push_back(SrcPtr);
14265 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
14266 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
14267 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
14268 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14269 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14270 VTs, InstOps, MVT::i64,
14271 MachinePointerInfo(SV),
14273 /*Volatile=*/false,
14275 /*WriteMem=*/true);
14276 Chain = VAARG.getValue(1);
14278 // Load the next argument and return it
14279 return DAG.getLoad(ArgVT, dl,
14282 MachinePointerInfo(),
14283 false, false, false, 0);
14286 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14287 SelectionDAG &DAG) {
14288 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14289 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14290 SDValue Chain = Op.getOperand(0);
14291 SDValue DstPtr = Op.getOperand(1);
14292 SDValue SrcPtr = Op.getOperand(2);
14293 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14294 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14297 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14298 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14300 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14303 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14304 // amount is a constant. Takes immediate version of shift as input.
14305 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14306 SDValue SrcOp, uint64_t ShiftAmt,
14307 SelectionDAG &DAG) {
14308 MVT ElementType = VT.getVectorElementType();
14310 // Fold this packed shift into its first operand if ShiftAmt is 0.
14314 // Check for ShiftAmt >= element width
14315 if (ShiftAmt >= ElementType.getSizeInBits()) {
14316 if (Opc == X86ISD::VSRAI)
14317 ShiftAmt = ElementType.getSizeInBits() - 1;
14319 return DAG.getConstant(0, VT);
14322 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14323 && "Unknown target vector shift-by-constant node");
14325 // Fold this packed vector shift into a build vector if SrcOp is a
14326 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14327 if (VT == SrcOp.getSimpleValueType() &&
14328 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14329 SmallVector<SDValue, 8> Elts;
14330 unsigned NumElts = SrcOp->getNumOperands();
14331 ConstantSDNode *ND;
14334 default: llvm_unreachable(nullptr);
14335 case X86ISD::VSHLI:
14336 for (unsigned i=0; i!=NumElts; ++i) {
14337 SDValue CurrentOp = SrcOp->getOperand(i);
14338 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14339 Elts.push_back(CurrentOp);
14342 ND = cast<ConstantSDNode>(CurrentOp);
14343 const APInt &C = ND->getAPIntValue();
14344 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14347 case X86ISD::VSRLI:
14348 for (unsigned i=0; i!=NumElts; ++i) {
14349 SDValue CurrentOp = SrcOp->getOperand(i);
14350 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14351 Elts.push_back(CurrentOp);
14354 ND = cast<ConstantSDNode>(CurrentOp);
14355 const APInt &C = ND->getAPIntValue();
14356 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14359 case X86ISD::VSRAI:
14360 for (unsigned i=0; i!=NumElts; ++i) {
14361 SDValue CurrentOp = SrcOp->getOperand(i);
14362 if (CurrentOp->getOpcode() == ISD::UNDEF) {
14363 Elts.push_back(CurrentOp);
14366 ND = cast<ConstantSDNode>(CurrentOp);
14367 const APInt &C = ND->getAPIntValue();
14368 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14373 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14376 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14379 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14380 // may or may not be a constant. Takes immediate version of shift as input.
14381 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14382 SDValue SrcOp, SDValue ShAmt,
14383 SelectionDAG &DAG) {
14384 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14386 // Catch shift-by-constant.
14387 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14388 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14389 CShAmt->getZExtValue(), DAG);
14391 // Change opcode to non-immediate version
14393 default: llvm_unreachable("Unknown target vector shift node");
14394 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14395 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14396 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14399 // Need to build a vector containing shift amount
14400 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14403 ShOps[1] = DAG.getConstant(0, MVT::i32);
14404 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14405 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14407 // The return type has to be a 128-bit type with the same element
14408 // type as the input type.
14409 MVT EltVT = VT.getVectorElementType();
14410 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14412 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14413 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14416 /// \brief Return (vselect \p Mask, \p Op, \p PreservedSrc) along with the
14417 /// necessary casting for \p Mask when lowering masking intrinsics.
14418 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14419 SDValue PreservedSrc, SelectionDAG &DAG) {
14420 EVT VT = Op.getValueType();
14421 EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14422 MVT::i1, VT.getVectorNumElements());
14425 assert(MaskVT.isSimple() && "invalid mask type");
14426 return DAG.getNode(ISD::VSELECT, dl, VT,
14427 DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask),
14431 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
14433 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14434 case Intrinsic::x86_fma_vfmadd_ps:
14435 case Intrinsic::x86_fma_vfmadd_pd:
14436 case Intrinsic::x86_fma_vfmadd_ps_256:
14437 case Intrinsic::x86_fma_vfmadd_pd_256:
14438 case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14439 case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14440 return X86ISD::FMADD;
14441 case Intrinsic::x86_fma_vfmsub_ps:
14442 case Intrinsic::x86_fma_vfmsub_pd:
14443 case Intrinsic::x86_fma_vfmsub_ps_256:
14444 case Intrinsic::x86_fma_vfmsub_pd_256:
14445 case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14446 case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14447 return X86ISD::FMSUB;
14448 case Intrinsic::x86_fma_vfnmadd_ps:
14449 case Intrinsic::x86_fma_vfnmadd_pd:
14450 case Intrinsic::x86_fma_vfnmadd_ps_256:
14451 case Intrinsic::x86_fma_vfnmadd_pd_256:
14452 case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14453 case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14454 return X86ISD::FNMADD;
14455 case Intrinsic::x86_fma_vfnmsub_ps:
14456 case Intrinsic::x86_fma_vfnmsub_pd:
14457 case Intrinsic::x86_fma_vfnmsub_ps_256:
14458 case Intrinsic::x86_fma_vfnmsub_pd_256:
14459 case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14460 case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14461 return X86ISD::FNMSUB;
14462 case Intrinsic::x86_fma_vfmaddsub_ps:
14463 case Intrinsic::x86_fma_vfmaddsub_pd:
14464 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14465 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14466 case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14467 case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14468 return X86ISD::FMADDSUB;
14469 case Intrinsic::x86_fma_vfmsubadd_ps:
14470 case Intrinsic::x86_fma_vfmsubadd_pd:
14471 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14472 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14473 case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14474 case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
14475 return X86ISD::FMSUBADD;
14479 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14481 InitIntrinsicsWithoutChain();
14483 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14485 const IntrinsicData* IntrData = GetIntrinsicWithoutChain(IntNo);
14487 switch(IntrData->Type) {
14488 case INTR_TYPE_1OP:
14489 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14490 case INTR_TYPE_2OP:
14491 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14493 case INTR_TYPE_3OP:
14494 return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14495 Op.getOperand(2), Op.getOperand(3));
14496 case COMI: { // Comparison intrinsics
14497 ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14498 SDValue LHS = Op.getOperand(1);
14499 SDValue RHS = Op.getOperand(2);
14500 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14501 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14502 SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14503 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14504 DAG.getConstant(X86CC, MVT::i8), Cond);
14505 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14508 return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14509 Op.getOperand(1), Op.getOperand(2), DAG);
14516 default: return SDValue(); // Don't custom lower most intrinsics.
14518 // Arithmetic intrinsics.
14519 case Intrinsic::x86_sse2_pmulu_dq:
14520 case Intrinsic::x86_avx2_pmulu_dq:
14521 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14522 Op.getOperand(1), Op.getOperand(2));
14524 case Intrinsic::x86_sse41_pmuldq:
14525 case Intrinsic::x86_avx2_pmul_dq:
14526 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14527 Op.getOperand(1), Op.getOperand(2));
14529 case Intrinsic::x86_sse2_pmulhu_w:
14530 case Intrinsic::x86_avx2_pmulhu_w:
14531 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14532 Op.getOperand(1), Op.getOperand(2));
14534 case Intrinsic::x86_sse2_pmulh_w:
14535 case Intrinsic::x86_avx2_pmulh_w:
14536 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14537 Op.getOperand(1), Op.getOperand(2));
14539 // SSE/SSE2/AVX floating point max/min intrinsics.
14540 case Intrinsic::x86_sse_max_ps:
14541 case Intrinsic::x86_sse2_max_pd:
14542 case Intrinsic::x86_avx_max_ps_256:
14543 case Intrinsic::x86_avx_max_pd_256:
14544 case Intrinsic::x86_sse_min_ps:
14545 case Intrinsic::x86_sse2_min_pd:
14546 case Intrinsic::x86_avx_min_ps_256:
14547 case Intrinsic::x86_avx_min_pd_256: {
14550 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14551 case Intrinsic::x86_sse_max_ps:
14552 case Intrinsic::x86_sse2_max_pd:
14553 case Intrinsic::x86_avx_max_ps_256:
14554 case Intrinsic::x86_avx_max_pd_256:
14555 Opcode = X86ISD::FMAX;
14557 case Intrinsic::x86_sse_min_ps:
14558 case Intrinsic::x86_sse2_min_pd:
14559 case Intrinsic::x86_avx_min_ps_256:
14560 case Intrinsic::x86_avx_min_pd_256:
14561 Opcode = X86ISD::FMIN;
14564 return DAG.getNode(Opcode, dl, Op.getValueType(),
14565 Op.getOperand(1), Op.getOperand(2));
14568 // AVX2 variable shift intrinsics
14569 case Intrinsic::x86_avx2_psllv_d:
14570 case Intrinsic::x86_avx2_psllv_q:
14571 case Intrinsic::x86_avx2_psllv_d_256:
14572 case Intrinsic::x86_avx2_psllv_q_256:
14573 case Intrinsic::x86_avx2_psrlv_d:
14574 case Intrinsic::x86_avx2_psrlv_q:
14575 case Intrinsic::x86_avx2_psrlv_d_256:
14576 case Intrinsic::x86_avx2_psrlv_q_256:
14577 case Intrinsic::x86_avx2_psrav_d:
14578 case Intrinsic::x86_avx2_psrav_d_256: {
14581 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14582 case Intrinsic::x86_avx2_psllv_d:
14583 case Intrinsic::x86_avx2_psllv_q:
14584 case Intrinsic::x86_avx2_psllv_d_256:
14585 case Intrinsic::x86_avx2_psllv_q_256:
14588 case Intrinsic::x86_avx2_psrlv_d:
14589 case Intrinsic::x86_avx2_psrlv_q:
14590 case Intrinsic::x86_avx2_psrlv_d_256:
14591 case Intrinsic::x86_avx2_psrlv_q_256:
14594 case Intrinsic::x86_avx2_psrav_d:
14595 case Intrinsic::x86_avx2_psrav_d_256:
14599 return DAG.getNode(Opcode, dl, Op.getValueType(),
14600 Op.getOperand(1), Op.getOperand(2));
14603 case Intrinsic::x86_sse2_packssdw_128:
14604 case Intrinsic::x86_sse2_packsswb_128:
14605 case Intrinsic::x86_avx2_packssdw:
14606 case Intrinsic::x86_avx2_packsswb:
14607 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14608 Op.getOperand(1), Op.getOperand(2));
14610 case Intrinsic::x86_sse2_packuswb_128:
14611 case Intrinsic::x86_sse41_packusdw:
14612 case Intrinsic::x86_avx2_packuswb:
14613 case Intrinsic::x86_avx2_packusdw:
14614 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14615 Op.getOperand(1), Op.getOperand(2));
14617 case Intrinsic::x86_ssse3_pshuf_b_128:
14618 case Intrinsic::x86_avx2_pshuf_b:
14619 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14620 Op.getOperand(1), Op.getOperand(2));
14622 case Intrinsic::x86_sse2_pshuf_d:
14623 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14624 Op.getOperand(1), Op.getOperand(2));
14626 case Intrinsic::x86_sse2_pshufl_w:
14627 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14628 Op.getOperand(1), Op.getOperand(2));
14630 case Intrinsic::x86_sse2_pshufh_w:
14631 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14632 Op.getOperand(1), Op.getOperand(2));
14634 case Intrinsic::x86_ssse3_psign_b_128:
14635 case Intrinsic::x86_ssse3_psign_w_128:
14636 case Intrinsic::x86_ssse3_psign_d_128:
14637 case Intrinsic::x86_avx2_psign_b:
14638 case Intrinsic::x86_avx2_psign_w:
14639 case Intrinsic::x86_avx2_psign_d:
14640 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14641 Op.getOperand(1), Op.getOperand(2));
14643 case Intrinsic::x86_avx2_permd:
14644 case Intrinsic::x86_avx2_permps:
14645 // Operands intentionally swapped. Mask is last operand to intrinsic,
14646 // but second operand for node/instruction.
14647 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14648 Op.getOperand(2), Op.getOperand(1));
14650 case Intrinsic::x86_avx512_mask_valign_q_512:
14651 case Intrinsic::x86_avx512_mask_valign_d_512:
14652 // Vector source operands are swapped.
14653 return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14654 Op.getValueType(), Op.getOperand(2),
14657 Op.getOperand(5), Op.getOperand(4), DAG);
14659 // ptest and testp intrinsics. The intrinsic these come from are designed to
14660 // return an integer value, not just an instruction so lower it to the ptest
14661 // or testp pattern and a setcc for the result.
14662 case Intrinsic::x86_sse41_ptestz:
14663 case Intrinsic::x86_sse41_ptestc:
14664 case Intrinsic::x86_sse41_ptestnzc:
14665 case Intrinsic::x86_avx_ptestz_256:
14666 case Intrinsic::x86_avx_ptestc_256:
14667 case Intrinsic::x86_avx_ptestnzc_256:
14668 case Intrinsic::x86_avx_vtestz_ps:
14669 case Intrinsic::x86_avx_vtestc_ps:
14670 case Intrinsic::x86_avx_vtestnzc_ps:
14671 case Intrinsic::x86_avx_vtestz_pd:
14672 case Intrinsic::x86_avx_vtestc_pd:
14673 case Intrinsic::x86_avx_vtestnzc_pd:
14674 case Intrinsic::x86_avx_vtestz_ps_256:
14675 case Intrinsic::x86_avx_vtestc_ps_256:
14676 case Intrinsic::x86_avx_vtestnzc_ps_256:
14677 case Intrinsic::x86_avx_vtestz_pd_256:
14678 case Intrinsic::x86_avx_vtestc_pd_256:
14679 case Intrinsic::x86_avx_vtestnzc_pd_256: {
14680 bool IsTestPacked = false;
14683 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14684 case Intrinsic::x86_avx_vtestz_ps:
14685 case Intrinsic::x86_avx_vtestz_pd:
14686 case Intrinsic::x86_avx_vtestz_ps_256:
14687 case Intrinsic::x86_avx_vtestz_pd_256:
14688 IsTestPacked = true; // Fallthrough
14689 case Intrinsic::x86_sse41_ptestz:
14690 case Intrinsic::x86_avx_ptestz_256:
14692 X86CC = X86::COND_E;
14694 case Intrinsic::x86_avx_vtestc_ps:
14695 case Intrinsic::x86_avx_vtestc_pd:
14696 case Intrinsic::x86_avx_vtestc_ps_256:
14697 case Intrinsic::x86_avx_vtestc_pd_256:
14698 IsTestPacked = true; // Fallthrough
14699 case Intrinsic::x86_sse41_ptestc:
14700 case Intrinsic::x86_avx_ptestc_256:
14702 X86CC = X86::COND_B;
14704 case Intrinsic::x86_avx_vtestnzc_ps:
14705 case Intrinsic::x86_avx_vtestnzc_pd:
14706 case Intrinsic::x86_avx_vtestnzc_ps_256:
14707 case Intrinsic::x86_avx_vtestnzc_pd_256:
14708 IsTestPacked = true; // Fallthrough
14709 case Intrinsic::x86_sse41_ptestnzc:
14710 case Intrinsic::x86_avx_ptestnzc_256:
14712 X86CC = X86::COND_A;
14716 SDValue LHS = Op.getOperand(1);
14717 SDValue RHS = Op.getOperand(2);
14718 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14719 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14720 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14721 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14722 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14724 case Intrinsic::x86_avx512_kortestz_w:
14725 case Intrinsic::x86_avx512_kortestc_w: {
14726 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14727 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14728 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14729 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14730 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14731 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14732 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14735 case Intrinsic::x86_sse42_pcmpistria128:
14736 case Intrinsic::x86_sse42_pcmpestria128:
14737 case Intrinsic::x86_sse42_pcmpistric128:
14738 case Intrinsic::x86_sse42_pcmpestric128:
14739 case Intrinsic::x86_sse42_pcmpistrio128:
14740 case Intrinsic::x86_sse42_pcmpestrio128:
14741 case Intrinsic::x86_sse42_pcmpistris128:
14742 case Intrinsic::x86_sse42_pcmpestris128:
14743 case Intrinsic::x86_sse42_pcmpistriz128:
14744 case Intrinsic::x86_sse42_pcmpestriz128: {
14748 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14749 case Intrinsic::x86_sse42_pcmpistria128:
14750 Opcode = X86ISD::PCMPISTRI;
14751 X86CC = X86::COND_A;
14753 case Intrinsic::x86_sse42_pcmpestria128:
14754 Opcode = X86ISD::PCMPESTRI;
14755 X86CC = X86::COND_A;
14757 case Intrinsic::x86_sse42_pcmpistric128:
14758 Opcode = X86ISD::PCMPISTRI;
14759 X86CC = X86::COND_B;
14761 case Intrinsic::x86_sse42_pcmpestric128:
14762 Opcode = X86ISD::PCMPESTRI;
14763 X86CC = X86::COND_B;
14765 case Intrinsic::x86_sse42_pcmpistrio128:
14766 Opcode = X86ISD::PCMPISTRI;
14767 X86CC = X86::COND_O;
14769 case Intrinsic::x86_sse42_pcmpestrio128:
14770 Opcode = X86ISD::PCMPESTRI;
14771 X86CC = X86::COND_O;
14773 case Intrinsic::x86_sse42_pcmpistris128:
14774 Opcode = X86ISD::PCMPISTRI;
14775 X86CC = X86::COND_S;
14777 case Intrinsic::x86_sse42_pcmpestris128:
14778 Opcode = X86ISD::PCMPESTRI;
14779 X86CC = X86::COND_S;
14781 case Intrinsic::x86_sse42_pcmpistriz128:
14782 Opcode = X86ISD::PCMPISTRI;
14783 X86CC = X86::COND_E;
14785 case Intrinsic::x86_sse42_pcmpestriz128:
14786 Opcode = X86ISD::PCMPESTRI;
14787 X86CC = X86::COND_E;
14790 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14791 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14792 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14793 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14794 DAG.getConstant(X86CC, MVT::i8),
14795 SDValue(PCMP.getNode(), 1));
14796 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14799 case Intrinsic::x86_sse42_pcmpistri128:
14800 case Intrinsic::x86_sse42_pcmpestri128: {
14802 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14803 Opcode = X86ISD::PCMPISTRI;
14805 Opcode = X86ISD::PCMPESTRI;
14807 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14808 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14809 return DAG.getNode(Opcode, dl, VTs, NewOps);
14812 case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14813 case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14814 case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14815 case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14816 case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14817 case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14818 case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14819 case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14820 case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14821 case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14822 case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14823 case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
14824 auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
14825 if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
14826 return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
14827 dl, Op.getValueType(),
14831 Op.getOperand(4), Op.getOperand(1), DAG);
14836 case Intrinsic::x86_fma_vfmadd_ps:
14837 case Intrinsic::x86_fma_vfmadd_pd:
14838 case Intrinsic::x86_fma_vfmsub_ps:
14839 case Intrinsic::x86_fma_vfmsub_pd:
14840 case Intrinsic::x86_fma_vfnmadd_ps:
14841 case Intrinsic::x86_fma_vfnmadd_pd:
14842 case Intrinsic::x86_fma_vfnmsub_ps:
14843 case Intrinsic::x86_fma_vfnmsub_pd:
14844 case Intrinsic::x86_fma_vfmaddsub_ps:
14845 case Intrinsic::x86_fma_vfmaddsub_pd:
14846 case Intrinsic::x86_fma_vfmsubadd_ps:
14847 case Intrinsic::x86_fma_vfmsubadd_pd:
14848 case Intrinsic::x86_fma_vfmadd_ps_256:
14849 case Intrinsic::x86_fma_vfmadd_pd_256:
14850 case Intrinsic::x86_fma_vfmsub_ps_256:
14851 case Intrinsic::x86_fma_vfmsub_pd_256:
14852 case Intrinsic::x86_fma_vfnmadd_ps_256:
14853 case Intrinsic::x86_fma_vfnmadd_pd_256:
14854 case Intrinsic::x86_fma_vfnmsub_ps_256:
14855 case Intrinsic::x86_fma_vfnmsub_pd_256:
14856 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14857 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14858 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14859 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14860 return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
14861 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14865 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14866 SDValue Src, SDValue Mask, SDValue Base,
14867 SDValue Index, SDValue ScaleOp, SDValue Chain,
14868 const X86Subtarget * Subtarget) {
14870 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14871 assert(C && "Invalid scale type");
14872 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14873 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14874 Index.getSimpleValueType().getVectorNumElements());
14876 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14878 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14880 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14881 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14882 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14883 SDValue Segment = DAG.getRegister(0, MVT::i32);
14884 if (Src.getOpcode() == ISD::UNDEF)
14885 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14886 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14887 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14888 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14889 return DAG.getMergeValues(RetOps, dl);
14892 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14893 SDValue Src, SDValue Mask, SDValue Base,
14894 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14896 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14897 assert(C && "Invalid scale type");
14898 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14899 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14900 SDValue Segment = DAG.getRegister(0, MVT::i32);
14901 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14902 Index.getSimpleValueType().getVectorNumElements());
14904 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14906 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14908 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14909 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14910 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14911 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14912 return SDValue(Res, 1);
14915 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14916 SDValue Mask, SDValue Base, SDValue Index,
14917 SDValue ScaleOp, SDValue Chain) {
14919 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14920 assert(C && "Invalid scale type");
14921 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14922 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14923 SDValue Segment = DAG.getRegister(0, MVT::i32);
14925 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14927 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14929 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14931 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14932 //SDVTList VTs = DAG.getVTList(MVT::Other);
14933 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14934 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14935 return SDValue(Res, 0);
14938 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14939 // read performance monitor counters (x86_rdpmc).
14940 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14941 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14942 SmallVectorImpl<SDValue> &Results) {
14943 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14944 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14947 // The ECX register is used to select the index of the performance counter
14949 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14951 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14953 // Reads the content of a 64-bit performance counter and returns it in the
14954 // registers EDX:EAX.
14955 if (Subtarget->is64Bit()) {
14956 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14957 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14960 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14961 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14964 Chain = HI.getValue(1);
14966 if (Subtarget->is64Bit()) {
14967 // The EAX register is loaded with the low-order 32 bits. The EDX register
14968 // is loaded with the supported high-order bits of the counter.
14969 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14970 DAG.getConstant(32, MVT::i8));
14971 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14972 Results.push_back(Chain);
14976 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14977 SDValue Ops[] = { LO, HI };
14978 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14979 Results.push_back(Pair);
14980 Results.push_back(Chain);
14983 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14984 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14985 // also used to custom lower READCYCLECOUNTER nodes.
14986 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14987 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14988 SmallVectorImpl<SDValue> &Results) {
14989 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14990 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14993 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14994 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14995 // and the EAX register is loaded with the low-order 32 bits.
14996 if (Subtarget->is64Bit()) {
14997 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14998 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15001 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15002 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15005 SDValue Chain = HI.getValue(1);
15007 if (Opcode == X86ISD::RDTSCP_DAG) {
15008 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15010 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15011 // the ECX register. Add 'ecx' explicitly to the chain.
15012 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15014 // Explicitly store the content of ECX at the location passed in input
15015 // to the 'rdtscp' intrinsic.
15016 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15017 MachinePointerInfo(), false, false, 0);
15020 if (Subtarget->is64Bit()) {
15021 // The EDX register is loaded with the high-order 32 bits of the MSR, and
15022 // the EAX register is loaded with the low-order 32 bits.
15023 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15024 DAG.getConstant(32, MVT::i8));
15025 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15026 Results.push_back(Chain);
15030 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15031 SDValue Ops[] = { LO, HI };
15032 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15033 Results.push_back(Pair);
15034 Results.push_back(Chain);
15037 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15038 SelectionDAG &DAG) {
15039 SmallVector<SDValue, 2> Results;
15041 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15043 return DAG.getMergeValues(Results, DL);
15047 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15048 SelectionDAG &DAG) {
15049 InitIntrinsicsWithChain();
15050 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15052 const IntrinsicData* IntrData = GetIntrinsicWithChain(IntNo);
15057 switch(IntrData->Type) {
15059 llvm_unreachable("Unknown Intrinsic Type");
15063 // Emit the node with the right value type.
15064 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15065 SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15067 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15068 // Otherwise return the value from Rand, which is always 0, casted to i32.
15069 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15070 DAG.getConstant(1, Op->getValueType(1)),
15071 DAG.getConstant(X86::COND_B, MVT::i32),
15072 SDValue(Result.getNode(), 1) };
15073 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15074 DAG.getVTList(Op->getValueType(1), MVT::Glue),
15077 // Return { result, isValid, chain }.
15078 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15079 SDValue(Result.getNode(), 2));
15082 //gather(v1, mask, index, base, scale);
15083 SDValue Chain = Op.getOperand(0);
15084 SDValue Src = Op.getOperand(2);
15085 SDValue Base = Op.getOperand(3);
15086 SDValue Index = Op.getOperand(4);
15087 SDValue Mask = Op.getOperand(5);
15088 SDValue Scale = Op.getOperand(6);
15089 return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15093 //scatter(base, mask, index, v1, scale);
15094 SDValue Chain = Op.getOperand(0);
15095 SDValue Base = Op.getOperand(2);
15096 SDValue Mask = Op.getOperand(3);
15097 SDValue Index = Op.getOperand(4);
15098 SDValue Src = Op.getOperand(5);
15099 SDValue Scale = Op.getOperand(6);
15100 return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15103 SDValue Hint = Op.getOperand(6);
15105 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15106 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15107 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15108 unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15109 SDValue Chain = Op.getOperand(0);
15110 SDValue Mask = Op.getOperand(2);
15111 SDValue Index = Op.getOperand(3);
15112 SDValue Base = Op.getOperand(4);
15113 SDValue Scale = Op.getOperand(5);
15114 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15116 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15118 SmallVector<SDValue, 2> Results;
15119 getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15120 return DAG.getMergeValues(Results, dl);
15122 // Read Performance Monitoring Counters.
15124 SmallVector<SDValue, 2> Results;
15125 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15126 return DAG.getMergeValues(Results, dl);
15128 // XTEST intrinsics.
15130 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15131 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
15132 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15133 DAG.getConstant(X86::COND_NE, MVT::i8),
15135 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15136 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15137 Ret, SDValue(InTrans.getNode(), 1));
15143 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15144 SelectionDAG &DAG) const {
15145 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15146 MFI->setReturnAddressIsTaken(true);
15148 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15151 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15153 EVT PtrVT = getPointerTy();
15156 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15157 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15158 DAG.getSubtarget().getRegisterInfo());
15159 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15160 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15161 DAG.getNode(ISD::ADD, dl, PtrVT,
15162 FrameAddr, Offset),
15163 MachinePointerInfo(), false, false, false, 0);
15166 // Just load the return address.
15167 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15168 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15169 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15172 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15173 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15174 MFI->setFrameAddressIsTaken(true);
15176 EVT VT = Op.getValueType();
15177 SDLoc dl(Op); // FIXME probably not meaningful
15178 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15179 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15180 DAG.getSubtarget().getRegisterInfo());
15181 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15182 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15183 (FrameReg == X86::EBP && VT == MVT::i32)) &&
15184 "Invalid Frame Register!");
15185 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15187 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15188 MachinePointerInfo(),
15189 false, false, false, 0);
15193 // FIXME? Maybe this could be a TableGen attribute on some registers and
15194 // this table could be generated automatically from RegInfo.
15195 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15197 unsigned Reg = StringSwitch<unsigned>(RegName)
15198 .Case("esp", X86::ESP)
15199 .Case("rsp", X86::RSP)
15203 report_fatal_error("Invalid register name global variable");
15206 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15207 SelectionDAG &DAG) const {
15208 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15209 DAG.getSubtarget().getRegisterInfo());
15210 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15213 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15214 SDValue Chain = Op.getOperand(0);
15215 SDValue Offset = Op.getOperand(1);
15216 SDValue Handler = Op.getOperand(2);
15219 EVT PtrVT = getPointerTy();
15220 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15221 DAG.getSubtarget().getRegisterInfo());
15222 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15223 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15224 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15225 "Invalid Frame Register!");
15226 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15227 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15229 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15230 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15231 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15232 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15234 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15236 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15237 DAG.getRegister(StoreAddrReg, PtrVT));
15240 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15241 SelectionDAG &DAG) const {
15243 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15244 DAG.getVTList(MVT::i32, MVT::Other),
15245 Op.getOperand(0), Op.getOperand(1));
15248 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15249 SelectionDAG &DAG) const {
15251 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15252 Op.getOperand(0), Op.getOperand(1));
15255 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15256 return Op.getOperand(0);
15259 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15260 SelectionDAG &DAG) const {
15261 SDValue Root = Op.getOperand(0);
15262 SDValue Trmp = Op.getOperand(1); // trampoline
15263 SDValue FPtr = Op.getOperand(2); // nested function
15264 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15267 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15268 const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15270 if (Subtarget->is64Bit()) {
15271 SDValue OutChains[6];
15273 // Large code-model.
15274 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
15275 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15277 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15278 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15280 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15282 // Load the pointer to the nested function into R11.
15283 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15284 SDValue Addr = Trmp;
15285 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15286 Addr, MachinePointerInfo(TrmpAddr),
15289 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15290 DAG.getConstant(2, MVT::i64));
15291 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15292 MachinePointerInfo(TrmpAddr, 2),
15295 // Load the 'nest' parameter value into R10.
15296 // R10 is specified in X86CallingConv.td
15297 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15298 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15299 DAG.getConstant(10, MVT::i64));
15300 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15301 Addr, MachinePointerInfo(TrmpAddr, 10),
15304 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15305 DAG.getConstant(12, MVT::i64));
15306 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15307 MachinePointerInfo(TrmpAddr, 12),
15310 // Jump to the nested function.
15311 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15312 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15313 DAG.getConstant(20, MVT::i64));
15314 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15315 Addr, MachinePointerInfo(TrmpAddr, 20),
15318 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15319 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15320 DAG.getConstant(22, MVT::i64));
15321 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15322 MachinePointerInfo(TrmpAddr, 22),
15325 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15327 const Function *Func =
15328 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15329 CallingConv::ID CC = Func->getCallingConv();
15334 llvm_unreachable("Unsupported calling convention");
15335 case CallingConv::C:
15336 case CallingConv::X86_StdCall: {
15337 // Pass 'nest' parameter in ECX.
15338 // Must be kept in sync with X86CallingConv.td
15339 NestReg = X86::ECX;
15341 // Check that ECX wasn't needed by an 'inreg' parameter.
15342 FunctionType *FTy = Func->getFunctionType();
15343 const AttributeSet &Attrs = Func->getAttributes();
15345 if (!Attrs.isEmpty() && !Func->isVarArg()) {
15346 unsigned InRegCount = 0;
15349 for (FunctionType::param_iterator I = FTy->param_begin(),
15350 E = FTy->param_end(); I != E; ++I, ++Idx)
15351 if (Attrs.hasAttribute(Idx, Attribute::InReg))
15352 // FIXME: should only count parameters that are lowered to integers.
15353 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15355 if (InRegCount > 2) {
15356 report_fatal_error("Nest register in use - reduce number of inreg"
15362 case CallingConv::X86_FastCall:
15363 case CallingConv::X86_ThisCall:
15364 case CallingConv::Fast:
15365 // Pass 'nest' parameter in EAX.
15366 // Must be kept in sync with X86CallingConv.td
15367 NestReg = X86::EAX;
15371 SDValue OutChains[4];
15372 SDValue Addr, Disp;
15374 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15375 DAG.getConstant(10, MVT::i32));
15376 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15378 // This is storing the opcode for MOV32ri.
15379 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15380 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15381 OutChains[0] = DAG.getStore(Root, dl,
15382 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15383 Trmp, MachinePointerInfo(TrmpAddr),
15386 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15387 DAG.getConstant(1, MVT::i32));
15388 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15389 MachinePointerInfo(TrmpAddr, 1),
15392 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15393 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15394 DAG.getConstant(5, MVT::i32));
15395 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15396 MachinePointerInfo(TrmpAddr, 5),
15399 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15400 DAG.getConstant(6, MVT::i32));
15401 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15402 MachinePointerInfo(TrmpAddr, 6),
15405 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15409 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15410 SelectionDAG &DAG) const {
15412 The rounding mode is in bits 11:10 of FPSR, and has the following
15414 00 Round to nearest
15419 FLT_ROUNDS, on the other hand, expects the following:
15426 To perform the conversion, we do:
15427 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15430 MachineFunction &MF = DAG.getMachineFunction();
15431 const TargetMachine &TM = MF.getTarget();
15432 const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15433 unsigned StackAlignment = TFI.getStackAlignment();
15434 MVT VT = Op.getSimpleValueType();
15437 // Save FP Control Word to stack slot
15438 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15439 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15441 MachineMemOperand *MMO =
15442 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15443 MachineMemOperand::MOStore, 2, 2);
15445 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15446 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15447 DAG.getVTList(MVT::Other),
15448 Ops, MVT::i16, MMO);
15450 // Load FP Control Word from stack slot
15451 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15452 MachinePointerInfo(), false, false, false, 0);
15454 // Transform as necessary
15456 DAG.getNode(ISD::SRL, DL, MVT::i16,
15457 DAG.getNode(ISD::AND, DL, MVT::i16,
15458 CWD, DAG.getConstant(0x800, MVT::i16)),
15459 DAG.getConstant(11, MVT::i8));
15461 DAG.getNode(ISD::SRL, DL, MVT::i16,
15462 DAG.getNode(ISD::AND, DL, MVT::i16,
15463 CWD, DAG.getConstant(0x400, MVT::i16)),
15464 DAG.getConstant(9, MVT::i8));
15467 DAG.getNode(ISD::AND, DL, MVT::i16,
15468 DAG.getNode(ISD::ADD, DL, MVT::i16,
15469 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15470 DAG.getConstant(1, MVT::i16)),
15471 DAG.getConstant(3, MVT::i16));
15473 return DAG.getNode((VT.getSizeInBits() < 16 ?
15474 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15477 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15478 MVT VT = Op.getSimpleValueType();
15480 unsigned NumBits = VT.getSizeInBits();
15483 Op = Op.getOperand(0);
15484 if (VT == MVT::i8) {
15485 // Zero extend to i32 since there is not an i8 bsr.
15487 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15490 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15491 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15492 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15494 // If src is zero (i.e. bsr sets ZF), returns NumBits.
15497 DAG.getConstant(NumBits+NumBits-1, OpVT),
15498 DAG.getConstant(X86::COND_E, MVT::i8),
15501 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15503 // Finally xor with NumBits-1.
15504 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15507 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15511 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15512 MVT VT = Op.getSimpleValueType();
15514 unsigned NumBits = VT.getSizeInBits();
15517 Op = Op.getOperand(0);
15518 if (VT == MVT::i8) {
15519 // Zero extend to i32 since there is not an i8 bsr.
15521 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15524 // Issue a bsr (scan bits in reverse).
15525 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15526 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15528 // And xor with NumBits-1.
15529 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15532 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15536 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15537 MVT VT = Op.getSimpleValueType();
15538 unsigned NumBits = VT.getSizeInBits();
15540 Op = Op.getOperand(0);
15542 // Issue a bsf (scan bits forward) which also sets EFLAGS.
15543 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15544 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15546 // If src is zero (i.e. bsf sets ZF), returns NumBits.
15549 DAG.getConstant(NumBits, VT),
15550 DAG.getConstant(X86::COND_E, MVT::i8),
15553 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15556 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15557 // ones, and then concatenate the result back.
15558 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15559 MVT VT = Op.getSimpleValueType();
15561 assert(VT.is256BitVector() && VT.isInteger() &&
15562 "Unsupported value type for operation");
15564 unsigned NumElems = VT.getVectorNumElements();
15567 // Extract the LHS vectors
15568 SDValue LHS = Op.getOperand(0);
15569 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15570 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15572 // Extract the RHS vectors
15573 SDValue RHS = Op.getOperand(1);
15574 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15575 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15577 MVT EltVT = VT.getVectorElementType();
15578 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15580 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15581 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15582 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15585 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15586 assert(Op.getSimpleValueType().is256BitVector() &&
15587 Op.getSimpleValueType().isInteger() &&
15588 "Only handle AVX 256-bit vector integer operation");
15589 return Lower256IntArith(Op, DAG);
15592 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15593 assert(Op.getSimpleValueType().is256BitVector() &&
15594 Op.getSimpleValueType().isInteger() &&
15595 "Only handle AVX 256-bit vector integer operation");
15596 return Lower256IntArith(Op, DAG);
15599 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15600 SelectionDAG &DAG) {
15602 MVT VT = Op.getSimpleValueType();
15604 // Decompose 256-bit ops into smaller 128-bit ops.
15605 if (VT.is256BitVector() && !Subtarget->hasInt256())
15606 return Lower256IntArith(Op, DAG);
15608 SDValue A = Op.getOperand(0);
15609 SDValue B = Op.getOperand(1);
15611 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15612 if (VT == MVT::v4i32) {
15613 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15614 "Should not custom lower when pmuldq is available!");
15616 // Extract the odd parts.
15617 static const int UnpackMask[] = { 1, -1, 3, -1 };
15618 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15619 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15621 // Multiply the even parts.
15622 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15623 // Now multiply odd parts.
15624 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15626 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15627 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15629 // Merge the two vectors back together with a shuffle. This expands into 2
15631 static const int ShufMask[] = { 0, 4, 2, 6 };
15632 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15635 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15636 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15638 // Ahi = psrlqi(a, 32);
15639 // Bhi = psrlqi(b, 32);
15641 // AloBlo = pmuludq(a, b);
15642 // AloBhi = pmuludq(a, Bhi);
15643 // AhiBlo = pmuludq(Ahi, b);
15645 // AloBhi = psllqi(AloBhi, 32);
15646 // AhiBlo = psllqi(AhiBlo, 32);
15647 // return AloBlo + AloBhi + AhiBlo;
15649 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15650 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15652 // Bit cast to 32-bit vectors for MULUDQ
15653 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15654 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15655 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15656 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15657 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15658 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15660 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15661 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15662 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15664 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15665 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15667 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15668 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15671 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15672 assert(Subtarget->isTargetWin64() && "Unexpected target");
15673 EVT VT = Op.getValueType();
15674 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15675 "Unexpected return type for lowering");
15679 switch (Op->getOpcode()) {
15680 default: llvm_unreachable("Unexpected request for libcall!");
15681 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15682 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15683 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15684 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15685 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15686 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15690 SDValue InChain = DAG.getEntryNode();
15692 TargetLowering::ArgListTy Args;
15693 TargetLowering::ArgListEntry Entry;
15694 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15695 EVT ArgVT = Op->getOperand(i).getValueType();
15696 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15697 "Unexpected argument type for lowering");
15698 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15699 Entry.Node = StackPtr;
15700 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15702 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15703 Entry.Ty = PointerType::get(ArgTy,0);
15704 Entry.isSExt = false;
15705 Entry.isZExt = false;
15706 Args.push_back(Entry);
15709 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15712 TargetLowering::CallLoweringInfo CLI(DAG);
15713 CLI.setDebugLoc(dl).setChain(InChain)
15714 .setCallee(getLibcallCallingConv(LC),
15715 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15716 Callee, std::move(Args), 0)
15717 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15719 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15720 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15723 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15724 SelectionDAG &DAG) {
15725 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15726 EVT VT = Op0.getValueType();
15729 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15730 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15732 // PMULxD operations multiply each even value (starting at 0) of LHS with
15733 // the related value of RHS and produce a widen result.
15734 // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15735 // => <2 x i64> <ae|cg>
15737 // In other word, to have all the results, we need to perform two PMULxD:
15738 // 1. one with the even values.
15739 // 2. one with the odd values.
15740 // To achieve #2, with need to place the odd values at an even position.
15742 // Place the odd value at an even position (basically, shift all values 1
15743 // step to the left):
15744 const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15745 // <a|b|c|d> => <b|undef|d|undef>
15746 SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15747 // <e|f|g|h> => <f|undef|h|undef>
15748 SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15750 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15752 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15753 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15755 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15756 // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15757 // => <2 x i64> <ae|cg>
15758 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15759 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15760 // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15761 // => <2 x i64> <bf|dh>
15762 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15763 DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15765 // Shuffle it back into the right order.
15766 SDValue Highs, Lows;
15767 if (VT == MVT::v8i32) {
15768 const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15769 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15770 const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15771 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15773 const int HighMask[] = {1, 5, 3, 7};
15774 Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15775 const int LowMask[] = {0, 4, 2, 6};
15776 Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15779 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15780 // unsigned multiply.
15781 if (IsSigned && !Subtarget->hasSSE41()) {
15783 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15784 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15785 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15786 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15787 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15789 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15790 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15793 // The first result of MUL_LOHI is actually the low value, followed by the
15795 SDValue Ops[] = {Lows, Highs};
15796 return DAG.getMergeValues(Ops, dl);
15799 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15800 const X86Subtarget *Subtarget) {
15801 MVT VT = Op.getSimpleValueType();
15803 SDValue R = Op.getOperand(0);
15804 SDValue Amt = Op.getOperand(1);
15806 // Optimize shl/srl/sra with constant shift amount.
15807 if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15808 if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15809 uint64_t ShiftAmt = ShiftConst->getZExtValue();
15811 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15812 (Subtarget->hasInt256() &&
15813 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15814 (Subtarget->hasAVX512() &&
15815 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15816 if (Op.getOpcode() == ISD::SHL)
15817 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15819 if (Op.getOpcode() == ISD::SRL)
15820 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15822 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15823 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15827 if (VT == MVT::v16i8) {
15828 if (Op.getOpcode() == ISD::SHL) {
15829 // Make a large shift.
15830 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15831 MVT::v8i16, R, ShiftAmt,
15833 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15834 // Zero out the rightmost bits.
15835 SmallVector<SDValue, 16> V(16,
15836 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15838 return DAG.getNode(ISD::AND, dl, VT, SHL,
15839 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15841 if (Op.getOpcode() == ISD::SRL) {
15842 // Make a large shift.
15843 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15844 MVT::v8i16, R, ShiftAmt,
15846 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15847 // Zero out the leftmost bits.
15848 SmallVector<SDValue, 16> V(16,
15849 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15851 return DAG.getNode(ISD::AND, dl, VT, SRL,
15852 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15854 if (Op.getOpcode() == ISD::SRA) {
15855 if (ShiftAmt == 7) {
15856 // R s>> 7 === R s< 0
15857 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15858 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15861 // R s>> a === ((R u>> a) ^ m) - m
15862 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15863 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15865 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15866 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15867 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15870 llvm_unreachable("Unknown shift opcode.");
15873 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15874 if (Op.getOpcode() == ISD::SHL) {
15875 // Make a large shift.
15876 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15877 MVT::v16i16, R, ShiftAmt,
15879 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15880 // Zero out the rightmost bits.
15881 SmallVector<SDValue, 32> V(32,
15882 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15884 return DAG.getNode(ISD::AND, dl, VT, SHL,
15885 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15887 if (Op.getOpcode() == ISD::SRL) {
15888 // Make a large shift.
15889 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15890 MVT::v16i16, R, ShiftAmt,
15892 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15893 // Zero out the leftmost bits.
15894 SmallVector<SDValue, 32> V(32,
15895 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15897 return DAG.getNode(ISD::AND, dl, VT, SRL,
15898 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15900 if (Op.getOpcode() == ISD::SRA) {
15901 if (ShiftAmt == 7) {
15902 // R s>> 7 === R s< 0
15903 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15904 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15907 // R s>> a === ((R u>> a) ^ m) - m
15908 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15909 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15911 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15912 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15913 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15916 llvm_unreachable("Unknown shift opcode.");
15921 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15922 if (!Subtarget->is64Bit() &&
15923 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15924 Amt.getOpcode() == ISD::BITCAST &&
15925 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15926 Amt = Amt.getOperand(0);
15927 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15928 VT.getVectorNumElements();
15929 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15930 uint64_t ShiftAmt = 0;
15931 for (unsigned i = 0; i != Ratio; ++i) {
15932 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15936 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15938 // Check remaining shift amounts.
15939 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15940 uint64_t ShAmt = 0;
15941 for (unsigned j = 0; j != Ratio; ++j) {
15942 ConstantSDNode *C =
15943 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15947 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15949 if (ShAmt != ShiftAmt)
15952 switch (Op.getOpcode()) {
15954 llvm_unreachable("Unknown shift opcode!");
15956 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15959 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15962 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15970 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15971 const X86Subtarget* Subtarget) {
15972 MVT VT = Op.getSimpleValueType();
15974 SDValue R = Op.getOperand(0);
15975 SDValue Amt = Op.getOperand(1);
15977 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15978 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15979 (Subtarget->hasInt256() &&
15980 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15981 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15982 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15984 EVT EltVT = VT.getVectorElementType();
15986 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15987 unsigned NumElts = VT.getVectorNumElements();
15989 for (i = 0; i != NumElts; ++i) {
15990 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15994 for (j = i; j != NumElts; ++j) {
15995 SDValue Arg = Amt.getOperand(j);
15996 if (Arg.getOpcode() == ISD::UNDEF) continue;
15997 if (Arg != Amt.getOperand(i))
16000 if (i != NumElts && j == NumElts)
16001 BaseShAmt = Amt.getOperand(i);
16003 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16004 Amt = Amt.getOperand(0);
16005 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
16006 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
16007 SDValue InVec = Amt.getOperand(0);
16008 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16009 unsigned NumElts = InVec.getValueType().getVectorNumElements();
16011 for (; i != NumElts; ++i) {
16012 SDValue Arg = InVec.getOperand(i);
16013 if (Arg.getOpcode() == ISD::UNDEF) continue;
16017 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16018 if (ConstantSDNode *C =
16019 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16020 unsigned SplatIdx =
16021 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16022 if (C->getZExtValue() == SplatIdx)
16023 BaseShAmt = InVec.getOperand(1);
16026 if (!BaseShAmt.getNode())
16027 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16028 DAG.getIntPtrConstant(0));
16032 if (BaseShAmt.getNode()) {
16033 if (EltVT.bitsGT(MVT::i32))
16034 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16035 else if (EltVT.bitsLT(MVT::i32))
16036 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16038 switch (Op.getOpcode()) {
16040 llvm_unreachable("Unknown shift opcode!");
16042 switch (VT.SimpleTy) {
16043 default: return SDValue();
16052 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16055 switch (VT.SimpleTy) {
16056 default: return SDValue();
16063 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16066 switch (VT.SimpleTy) {
16067 default: return SDValue();
16076 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16082 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16083 if (!Subtarget->is64Bit() &&
16084 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16085 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16086 Amt.getOpcode() == ISD::BITCAST &&
16087 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16088 Amt = Amt.getOperand(0);
16089 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16090 VT.getVectorNumElements();
16091 std::vector<SDValue> Vals(Ratio);
16092 for (unsigned i = 0; i != Ratio; ++i)
16093 Vals[i] = Amt.getOperand(i);
16094 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16095 for (unsigned j = 0; j != Ratio; ++j)
16096 if (Vals[j] != Amt.getOperand(i + j))
16099 switch (Op.getOpcode()) {
16101 llvm_unreachable("Unknown shift opcode!");
16103 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16105 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16107 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16114 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16115 SelectionDAG &DAG) {
16116 MVT VT = Op.getSimpleValueType();
16118 SDValue R = Op.getOperand(0);
16119 SDValue Amt = Op.getOperand(1);
16122 assert(VT.isVector() && "Custom lowering only for vector shifts!");
16123 assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16125 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16129 V = LowerScalarVariableShift(Op, DAG, Subtarget);
16133 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16135 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16136 if (Subtarget->hasInt256()) {
16137 if (Op.getOpcode() == ISD::SRL &&
16138 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16139 VT == MVT::v4i64 || VT == MVT::v8i32))
16141 if (Op.getOpcode() == ISD::SHL &&
16142 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16143 VT == MVT::v4i64 || VT == MVT::v8i32))
16145 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16149 // If possible, lower this packed shift into a vector multiply instead of
16150 // expanding it into a sequence of scalar shifts.
16151 // Do this only if the vector shift count is a constant build_vector.
16152 if (Op.getOpcode() == ISD::SHL &&
16153 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16154 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16155 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16156 SmallVector<SDValue, 8> Elts;
16157 EVT SVT = VT.getScalarType();
16158 unsigned SVTBits = SVT.getSizeInBits();
16159 const APInt &One = APInt(SVTBits, 1);
16160 unsigned NumElems = VT.getVectorNumElements();
16162 for (unsigned i=0; i !=NumElems; ++i) {
16163 SDValue Op = Amt->getOperand(i);
16164 if (Op->getOpcode() == ISD::UNDEF) {
16165 Elts.push_back(Op);
16169 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16170 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16171 uint64_t ShAmt = C.getZExtValue();
16172 if (ShAmt >= SVTBits) {
16173 Elts.push_back(DAG.getUNDEF(SVT));
16176 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16178 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16179 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16182 // Lower SHL with variable shift amount.
16183 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16184 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16186 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16187 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16188 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16189 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16192 // If possible, lower this shift as a sequence of two shifts by
16193 // constant plus a MOVSS/MOVSD instead of scalarizing it.
16195 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16197 // Could be rewritten as:
16198 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16200 // The advantage is that the two shifts from the example would be
16201 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16202 // the vector shift into four scalar shifts plus four pairs of vector
16204 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16205 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16206 unsigned TargetOpcode = X86ISD::MOVSS;
16207 bool CanBeSimplified;
16208 // The splat value for the first packed shift (the 'X' from the example).
16209 SDValue Amt1 = Amt->getOperand(0);
16210 // The splat value for the second packed shift (the 'Y' from the example).
16211 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16212 Amt->getOperand(2);
16214 // See if it is possible to replace this node with a sequence of
16215 // two shifts followed by a MOVSS/MOVSD
16216 if (VT == MVT::v4i32) {
16217 // Check if it is legal to use a MOVSS.
16218 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16219 Amt2 == Amt->getOperand(3);
16220 if (!CanBeSimplified) {
16221 // Otherwise, check if we can still simplify this node using a MOVSD.
16222 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16223 Amt->getOperand(2) == Amt->getOperand(3);
16224 TargetOpcode = X86ISD::MOVSD;
16225 Amt2 = Amt->getOperand(2);
16228 // Do similar checks for the case where the machine value type
16230 CanBeSimplified = Amt1 == Amt->getOperand(1);
16231 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16232 CanBeSimplified = Amt2 == Amt->getOperand(i);
16234 if (!CanBeSimplified) {
16235 TargetOpcode = X86ISD::MOVSD;
16236 CanBeSimplified = true;
16237 Amt2 = Amt->getOperand(4);
16238 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16239 CanBeSimplified = Amt1 == Amt->getOperand(i);
16240 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16241 CanBeSimplified = Amt2 == Amt->getOperand(j);
16245 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16246 isa<ConstantSDNode>(Amt2)) {
16247 // Replace this node with two shifts followed by a MOVSS/MOVSD.
16248 EVT CastVT = MVT::v4i32;
16250 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16251 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16253 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16254 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16255 if (TargetOpcode == X86ISD::MOVSD)
16256 CastVT = MVT::v2i64;
16257 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16258 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16259 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16261 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16265 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16266 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16269 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16270 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16272 // Turn 'a' into a mask suitable for VSELECT
16273 SDValue VSelM = DAG.getConstant(0x80, VT);
16274 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16275 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16277 SDValue CM1 = DAG.getConstant(0x0f, VT);
16278 SDValue CM2 = DAG.getConstant(0x3f, VT);
16280 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16281 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16282 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16283 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16284 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16287 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16288 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16289 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16291 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16292 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16293 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16294 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16295 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16298 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16299 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16300 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16302 // return VSELECT(r, r+r, a);
16303 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16304 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16308 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16309 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16310 // solution better.
16311 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16312 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16314 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16315 R = DAG.getNode(ExtOpc, dl, NewVT, R);
16316 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16317 return DAG.getNode(ISD::TRUNCATE, dl, VT,
16318 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16321 // Decompose 256-bit shifts into smaller 128-bit shifts.
16322 if (VT.is256BitVector()) {
16323 unsigned NumElems = VT.getVectorNumElements();
16324 MVT EltVT = VT.getVectorElementType();
16325 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16327 // Extract the two vectors
16328 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16329 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16331 // Recreate the shift amount vectors
16332 SDValue Amt1, Amt2;
16333 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16334 // Constant shift amount
16335 SmallVector<SDValue, 4> Amt1Csts;
16336 SmallVector<SDValue, 4> Amt2Csts;
16337 for (unsigned i = 0; i != NumElems/2; ++i)
16338 Amt1Csts.push_back(Amt->getOperand(i));
16339 for (unsigned i = NumElems/2; i != NumElems; ++i)
16340 Amt2Csts.push_back(Amt->getOperand(i));
16342 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16343 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16345 // Variable shift amount
16346 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16347 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16350 // Issue new vector shifts for the smaller types
16351 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16352 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16354 // Concatenate the result back
16355 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16361 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16362 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16363 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16364 // looks for this combo and may remove the "setcc" instruction if the "setcc"
16365 // has only one use.
16366 SDNode *N = Op.getNode();
16367 SDValue LHS = N->getOperand(0);
16368 SDValue RHS = N->getOperand(1);
16369 unsigned BaseOp = 0;
16372 switch (Op.getOpcode()) {
16373 default: llvm_unreachable("Unknown ovf instruction!");
16375 // A subtract of one will be selected as a INC. Note that INC doesn't
16376 // set CF, so we can't do this for UADDO.
16377 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16379 BaseOp = X86ISD::INC;
16380 Cond = X86::COND_O;
16383 BaseOp = X86ISD::ADD;
16384 Cond = X86::COND_O;
16387 BaseOp = X86ISD::ADD;
16388 Cond = X86::COND_B;
16391 // A subtract of one will be selected as a DEC. Note that DEC doesn't
16392 // set CF, so we can't do this for USUBO.
16393 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16395 BaseOp = X86ISD::DEC;
16396 Cond = X86::COND_O;
16399 BaseOp = X86ISD::SUB;
16400 Cond = X86::COND_O;
16403 BaseOp = X86ISD::SUB;
16404 Cond = X86::COND_B;
16407 BaseOp = X86ISD::SMUL;
16408 Cond = X86::COND_O;
16410 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16411 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16413 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16416 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16417 DAG.getConstant(X86::COND_O, MVT::i32),
16418 SDValue(Sum.getNode(), 2));
16420 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16424 // Also sets EFLAGS.
16425 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16426 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16429 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16430 DAG.getConstant(Cond, MVT::i32),
16431 SDValue(Sum.getNode(), 1));
16433 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16436 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16437 SelectionDAG &DAG) const {
16439 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16440 MVT VT = Op.getSimpleValueType();
16442 if (!Subtarget->hasSSE2() || !VT.isVector())
16445 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16446 ExtraVT.getScalarType().getSizeInBits();
16448 switch (VT.SimpleTy) {
16449 default: return SDValue();
16452 if (!Subtarget->hasFp256())
16454 if (!Subtarget->hasInt256()) {
16455 // needs to be split
16456 unsigned NumElems = VT.getVectorNumElements();
16458 // Extract the LHS vectors
16459 SDValue LHS = Op.getOperand(0);
16460 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16461 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16463 MVT EltVT = VT.getVectorElementType();
16464 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16466 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16467 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16468 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16470 SDValue Extra = DAG.getValueType(ExtraVT);
16472 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16473 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16475 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16480 SDValue Op0 = Op.getOperand(0);
16481 SDValue Op00 = Op0.getOperand(0);
16483 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16484 if (Op0.getOpcode() == ISD::BITCAST &&
16485 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16486 // (sext (vzext x)) -> (vsext x)
16487 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16488 if (Tmp1.getNode()) {
16489 EVT ExtraEltVT = ExtraVT.getVectorElementType();
16490 // This folding is only valid when the in-reg type is a vector of i8,
16492 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16493 ExtraEltVT == MVT::i32) {
16494 SDValue Tmp1Op0 = Tmp1.getOperand(0);
16495 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16496 "This optimization is invalid without a VZEXT.");
16497 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16503 // If the above didn't work, then just use Shift-Left + Shift-Right.
16504 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16506 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16512 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16513 SelectionDAG &DAG) {
16515 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16516 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16517 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16518 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16520 // The only fence that needs an instruction is a sequentially-consistent
16521 // cross-thread fence.
16522 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16523 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16524 // no-sse2). There isn't any reason to disable it if the target processor
16526 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16527 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16529 SDValue Chain = Op.getOperand(0);
16530 SDValue Zero = DAG.getConstant(0, MVT::i32);
16532 DAG.getRegister(X86::ESP, MVT::i32), // Base
16533 DAG.getTargetConstant(1, MVT::i8), // Scale
16534 DAG.getRegister(0, MVT::i32), // Index
16535 DAG.getTargetConstant(0, MVT::i32), // Disp
16536 DAG.getRegister(0, MVT::i32), // Segment.
16540 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16541 return SDValue(Res, 0);
16544 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16545 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16548 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16549 SelectionDAG &DAG) {
16550 MVT T = Op.getSimpleValueType();
16554 switch(T.SimpleTy) {
16555 default: llvm_unreachable("Invalid value type!");
16556 case MVT::i8: Reg = X86::AL; size = 1; break;
16557 case MVT::i16: Reg = X86::AX; size = 2; break;
16558 case MVT::i32: Reg = X86::EAX; size = 4; break;
16560 assert(Subtarget->is64Bit() && "Node not type legal!");
16561 Reg = X86::RAX; size = 8;
16564 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16565 Op.getOperand(2), SDValue());
16566 SDValue Ops[] = { cpIn.getValue(0),
16569 DAG.getTargetConstant(size, MVT::i8),
16570 cpIn.getValue(1) };
16571 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16572 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16573 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16577 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16578 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16579 MVT::i32, cpOut.getValue(2));
16580 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16581 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16583 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16584 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16585 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16589 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16590 SelectionDAG &DAG) {
16591 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16592 MVT DstVT = Op.getSimpleValueType();
16594 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16595 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16596 if (DstVT != MVT::f64)
16597 // This conversion needs to be expanded.
16600 SDValue InVec = Op->getOperand(0);
16602 unsigned NumElts = SrcVT.getVectorNumElements();
16603 EVT SVT = SrcVT.getVectorElementType();
16605 // Widen the vector in input in the case of MVT::v2i32.
16606 // Example: from MVT::v2i32 to MVT::v4i32.
16607 SmallVector<SDValue, 16> Elts;
16608 for (unsigned i = 0, e = NumElts; i != e; ++i)
16609 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16610 DAG.getIntPtrConstant(i)));
16612 // Explicitly mark the extra elements as Undef.
16613 SDValue Undef = DAG.getUNDEF(SVT);
16614 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16615 Elts.push_back(Undef);
16617 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16618 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16619 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16620 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16621 DAG.getIntPtrConstant(0));
16624 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16625 Subtarget->hasMMX() && "Unexpected custom BITCAST");
16626 assert((DstVT == MVT::i64 ||
16627 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16628 "Unexpected custom BITCAST");
16629 // i64 <=> MMX conversions are Legal.
16630 if (SrcVT==MVT::i64 && DstVT.isVector())
16632 if (DstVT==MVT::i64 && SrcVT.isVector())
16634 // MMX <=> MMX conversions are Legal.
16635 if (SrcVT.isVector() && DstVT.isVector())
16637 // All other conversions need to be expanded.
16641 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16642 SDNode *Node = Op.getNode();
16644 EVT T = Node->getValueType(0);
16645 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16646 DAG.getConstant(0, T), Node->getOperand(2));
16647 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16648 cast<AtomicSDNode>(Node)->getMemoryVT(),
16649 Node->getOperand(0),
16650 Node->getOperand(1), negOp,
16651 cast<AtomicSDNode>(Node)->getMemOperand(),
16652 cast<AtomicSDNode>(Node)->getOrdering(),
16653 cast<AtomicSDNode>(Node)->getSynchScope());
16656 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16657 SDNode *Node = Op.getNode();
16659 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16661 // Convert seq_cst store -> xchg
16662 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16663 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16664 // (The only way to get a 16-byte store is cmpxchg16b)
16665 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16666 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16667 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16668 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16669 cast<AtomicSDNode>(Node)->getMemoryVT(),
16670 Node->getOperand(0),
16671 Node->getOperand(1), Node->getOperand(2),
16672 cast<AtomicSDNode>(Node)->getMemOperand(),
16673 cast<AtomicSDNode>(Node)->getOrdering(),
16674 cast<AtomicSDNode>(Node)->getSynchScope());
16675 return Swap.getValue(1);
16677 // Other atomic stores have a simple pattern.
16681 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16682 EVT VT = Op.getNode()->getSimpleValueType(0);
16684 // Let legalize expand this if it isn't a legal type yet.
16685 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16688 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16691 bool ExtraOp = false;
16692 switch (Op.getOpcode()) {
16693 default: llvm_unreachable("Invalid code");
16694 case ISD::ADDC: Opc = X86ISD::ADD; break;
16695 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16696 case ISD::SUBC: Opc = X86ISD::SUB; break;
16697 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16701 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16703 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16704 Op.getOperand(1), Op.getOperand(2));
16707 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16708 SelectionDAG &DAG) {
16709 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16711 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16712 // which returns the values as { float, float } (in XMM0) or
16713 // { double, double } (which is returned in XMM0, XMM1).
16715 SDValue Arg = Op.getOperand(0);
16716 EVT ArgVT = Arg.getValueType();
16717 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16719 TargetLowering::ArgListTy Args;
16720 TargetLowering::ArgListEntry Entry;
16724 Entry.isSExt = false;
16725 Entry.isZExt = false;
16726 Args.push_back(Entry);
16728 bool isF64 = ArgVT == MVT::f64;
16729 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16730 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16731 // the results are returned via SRet in memory.
16732 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16733 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16734 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16736 Type *RetTy = isF64
16737 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16738 : (Type*)VectorType::get(ArgTy, 4);
16740 TargetLowering::CallLoweringInfo CLI(DAG);
16741 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16742 .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16744 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16747 // Returned in xmm0 and xmm1.
16748 return CallResult.first;
16750 // Returned in bits 0:31 and 32:64 xmm0.
16751 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16752 CallResult.first, DAG.getIntPtrConstant(0));
16753 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16754 CallResult.first, DAG.getIntPtrConstant(1));
16755 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16756 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16759 /// LowerOperation - Provide custom lowering hooks for some operations.
16761 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16762 switch (Op.getOpcode()) {
16763 default: llvm_unreachable("Should not custom lower this!");
16764 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
16765 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16766 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16767 return LowerCMP_SWAP(Op, Subtarget, DAG);
16768 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16769 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16770 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16771 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16772 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
16773 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16774 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16775 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16776 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16777 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16778 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16779 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16780 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16781 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16782 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16783 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16784 case ISD::SHL_PARTS:
16785 case ISD::SRA_PARTS:
16786 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16787 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16788 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16789 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16790 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16791 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16792 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16793 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16794 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16795 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16796 case ISD::LOAD: return LowerExtendedLoad(Op, Subtarget, DAG);
16797 case ISD::FABS: return LowerFABS(Op, DAG);
16798 case ISD::FNEG: return LowerFNEG(Op, DAG);
16799 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16800 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16801 case ISD::SETCC: return LowerSETCC(Op, DAG);
16802 case ISD::SELECT: return LowerSELECT(Op, DAG);
16803 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16804 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16805 case ISD::VASTART: return LowerVASTART(Op, DAG);
16806 case ISD::VAARG: return LowerVAARG(Op, DAG);
16807 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16808 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16809 case ISD::INTRINSIC_VOID:
16810 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16811 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16812 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16813 case ISD::FRAME_TO_ARGS_OFFSET:
16814 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16815 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16816 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16817 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16818 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16819 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16820 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16821 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16822 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16823 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16824 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16825 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16826 case ISD::UMUL_LOHI:
16827 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16830 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16836 case ISD::UMULO: return LowerXALUO(Op, DAG);
16837 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16838 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16842 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16843 case ISD::ADD: return LowerADD(Op, DAG);
16844 case ISD::SUB: return LowerSUB(Op, DAG);
16845 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16849 static void ReplaceATOMIC_LOAD(SDNode *Node,
16850 SmallVectorImpl<SDValue> &Results,
16851 SelectionDAG &DAG) {
16853 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16855 // Convert wide load -> cmpxchg8b/cmpxchg16b
16856 // FIXME: On 32-bit, load -> fild or movq would be more efficient
16857 // (The only way to get a 16-byte load is cmpxchg16b)
16858 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16859 SDValue Zero = DAG.getConstant(0, VT);
16860 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16862 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16863 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16864 cast<AtomicSDNode>(Node)->getMemOperand(),
16865 cast<AtomicSDNode>(Node)->getOrdering(),
16866 cast<AtomicSDNode>(Node)->getOrdering(),
16867 cast<AtomicSDNode>(Node)->getSynchScope());
16868 Results.push_back(Swap.getValue(0));
16869 Results.push_back(Swap.getValue(2));
16872 /// ReplaceNodeResults - Replace a node with an illegal result type
16873 /// with a new node built out of custom code.
16874 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16875 SmallVectorImpl<SDValue>&Results,
16876 SelectionDAG &DAG) const {
16878 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16879 switch (N->getOpcode()) {
16881 llvm_unreachable("Do not know how to custom type legalize this operation!");
16882 case ISD::SIGN_EXTEND_INREG:
16887 // We don't want to expand or promote these.
16894 case ISD::UDIVREM: {
16895 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16896 Results.push_back(V);
16899 case ISD::FP_TO_SINT:
16900 case ISD::FP_TO_UINT: {
16901 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16903 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16906 std::pair<SDValue,SDValue> Vals =
16907 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16908 SDValue FIST = Vals.first, StackSlot = Vals.second;
16909 if (FIST.getNode()) {
16910 EVT VT = N->getValueType(0);
16911 // Return a load from the stack slot.
16912 if (StackSlot.getNode())
16913 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16914 MachinePointerInfo(),
16915 false, false, false, 0));
16917 Results.push_back(FIST);
16921 case ISD::UINT_TO_FP: {
16922 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16923 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16924 N->getValueType(0) != MVT::v2f32)
16926 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16928 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16930 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16931 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16932 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16933 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16934 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16935 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16938 case ISD::FP_ROUND: {
16939 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16941 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16942 Results.push_back(V);
16945 case ISD::INTRINSIC_W_CHAIN: {
16946 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16948 default : llvm_unreachable("Do not know how to custom type "
16949 "legalize this intrinsic operation!");
16950 case Intrinsic::x86_rdtsc:
16951 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16953 case Intrinsic::x86_rdtscp:
16954 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16956 case Intrinsic::x86_rdpmc:
16957 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16960 case ISD::READCYCLECOUNTER: {
16961 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16964 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16965 EVT T = N->getValueType(0);
16966 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16967 bool Regs64bit = T == MVT::i128;
16968 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16969 SDValue cpInL, cpInH;
16970 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16971 DAG.getConstant(0, HalfT));
16972 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16973 DAG.getConstant(1, HalfT));
16974 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16975 Regs64bit ? X86::RAX : X86::EAX,
16977 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16978 Regs64bit ? X86::RDX : X86::EDX,
16979 cpInH, cpInL.getValue(1));
16980 SDValue swapInL, swapInH;
16981 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16982 DAG.getConstant(0, HalfT));
16983 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16984 DAG.getConstant(1, HalfT));
16985 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16986 Regs64bit ? X86::RBX : X86::EBX,
16987 swapInL, cpInH.getValue(1));
16988 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16989 Regs64bit ? X86::RCX : X86::ECX,
16990 swapInH, swapInL.getValue(1));
16991 SDValue Ops[] = { swapInH.getValue(0),
16993 swapInH.getValue(1) };
16994 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16995 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16996 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16997 X86ISD::LCMPXCHG8_DAG;
16998 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16999 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17000 Regs64bit ? X86::RAX : X86::EAX,
17001 HalfT, Result.getValue(1));
17002 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17003 Regs64bit ? X86::RDX : X86::EDX,
17004 HalfT, cpOutL.getValue(2));
17005 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17007 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17008 MVT::i32, cpOutH.getValue(2));
17010 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17011 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17012 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17014 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17015 Results.push_back(Success);
17016 Results.push_back(EFLAGS.getValue(1));
17019 case ISD::ATOMIC_SWAP:
17020 case ISD::ATOMIC_LOAD_ADD:
17021 case ISD::ATOMIC_LOAD_SUB:
17022 case ISD::ATOMIC_LOAD_AND:
17023 case ISD::ATOMIC_LOAD_OR:
17024 case ISD::ATOMIC_LOAD_XOR:
17025 case ISD::ATOMIC_LOAD_NAND:
17026 case ISD::ATOMIC_LOAD_MIN:
17027 case ISD::ATOMIC_LOAD_MAX:
17028 case ISD::ATOMIC_LOAD_UMIN:
17029 case ISD::ATOMIC_LOAD_UMAX:
17030 // Delegate to generic TypeLegalization. Situations we can really handle
17031 // should have already been dealt with by X86AtomicExpandPass.cpp.
17033 case ISD::ATOMIC_LOAD: {
17034 ReplaceATOMIC_LOAD(N, Results, DAG);
17037 case ISD::BITCAST: {
17038 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17039 EVT DstVT = N->getValueType(0);
17040 EVT SrcVT = N->getOperand(0)->getValueType(0);
17042 if (SrcVT != MVT::f64 ||
17043 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17046 unsigned NumElts = DstVT.getVectorNumElements();
17047 EVT SVT = DstVT.getVectorElementType();
17048 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17049 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17050 MVT::v2f64, N->getOperand(0));
17051 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17053 if (ExperimentalVectorWideningLegalization) {
17054 // If we are legalizing vectors by widening, we already have the desired
17055 // legal vector type, just return it.
17056 Results.push_back(ToVecInt);
17060 SmallVector<SDValue, 8> Elts;
17061 for (unsigned i = 0, e = NumElts; i != e; ++i)
17062 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17063 ToVecInt, DAG.getIntPtrConstant(i)));
17065 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17070 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17072 default: return nullptr;
17073 case X86ISD::BSF: return "X86ISD::BSF";
17074 case X86ISD::BSR: return "X86ISD::BSR";
17075 case X86ISD::SHLD: return "X86ISD::SHLD";
17076 case X86ISD::SHRD: return "X86ISD::SHRD";
17077 case X86ISD::FAND: return "X86ISD::FAND";
17078 case X86ISD::FANDN: return "X86ISD::FANDN";
17079 case X86ISD::FOR: return "X86ISD::FOR";
17080 case X86ISD::FXOR: return "X86ISD::FXOR";
17081 case X86ISD::FSRL: return "X86ISD::FSRL";
17082 case X86ISD::FILD: return "X86ISD::FILD";
17083 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
17084 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17085 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17086 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17087 case X86ISD::FLD: return "X86ISD::FLD";
17088 case X86ISD::FST: return "X86ISD::FST";
17089 case X86ISD::CALL: return "X86ISD::CALL";
17090 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
17091 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
17092 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
17093 case X86ISD::BT: return "X86ISD::BT";
17094 case X86ISD::CMP: return "X86ISD::CMP";
17095 case X86ISD::COMI: return "X86ISD::COMI";
17096 case X86ISD::UCOMI: return "X86ISD::UCOMI";
17097 case X86ISD::CMPM: return "X86ISD::CMPM";
17098 case X86ISD::CMPMU: return "X86ISD::CMPMU";
17099 case X86ISD::SETCC: return "X86ISD::SETCC";
17100 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
17101 case X86ISD::FSETCC: return "X86ISD::FSETCC";
17102 case X86ISD::CMOV: return "X86ISD::CMOV";
17103 case X86ISD::BRCOND: return "X86ISD::BRCOND";
17104 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
17105 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
17106 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
17107 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
17108 case X86ISD::Wrapper: return "X86ISD::Wrapper";
17109 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
17110 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
17111 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
17112 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
17113 case X86ISD::PINSRB: return "X86ISD::PINSRB";
17114 case X86ISD::PINSRW: return "X86ISD::PINSRW";
17115 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
17116 case X86ISD::ANDNP: return "X86ISD::ANDNP";
17117 case X86ISD::PSIGN: return "X86ISD::PSIGN";
17118 case X86ISD::BLENDV: return "X86ISD::BLENDV";
17119 case X86ISD::BLENDI: return "X86ISD::BLENDI";
17120 case X86ISD::SUBUS: return "X86ISD::SUBUS";
17121 case X86ISD::HADD: return "X86ISD::HADD";
17122 case X86ISD::HSUB: return "X86ISD::HSUB";
17123 case X86ISD::FHADD: return "X86ISD::FHADD";
17124 case X86ISD::FHSUB: return "X86ISD::FHSUB";
17125 case X86ISD::UMAX: return "X86ISD::UMAX";
17126 case X86ISD::UMIN: return "X86ISD::UMIN";
17127 case X86ISD::SMAX: return "X86ISD::SMAX";
17128 case X86ISD::SMIN: return "X86ISD::SMIN";
17129 case X86ISD::FMAX: return "X86ISD::FMAX";
17130 case X86ISD::FMIN: return "X86ISD::FMIN";
17131 case X86ISD::FMAXC: return "X86ISD::FMAXC";
17132 case X86ISD::FMINC: return "X86ISD::FMINC";
17133 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
17134 case X86ISD::FRCP: return "X86ISD::FRCP";
17135 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
17136 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
17137 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
17138 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
17139 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
17140 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
17141 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
17142 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
17143 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
17144 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
17145 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
17146 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
17147 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
17148 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
17149 case X86ISD::VZEXT: return "X86ISD::VZEXT";
17150 case X86ISD::VSEXT: return "X86ISD::VSEXT";
17151 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
17152 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
17153 case X86ISD::VINSERT: return "X86ISD::VINSERT";
17154 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
17155 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
17156 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
17157 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
17158 case X86ISD::VSHL: return "X86ISD::VSHL";
17159 case X86ISD::VSRL: return "X86ISD::VSRL";
17160 case X86ISD::VSRA: return "X86ISD::VSRA";
17161 case X86ISD::VSHLI: return "X86ISD::VSHLI";
17162 case X86ISD::VSRLI: return "X86ISD::VSRLI";
17163 case X86ISD::VSRAI: return "X86ISD::VSRAI";
17164 case X86ISD::CMPP: return "X86ISD::CMPP";
17165 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
17166 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
17167 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
17168 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
17169 case X86ISD::ADD: return "X86ISD::ADD";
17170 case X86ISD::SUB: return "X86ISD::SUB";
17171 case X86ISD::ADC: return "X86ISD::ADC";
17172 case X86ISD::SBB: return "X86ISD::SBB";
17173 case X86ISD::SMUL: return "X86ISD::SMUL";
17174 case X86ISD::UMUL: return "X86ISD::UMUL";
17175 case X86ISD::INC: return "X86ISD::INC";
17176 case X86ISD::DEC: return "X86ISD::DEC";
17177 case X86ISD::OR: return "X86ISD::OR";
17178 case X86ISD::XOR: return "X86ISD::XOR";
17179 case X86ISD::AND: return "X86ISD::AND";
17180 case X86ISD::BEXTR: return "X86ISD::BEXTR";
17181 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
17182 case X86ISD::PTEST: return "X86ISD::PTEST";
17183 case X86ISD::TESTP: return "X86ISD::TESTP";
17184 case X86ISD::TESTM: return "X86ISD::TESTM";
17185 case X86ISD::TESTNM: return "X86ISD::TESTNM";
17186 case X86ISD::KORTEST: return "X86ISD::KORTEST";
17187 case X86ISD::PACKSS: return "X86ISD::PACKSS";
17188 case X86ISD::PACKUS: return "X86ISD::PACKUS";
17189 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
17190 case X86ISD::VALIGN: return "X86ISD::VALIGN";
17191 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
17192 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
17193 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
17194 case X86ISD::SHUFP: return "X86ISD::SHUFP";
17195 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
17196 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
17197 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
17198 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
17199 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
17200 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
17201 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
17202 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
17203 case X86ISD::MOVSD: return "X86ISD::MOVSD";
17204 case X86ISD::MOVSS: return "X86ISD::MOVSS";
17205 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
17206 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
17207 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
17208 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
17209 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
17210 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
17211 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
17212 case X86ISD::VPERMV: return "X86ISD::VPERMV";
17213 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
17214 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
17215 case X86ISD::VPERMI: return "X86ISD::VPERMI";
17216 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
17217 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
17218 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17219 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
17220 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
17221 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
17222 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
17223 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
17224 case X86ISD::SAHF: return "X86ISD::SAHF";
17225 case X86ISD::RDRAND: return "X86ISD::RDRAND";
17226 case X86ISD::RDSEED: return "X86ISD::RDSEED";
17227 case X86ISD::FMADD: return "X86ISD::FMADD";
17228 case X86ISD::FMSUB: return "X86ISD::FMSUB";
17229 case X86ISD::FNMADD: return "X86ISD::FNMADD";
17230 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
17231 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
17232 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
17233 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
17234 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
17235 case X86ISD::XTEST: return "X86ISD::XTEST";
17239 // isLegalAddressingMode - Return true if the addressing mode represented
17240 // by AM is legal for this target, for a load/store of the specified type.
17241 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17243 // X86 supports extremely general addressing modes.
17244 CodeModel::Model M = getTargetMachine().getCodeModel();
17245 Reloc::Model R = getTargetMachine().getRelocationModel();
17247 // X86 allows a sign-extended 32-bit immediate field as a displacement.
17248 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17253 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17255 // If a reference to this global requires an extra load, we can't fold it.
17256 if (isGlobalStubReference(GVFlags))
17259 // If BaseGV requires a register for the PIC base, we cannot also have a
17260 // BaseReg specified.
17261 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17264 // If lower 4G is not available, then we must use rip-relative addressing.
17265 if ((M != CodeModel::Small || R != Reloc::Static) &&
17266 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17270 switch (AM.Scale) {
17276 // These scales always work.
17281 // These scales are formed with basereg+scalereg. Only accept if there is
17286 default: // Other stuff never works.
17293 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17294 unsigned Bits = Ty->getScalarSizeInBits();
17296 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17297 // particularly cheaper than those without.
17301 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17302 // variable shifts just as cheap as scalar ones.
17303 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17306 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17307 // fully general vector.
17311 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17312 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17314 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17315 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17316 return NumBits1 > NumBits2;
17319 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17320 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17323 if (!isTypeLegal(EVT::getEVT(Ty1)))
17326 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17328 // Assuming the caller doesn't have a zeroext or signext return parameter,
17329 // truncation all the way down to i1 is valid.
17333 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17334 return isInt<32>(Imm);
17337 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17338 // Can also use sub to handle negated immediates.
17339 return isInt<32>(Imm);
17342 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17343 if (!VT1.isInteger() || !VT2.isInteger())
17345 unsigned NumBits1 = VT1.getSizeInBits();
17346 unsigned NumBits2 = VT2.getSizeInBits();
17347 return NumBits1 > NumBits2;
17350 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17351 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17352 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17355 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17356 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17357 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17360 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17361 EVT VT1 = Val.getValueType();
17362 if (isZExtFree(VT1, VT2))
17365 if (Val.getOpcode() != ISD::LOAD)
17368 if (!VT1.isSimple() || !VT1.isInteger() ||
17369 !VT2.isSimple() || !VT2.isInteger())
17372 switch (VT1.getSimpleVT().SimpleTy) {
17377 // X86 has 8, 16, and 32-bit zero-extending loads.
17385 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17386 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17389 VT = VT.getScalarType();
17391 if (!VT.isSimple())
17394 switch (VT.getSimpleVT().SimpleTy) {
17405 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17406 // i16 instructions are longer (0x66 prefix) and potentially slower.
17407 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17410 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17411 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17412 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17413 /// are assumed to be legal.
17415 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17417 if (!VT.isSimple())
17420 MVT SVT = VT.getSimpleVT();
17422 // Very little shuffling can be done for 64-bit vectors right now.
17423 if (VT.getSizeInBits() == 64)
17426 // If this is a single-input shuffle with no 128 bit lane crossings we can
17427 // lower it into pshufb.
17428 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17429 (SVT.is256BitVector() && Subtarget->hasInt256())) {
17430 bool isLegal = true;
17431 for (unsigned I = 0, E = M.size(); I != E; ++I) {
17432 if (M[I] >= (int)SVT.getVectorNumElements() ||
17433 ShuffleCrosses128bitLane(SVT, I, M[I])) {
17442 // FIXME: blends, shifts.
17443 return (SVT.getVectorNumElements() == 2 ||
17444 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17445 isMOVLMask(M, SVT) ||
17446 isMOVHLPSMask(M, SVT) ||
17447 isSHUFPMask(M, SVT) ||
17448 isPSHUFDMask(M, SVT) ||
17449 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17450 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17451 isPALIGNRMask(M, SVT, Subtarget) ||
17452 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17453 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17454 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17455 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17456 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17460 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17462 if (!VT.isSimple())
17465 MVT SVT = VT.getSimpleVT();
17466 unsigned NumElts = SVT.getVectorNumElements();
17467 // FIXME: This collection of masks seems suspect.
17470 if (NumElts == 4 && SVT.is128BitVector()) {
17471 return (isMOVLMask(Mask, SVT) ||
17472 isCommutedMOVLMask(Mask, SVT, true) ||
17473 isSHUFPMask(Mask, SVT) ||
17474 isSHUFPMask(Mask, SVT, /* Commuted */ true));
17479 //===----------------------------------------------------------------------===//
17480 // X86 Scheduler Hooks
17481 //===----------------------------------------------------------------------===//
17483 /// Utility function to emit xbegin specifying the start of an RTM region.
17484 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17485 const TargetInstrInfo *TII) {
17486 DebugLoc DL = MI->getDebugLoc();
17488 const BasicBlock *BB = MBB->getBasicBlock();
17489 MachineFunction::iterator I = MBB;
17492 // For the v = xbegin(), we generate
17503 MachineBasicBlock *thisMBB = MBB;
17504 MachineFunction *MF = MBB->getParent();
17505 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17506 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17507 MF->insert(I, mainMBB);
17508 MF->insert(I, sinkMBB);
17510 // Transfer the remainder of BB and its successor edges to sinkMBB.
17511 sinkMBB->splice(sinkMBB->begin(), MBB,
17512 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17513 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17517 // # fallthrough to mainMBB
17518 // # abortion to sinkMBB
17519 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17520 thisMBB->addSuccessor(mainMBB);
17521 thisMBB->addSuccessor(sinkMBB);
17525 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17526 mainMBB->addSuccessor(sinkMBB);
17529 // EAX is live into the sinkMBB
17530 sinkMBB->addLiveIn(X86::EAX);
17531 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17532 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17535 MI->eraseFromParent();
17539 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17540 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17541 // in the .td file.
17542 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17543 const TargetInstrInfo *TII) {
17545 switch (MI->getOpcode()) {
17546 default: llvm_unreachable("illegal opcode!");
17547 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17548 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17549 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17550 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17551 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17552 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17553 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17554 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17557 DebugLoc dl = MI->getDebugLoc();
17558 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17560 unsigned NumArgs = MI->getNumOperands();
17561 for (unsigned i = 1; i < NumArgs; ++i) {
17562 MachineOperand &Op = MI->getOperand(i);
17563 if (!(Op.isReg() && Op.isImplicit()))
17564 MIB.addOperand(Op);
17566 if (MI->hasOneMemOperand())
17567 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17569 BuildMI(*BB, MI, dl,
17570 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17571 .addReg(X86::XMM0);
17573 MI->eraseFromParent();
17577 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17578 // defs in an instruction pattern
17579 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17580 const TargetInstrInfo *TII) {
17582 switch (MI->getOpcode()) {
17583 default: llvm_unreachable("illegal opcode!");
17584 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17585 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17586 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17587 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17588 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17589 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17590 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17591 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17594 DebugLoc dl = MI->getDebugLoc();
17595 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17597 unsigned NumArgs = MI->getNumOperands(); // remove the results
17598 for (unsigned i = 1; i < NumArgs; ++i) {
17599 MachineOperand &Op = MI->getOperand(i);
17600 if (!(Op.isReg() && Op.isImplicit()))
17601 MIB.addOperand(Op);
17603 if (MI->hasOneMemOperand())
17604 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17606 BuildMI(*BB, MI, dl,
17607 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17610 MI->eraseFromParent();
17614 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17615 const TargetInstrInfo *TII,
17616 const X86Subtarget* Subtarget) {
17617 DebugLoc dl = MI->getDebugLoc();
17619 // Address into RAX/EAX, other two args into ECX, EDX.
17620 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17621 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17622 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17623 for (int i = 0; i < X86::AddrNumOperands; ++i)
17624 MIB.addOperand(MI->getOperand(i));
17626 unsigned ValOps = X86::AddrNumOperands;
17627 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17628 .addReg(MI->getOperand(ValOps).getReg());
17629 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17630 .addReg(MI->getOperand(ValOps+1).getReg());
17632 // The instruction doesn't actually take any operands though.
17633 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17635 MI->eraseFromParent(); // The pseudo is gone now.
17639 MachineBasicBlock *
17640 X86TargetLowering::EmitVAARG64WithCustomInserter(
17642 MachineBasicBlock *MBB) const {
17643 // Emit va_arg instruction on X86-64.
17645 // Operands to this pseudo-instruction:
17646 // 0 ) Output : destination address (reg)
17647 // 1-5) Input : va_list address (addr, i64mem)
17648 // 6 ) ArgSize : Size (in bytes) of vararg type
17649 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17650 // 8 ) Align : Alignment of type
17651 // 9 ) EFLAGS (implicit-def)
17653 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17654 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17656 unsigned DestReg = MI->getOperand(0).getReg();
17657 MachineOperand &Base = MI->getOperand(1);
17658 MachineOperand &Scale = MI->getOperand(2);
17659 MachineOperand &Index = MI->getOperand(3);
17660 MachineOperand &Disp = MI->getOperand(4);
17661 MachineOperand &Segment = MI->getOperand(5);
17662 unsigned ArgSize = MI->getOperand(6).getImm();
17663 unsigned ArgMode = MI->getOperand(7).getImm();
17664 unsigned Align = MI->getOperand(8).getImm();
17666 // Memory Reference
17667 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17668 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17669 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17671 // Machine Information
17672 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17673 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17674 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17675 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17676 DebugLoc DL = MI->getDebugLoc();
17678 // struct va_list {
17681 // i64 overflow_area (address)
17682 // i64 reg_save_area (address)
17684 // sizeof(va_list) = 24
17685 // alignment(va_list) = 8
17687 unsigned TotalNumIntRegs = 6;
17688 unsigned TotalNumXMMRegs = 8;
17689 bool UseGPOffset = (ArgMode == 1);
17690 bool UseFPOffset = (ArgMode == 2);
17691 unsigned MaxOffset = TotalNumIntRegs * 8 +
17692 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17694 /* Align ArgSize to a multiple of 8 */
17695 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17696 bool NeedsAlign = (Align > 8);
17698 MachineBasicBlock *thisMBB = MBB;
17699 MachineBasicBlock *overflowMBB;
17700 MachineBasicBlock *offsetMBB;
17701 MachineBasicBlock *endMBB;
17703 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17704 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17705 unsigned OffsetReg = 0;
17707 if (!UseGPOffset && !UseFPOffset) {
17708 // If we only pull from the overflow region, we don't create a branch.
17709 // We don't need to alter control flow.
17710 OffsetDestReg = 0; // unused
17711 OverflowDestReg = DestReg;
17713 offsetMBB = nullptr;
17714 overflowMBB = thisMBB;
17717 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17718 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17719 // If not, pull from overflow_area. (branch to overflowMBB)
17724 // offsetMBB overflowMBB
17729 // Registers for the PHI in endMBB
17730 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17731 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17733 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17734 MachineFunction *MF = MBB->getParent();
17735 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17736 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17737 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17739 MachineFunction::iterator MBBIter = MBB;
17742 // Insert the new basic blocks
17743 MF->insert(MBBIter, offsetMBB);
17744 MF->insert(MBBIter, overflowMBB);
17745 MF->insert(MBBIter, endMBB);
17747 // Transfer the remainder of MBB and its successor edges to endMBB.
17748 endMBB->splice(endMBB->begin(), thisMBB,
17749 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17750 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17752 // Make offsetMBB and overflowMBB successors of thisMBB
17753 thisMBB->addSuccessor(offsetMBB);
17754 thisMBB->addSuccessor(overflowMBB);
17756 // endMBB is a successor of both offsetMBB and overflowMBB
17757 offsetMBB->addSuccessor(endMBB);
17758 overflowMBB->addSuccessor(endMBB);
17760 // Load the offset value into a register
17761 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17762 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17766 .addDisp(Disp, UseFPOffset ? 4 : 0)
17767 .addOperand(Segment)
17768 .setMemRefs(MMOBegin, MMOEnd);
17770 // Check if there is enough room left to pull this argument.
17771 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17773 .addImm(MaxOffset + 8 - ArgSizeA8);
17775 // Branch to "overflowMBB" if offset >= max
17776 // Fall through to "offsetMBB" otherwise
17777 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17778 .addMBB(overflowMBB);
17781 // In offsetMBB, emit code to use the reg_save_area.
17783 assert(OffsetReg != 0);
17785 // Read the reg_save_area address.
17786 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17787 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17792 .addOperand(Segment)
17793 .setMemRefs(MMOBegin, MMOEnd);
17795 // Zero-extend the offset
17796 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17797 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17800 .addImm(X86::sub_32bit);
17802 // Add the offset to the reg_save_area to get the final address.
17803 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17804 .addReg(OffsetReg64)
17805 .addReg(RegSaveReg);
17807 // Compute the offset for the next argument
17808 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17809 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17811 .addImm(UseFPOffset ? 16 : 8);
17813 // Store it back into the va_list.
17814 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17818 .addDisp(Disp, UseFPOffset ? 4 : 0)
17819 .addOperand(Segment)
17820 .addReg(NextOffsetReg)
17821 .setMemRefs(MMOBegin, MMOEnd);
17824 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17829 // Emit code to use overflow area
17832 // Load the overflow_area address into a register.
17833 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17834 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17839 .addOperand(Segment)
17840 .setMemRefs(MMOBegin, MMOEnd);
17842 // If we need to align it, do so. Otherwise, just copy the address
17843 // to OverflowDestReg.
17845 // Align the overflow address
17846 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17847 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17849 // aligned_addr = (addr + (align-1)) & ~(align-1)
17850 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17851 .addReg(OverflowAddrReg)
17854 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17856 .addImm(~(uint64_t)(Align-1));
17858 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17859 .addReg(OverflowAddrReg);
17862 // Compute the next overflow address after this argument.
17863 // (the overflow address should be kept 8-byte aligned)
17864 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17865 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17866 .addReg(OverflowDestReg)
17867 .addImm(ArgSizeA8);
17869 // Store the new overflow address.
17870 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17875 .addOperand(Segment)
17876 .addReg(NextAddrReg)
17877 .setMemRefs(MMOBegin, MMOEnd);
17879 // If we branched, emit the PHI to the front of endMBB.
17881 BuildMI(*endMBB, endMBB->begin(), DL,
17882 TII->get(X86::PHI), DestReg)
17883 .addReg(OffsetDestReg).addMBB(offsetMBB)
17884 .addReg(OverflowDestReg).addMBB(overflowMBB);
17887 // Erase the pseudo instruction
17888 MI->eraseFromParent();
17893 MachineBasicBlock *
17894 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17896 MachineBasicBlock *MBB) const {
17897 // Emit code to save XMM registers to the stack. The ABI says that the
17898 // number of registers to save is given in %al, so it's theoretically
17899 // possible to do an indirect jump trick to avoid saving all of them,
17900 // however this code takes a simpler approach and just executes all
17901 // of the stores if %al is non-zero. It's less code, and it's probably
17902 // easier on the hardware branch predictor, and stores aren't all that
17903 // expensive anyway.
17905 // Create the new basic blocks. One block contains all the XMM stores,
17906 // and one block is the final destination regardless of whether any
17907 // stores were performed.
17908 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17909 MachineFunction *F = MBB->getParent();
17910 MachineFunction::iterator MBBIter = MBB;
17912 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17913 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17914 F->insert(MBBIter, XMMSaveMBB);
17915 F->insert(MBBIter, EndMBB);
17917 // Transfer the remainder of MBB and its successor edges to EndMBB.
17918 EndMBB->splice(EndMBB->begin(), MBB,
17919 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17920 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17922 // The original block will now fall through to the XMM save block.
17923 MBB->addSuccessor(XMMSaveMBB);
17924 // The XMMSaveMBB will fall through to the end block.
17925 XMMSaveMBB->addSuccessor(EndMBB);
17927 // Now add the instructions.
17928 const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
17929 DebugLoc DL = MI->getDebugLoc();
17931 unsigned CountReg = MI->getOperand(0).getReg();
17932 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17933 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17935 if (!Subtarget->isTargetWin64()) {
17936 // If %al is 0, branch around the XMM save block.
17937 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17938 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17939 MBB->addSuccessor(EndMBB);
17942 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17943 // that was just emitted, but clearly shouldn't be "saved".
17944 assert((MI->getNumOperands() <= 3 ||
17945 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17946 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17947 && "Expected last argument to be EFLAGS");
17948 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17949 // In the XMM save block, save all the XMM argument registers.
17950 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17951 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17952 MachineMemOperand *MMO =
17953 F->getMachineMemOperand(
17954 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17955 MachineMemOperand::MOStore,
17956 /*Size=*/16, /*Align=*/16);
17957 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17958 .addFrameIndex(RegSaveFrameIndex)
17959 .addImm(/*Scale=*/1)
17960 .addReg(/*IndexReg=*/0)
17961 .addImm(/*Disp=*/Offset)
17962 .addReg(/*Segment=*/0)
17963 .addReg(MI->getOperand(i).getReg())
17964 .addMemOperand(MMO);
17967 MI->eraseFromParent(); // The pseudo instruction is gone now.
17972 // The EFLAGS operand of SelectItr might be missing a kill marker
17973 // because there were multiple uses of EFLAGS, and ISel didn't know
17974 // which to mark. Figure out whether SelectItr should have had a
17975 // kill marker, and set it if it should. Returns the correct kill
17977 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17978 MachineBasicBlock* BB,
17979 const TargetRegisterInfo* TRI) {
17980 // Scan forward through BB for a use/def of EFLAGS.
17981 MachineBasicBlock::iterator miI(std::next(SelectItr));
17982 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17983 const MachineInstr& mi = *miI;
17984 if (mi.readsRegister(X86::EFLAGS))
17986 if (mi.definesRegister(X86::EFLAGS))
17987 break; // Should have kill-flag - update below.
17990 // If we hit the end of the block, check whether EFLAGS is live into a
17992 if (miI == BB->end()) {
17993 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17994 sEnd = BB->succ_end();
17995 sItr != sEnd; ++sItr) {
17996 MachineBasicBlock* succ = *sItr;
17997 if (succ->isLiveIn(X86::EFLAGS))
18002 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18003 // out. SelectMI should have a kill flag on EFLAGS.
18004 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18008 MachineBasicBlock *
18009 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18010 MachineBasicBlock *BB) const {
18011 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18012 DebugLoc DL = MI->getDebugLoc();
18014 // To "insert" a SELECT_CC instruction, we actually have to insert the
18015 // diamond control-flow pattern. The incoming instruction knows the
18016 // destination vreg to set, the condition code register to branch on, the
18017 // true/false values to select between, and a branch opcode to use.
18018 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18019 MachineFunction::iterator It = BB;
18025 // cmpTY ccX, r1, r2
18027 // fallthrough --> copy0MBB
18028 MachineBasicBlock *thisMBB = BB;
18029 MachineFunction *F = BB->getParent();
18030 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18031 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18032 F->insert(It, copy0MBB);
18033 F->insert(It, sinkMBB);
18035 // If the EFLAGS register isn't dead in the terminator, then claim that it's
18036 // live into the sink and copy blocks.
18037 const TargetRegisterInfo *TRI =
18038 BB->getParent()->getSubtarget().getRegisterInfo();
18039 if (!MI->killsRegister(X86::EFLAGS) &&
18040 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18041 copy0MBB->addLiveIn(X86::EFLAGS);
18042 sinkMBB->addLiveIn(X86::EFLAGS);
18045 // Transfer the remainder of BB and its successor edges to sinkMBB.
18046 sinkMBB->splice(sinkMBB->begin(), BB,
18047 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18048 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18050 // Add the true and fallthrough blocks as its successors.
18051 BB->addSuccessor(copy0MBB);
18052 BB->addSuccessor(sinkMBB);
18054 // Create the conditional branch instruction.
18056 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18057 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18060 // %FalseValue = ...
18061 // # fallthrough to sinkMBB
18062 copy0MBB->addSuccessor(sinkMBB);
18065 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18067 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18068 TII->get(X86::PHI), MI->getOperand(0).getReg())
18069 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18070 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18072 MI->eraseFromParent(); // The pseudo instruction is gone now.
18076 MachineBasicBlock *
18077 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18078 bool Is64Bit) const {
18079 MachineFunction *MF = BB->getParent();
18080 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18081 DebugLoc DL = MI->getDebugLoc();
18082 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18084 assert(MF->shouldSplitStack());
18086 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18087 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18090 // ... [Till the alloca]
18091 // If stacklet is not large enough, jump to mallocMBB
18094 // Allocate by subtracting from RSP
18095 // Jump to continueMBB
18098 // Allocate by call to runtime
18102 // [rest of original BB]
18105 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18106 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18107 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18109 MachineRegisterInfo &MRI = MF->getRegInfo();
18110 const TargetRegisterClass *AddrRegClass =
18111 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18113 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18114 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18115 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18116 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18117 sizeVReg = MI->getOperand(1).getReg(),
18118 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18120 MachineFunction::iterator MBBIter = BB;
18123 MF->insert(MBBIter, bumpMBB);
18124 MF->insert(MBBIter, mallocMBB);
18125 MF->insert(MBBIter, continueMBB);
18127 continueMBB->splice(continueMBB->begin(), BB,
18128 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18129 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18131 // Add code to the main basic block to check if the stack limit has been hit,
18132 // and if so, jump to mallocMBB otherwise to bumpMBB.
18133 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18134 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18135 .addReg(tmpSPVReg).addReg(sizeVReg);
18136 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18137 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18138 .addReg(SPLimitVReg);
18139 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18141 // bumpMBB simply decreases the stack pointer, since we know the current
18142 // stacklet has enough space.
18143 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18144 .addReg(SPLimitVReg);
18145 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18146 .addReg(SPLimitVReg);
18147 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18149 // Calls into a routine in libgcc to allocate more space from the heap.
18150 const uint32_t *RegMask = MF->getTarget()
18151 .getSubtargetImpl()
18152 ->getRegisterInfo()
18153 ->getCallPreservedMask(CallingConv::C);
18155 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18157 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18158 .addExternalSymbol("__morestack_allocate_stack_space")
18159 .addRegMask(RegMask)
18160 .addReg(X86::RDI, RegState::Implicit)
18161 .addReg(X86::RAX, RegState::ImplicitDefine);
18163 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18165 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18166 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18167 .addExternalSymbol("__morestack_allocate_stack_space")
18168 .addRegMask(RegMask)
18169 .addReg(X86::EAX, RegState::ImplicitDefine);
18173 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18176 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18177 .addReg(Is64Bit ? X86::RAX : X86::EAX);
18178 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18180 // Set up the CFG correctly.
18181 BB->addSuccessor(bumpMBB);
18182 BB->addSuccessor(mallocMBB);
18183 mallocMBB->addSuccessor(continueMBB);
18184 bumpMBB->addSuccessor(continueMBB);
18186 // Take care of the PHI nodes.
18187 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18188 MI->getOperand(0).getReg())
18189 .addReg(mallocPtrVReg).addMBB(mallocMBB)
18190 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18192 // Delete the original pseudo instruction.
18193 MI->eraseFromParent();
18196 return continueMBB;
18199 MachineBasicBlock *
18200 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18201 MachineBasicBlock *BB) const {
18202 const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18203 DebugLoc DL = MI->getDebugLoc();
18205 assert(!Subtarget->isTargetMacho());
18207 // The lowering is pretty easy: we're just emitting the call to _alloca. The
18208 // non-trivial part is impdef of ESP.
18210 if (Subtarget->isTargetWin64()) {
18211 if (Subtarget->isTargetCygMing()) {
18212 // ___chkstk(Mingw64):
18213 // Clobbers R10, R11, RAX and EFLAGS.
18215 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18216 .addExternalSymbol("___chkstk")
18217 .addReg(X86::RAX, RegState::Implicit)
18218 .addReg(X86::RSP, RegState::Implicit)
18219 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18220 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18221 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18223 // __chkstk(MSVCRT): does not update stack pointer.
18224 // Clobbers R10, R11 and EFLAGS.
18225 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18226 .addExternalSymbol("__chkstk")
18227 .addReg(X86::RAX, RegState::Implicit)
18228 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18229 // RAX has the offset to be subtracted from RSP.
18230 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18235 const char *StackProbeSymbol =
18236 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18238 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18239 .addExternalSymbol(StackProbeSymbol)
18240 .addReg(X86::EAX, RegState::Implicit)
18241 .addReg(X86::ESP, RegState::Implicit)
18242 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18243 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18244 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18247 MI->eraseFromParent(); // The pseudo instruction is gone now.
18251 MachineBasicBlock *
18252 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18253 MachineBasicBlock *BB) const {
18254 // This is pretty easy. We're taking the value that we received from
18255 // our load from the relocation, sticking it in either RDI (x86-64)
18256 // or EAX and doing an indirect call. The return value will then
18257 // be in the normal return register.
18258 MachineFunction *F = BB->getParent();
18259 const X86InstrInfo *TII =
18260 static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18261 DebugLoc DL = MI->getDebugLoc();
18263 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18264 assert(MI->getOperand(3).isGlobal() && "This should be a global");
18266 // Get a register mask for the lowered call.
18267 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18268 // proper register mask.
18269 const uint32_t *RegMask = F->getTarget()
18270 .getSubtargetImpl()
18271 ->getRegisterInfo()
18272 ->getCallPreservedMask(CallingConv::C);
18273 if (Subtarget->is64Bit()) {
18274 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18275 TII->get(X86::MOV64rm), X86::RDI)
18277 .addImm(0).addReg(0)
18278 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18279 MI->getOperand(3).getTargetFlags())
18281 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18282 addDirectMem(MIB, X86::RDI);
18283 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18284 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18285 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18286 TII->get(X86::MOV32rm), X86::EAX)
18288 .addImm(0).addReg(0)
18289 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18290 MI->getOperand(3).getTargetFlags())
18292 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18293 addDirectMem(MIB, X86::EAX);
18294 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18296 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18297 TII->get(X86::MOV32rm), X86::EAX)
18298 .addReg(TII->getGlobalBaseReg(F))
18299 .addImm(0).addReg(0)
18300 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18301 MI->getOperand(3).getTargetFlags())
18303 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18304 addDirectMem(MIB, X86::EAX);
18305 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18308 MI->eraseFromParent(); // The pseudo instruction is gone now.
18312 MachineBasicBlock *
18313 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18314 MachineBasicBlock *MBB) const {
18315 DebugLoc DL = MI->getDebugLoc();
18316 MachineFunction *MF = MBB->getParent();
18317 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18318 MachineRegisterInfo &MRI = MF->getRegInfo();
18320 const BasicBlock *BB = MBB->getBasicBlock();
18321 MachineFunction::iterator I = MBB;
18324 // Memory Reference
18325 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18326 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18329 unsigned MemOpndSlot = 0;
18331 unsigned CurOp = 0;
18333 DstReg = MI->getOperand(CurOp++).getReg();
18334 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18335 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18336 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18337 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18339 MemOpndSlot = CurOp;
18341 MVT PVT = getPointerTy();
18342 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18343 "Invalid Pointer Size!");
18345 // For v = setjmp(buf), we generate
18348 // buf[LabelOffset] = restoreMBB
18349 // SjLjSetup restoreMBB
18355 // v = phi(main, restore)
18360 MachineBasicBlock *thisMBB = MBB;
18361 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18362 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18363 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18364 MF->insert(I, mainMBB);
18365 MF->insert(I, sinkMBB);
18366 MF->push_back(restoreMBB);
18368 MachineInstrBuilder MIB;
18370 // Transfer the remainder of BB and its successor edges to sinkMBB.
18371 sinkMBB->splice(sinkMBB->begin(), MBB,
18372 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18373 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18376 unsigned PtrStoreOpc = 0;
18377 unsigned LabelReg = 0;
18378 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18379 Reloc::Model RM = MF->getTarget().getRelocationModel();
18380 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18381 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18383 // Prepare IP either in reg or imm.
18384 if (!UseImmLabel) {
18385 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18386 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18387 LabelReg = MRI.createVirtualRegister(PtrRC);
18388 if (Subtarget->is64Bit()) {
18389 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18393 .addMBB(restoreMBB)
18396 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18397 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18398 .addReg(XII->getGlobalBaseReg(MF))
18401 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18405 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18407 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18408 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18409 if (i == X86::AddrDisp)
18410 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18412 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18415 MIB.addReg(LabelReg);
18417 MIB.addMBB(restoreMBB);
18418 MIB.setMemRefs(MMOBegin, MMOEnd);
18420 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18421 .addMBB(restoreMBB);
18423 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18424 MF->getSubtarget().getRegisterInfo());
18425 MIB.addRegMask(RegInfo->getNoPreservedMask());
18426 thisMBB->addSuccessor(mainMBB);
18427 thisMBB->addSuccessor(restoreMBB);
18431 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18432 mainMBB->addSuccessor(sinkMBB);
18435 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18436 TII->get(X86::PHI), DstReg)
18437 .addReg(mainDstReg).addMBB(mainMBB)
18438 .addReg(restoreDstReg).addMBB(restoreMBB);
18441 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18442 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18443 restoreMBB->addSuccessor(sinkMBB);
18445 MI->eraseFromParent();
18449 MachineBasicBlock *
18450 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18451 MachineBasicBlock *MBB) const {
18452 DebugLoc DL = MI->getDebugLoc();
18453 MachineFunction *MF = MBB->getParent();
18454 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18455 MachineRegisterInfo &MRI = MF->getRegInfo();
18457 // Memory Reference
18458 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18459 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18461 MVT PVT = getPointerTy();
18462 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18463 "Invalid Pointer Size!");
18465 const TargetRegisterClass *RC =
18466 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18467 unsigned Tmp = MRI.createVirtualRegister(RC);
18468 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18469 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18470 MF->getSubtarget().getRegisterInfo());
18471 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18472 unsigned SP = RegInfo->getStackRegister();
18474 MachineInstrBuilder MIB;
18476 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18477 const int64_t SPOffset = 2 * PVT.getStoreSize();
18479 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18480 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18483 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18484 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18485 MIB.addOperand(MI->getOperand(i));
18486 MIB.setMemRefs(MMOBegin, MMOEnd);
18488 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18489 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18490 if (i == X86::AddrDisp)
18491 MIB.addDisp(MI->getOperand(i), LabelOffset);
18493 MIB.addOperand(MI->getOperand(i));
18495 MIB.setMemRefs(MMOBegin, MMOEnd);
18497 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18498 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18499 if (i == X86::AddrDisp)
18500 MIB.addDisp(MI->getOperand(i), SPOffset);
18502 MIB.addOperand(MI->getOperand(i));
18504 MIB.setMemRefs(MMOBegin, MMOEnd);
18506 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18508 MI->eraseFromParent();
18512 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18513 // accumulator loops. Writing back to the accumulator allows the coalescer
18514 // to remove extra copies in the loop.
18515 MachineBasicBlock *
18516 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18517 MachineBasicBlock *MBB) const {
18518 MachineOperand &AddendOp = MI->getOperand(3);
18520 // Bail out early if the addend isn't a register - we can't switch these.
18521 if (!AddendOp.isReg())
18524 MachineFunction &MF = *MBB->getParent();
18525 MachineRegisterInfo &MRI = MF.getRegInfo();
18527 // Check whether the addend is defined by a PHI:
18528 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18529 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18530 if (!AddendDef.isPHI())
18533 // Look for the following pattern:
18535 // %addend = phi [%entry, 0], [%loop, %result]
18537 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18541 // %addend = phi [%entry, 0], [%loop, %result]
18543 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18545 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18546 assert(AddendDef.getOperand(i).isReg());
18547 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18548 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18549 if (&PHISrcInst == MI) {
18550 // Found a matching instruction.
18551 unsigned NewFMAOpc = 0;
18552 switch (MI->getOpcode()) {
18553 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18554 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18555 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18556 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18557 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18558 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18559 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18560 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18561 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18562 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18563 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18564 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18565 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18566 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18567 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18568 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18569 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18570 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18571 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18572 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18573 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18574 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18575 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18576 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18577 default: llvm_unreachable("Unrecognized FMA variant.");
18580 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18581 MachineInstrBuilder MIB =
18582 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18583 .addOperand(MI->getOperand(0))
18584 .addOperand(MI->getOperand(3))
18585 .addOperand(MI->getOperand(2))
18586 .addOperand(MI->getOperand(1));
18587 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18588 MI->eraseFromParent();
18595 MachineBasicBlock *
18596 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18597 MachineBasicBlock *BB) const {
18598 switch (MI->getOpcode()) {
18599 default: llvm_unreachable("Unexpected instr type to insert");
18600 case X86::TAILJMPd64:
18601 case X86::TAILJMPr64:
18602 case X86::TAILJMPm64:
18603 llvm_unreachable("TAILJMP64 would not be touched here.");
18604 case X86::TCRETURNdi64:
18605 case X86::TCRETURNri64:
18606 case X86::TCRETURNmi64:
18608 case X86::WIN_ALLOCA:
18609 return EmitLoweredWinAlloca(MI, BB);
18610 case X86::SEG_ALLOCA_32:
18611 return EmitLoweredSegAlloca(MI, BB, false);
18612 case X86::SEG_ALLOCA_64:
18613 return EmitLoweredSegAlloca(MI, BB, true);
18614 case X86::TLSCall_32:
18615 case X86::TLSCall_64:
18616 return EmitLoweredTLSCall(MI, BB);
18617 case X86::CMOV_GR8:
18618 case X86::CMOV_FR32:
18619 case X86::CMOV_FR64:
18620 case X86::CMOV_V4F32:
18621 case X86::CMOV_V2F64:
18622 case X86::CMOV_V2I64:
18623 case X86::CMOV_V8F32:
18624 case X86::CMOV_V4F64:
18625 case X86::CMOV_V4I64:
18626 case X86::CMOV_V16F32:
18627 case X86::CMOV_V8F64:
18628 case X86::CMOV_V8I64:
18629 case X86::CMOV_GR16:
18630 case X86::CMOV_GR32:
18631 case X86::CMOV_RFP32:
18632 case X86::CMOV_RFP64:
18633 case X86::CMOV_RFP80:
18634 return EmitLoweredSelect(MI, BB);
18636 case X86::FP32_TO_INT16_IN_MEM:
18637 case X86::FP32_TO_INT32_IN_MEM:
18638 case X86::FP32_TO_INT64_IN_MEM:
18639 case X86::FP64_TO_INT16_IN_MEM:
18640 case X86::FP64_TO_INT32_IN_MEM:
18641 case X86::FP64_TO_INT64_IN_MEM:
18642 case X86::FP80_TO_INT16_IN_MEM:
18643 case X86::FP80_TO_INT32_IN_MEM:
18644 case X86::FP80_TO_INT64_IN_MEM: {
18645 MachineFunction *F = BB->getParent();
18646 const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
18647 DebugLoc DL = MI->getDebugLoc();
18649 // Change the floating point control register to use "round towards zero"
18650 // mode when truncating to an integer value.
18651 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18652 addFrameReference(BuildMI(*BB, MI, DL,
18653 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18655 // Load the old value of the high byte of the control word...
18657 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18658 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18661 // Set the high part to be round to zero...
18662 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18665 // Reload the modified control word now...
18666 addFrameReference(BuildMI(*BB, MI, DL,
18667 TII->get(X86::FLDCW16m)), CWFrameIdx);
18669 // Restore the memory image of control word to original value
18670 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18673 // Get the X86 opcode to use.
18675 switch (MI->getOpcode()) {
18676 default: llvm_unreachable("illegal opcode!");
18677 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18678 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18679 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18680 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18681 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18682 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18683 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18684 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18685 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18689 MachineOperand &Op = MI->getOperand(0);
18691 AM.BaseType = X86AddressMode::RegBase;
18692 AM.Base.Reg = Op.getReg();
18694 AM.BaseType = X86AddressMode::FrameIndexBase;
18695 AM.Base.FrameIndex = Op.getIndex();
18697 Op = MI->getOperand(1);
18699 AM.Scale = Op.getImm();
18700 Op = MI->getOperand(2);
18702 AM.IndexReg = Op.getImm();
18703 Op = MI->getOperand(3);
18704 if (Op.isGlobal()) {
18705 AM.GV = Op.getGlobal();
18707 AM.Disp = Op.getImm();
18709 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18710 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18712 // Reload the original control word now.
18713 addFrameReference(BuildMI(*BB, MI, DL,
18714 TII->get(X86::FLDCW16m)), CWFrameIdx);
18716 MI->eraseFromParent(); // The pseudo instruction is gone now.
18719 // String/text processing lowering.
18720 case X86::PCMPISTRM128REG:
18721 case X86::VPCMPISTRM128REG:
18722 case X86::PCMPISTRM128MEM:
18723 case X86::VPCMPISTRM128MEM:
18724 case X86::PCMPESTRM128REG:
18725 case X86::VPCMPESTRM128REG:
18726 case X86::PCMPESTRM128MEM:
18727 case X86::VPCMPESTRM128MEM:
18728 assert(Subtarget->hasSSE42() &&
18729 "Target must have SSE4.2 or AVX features enabled");
18730 return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18732 // String/text processing lowering.
18733 case X86::PCMPISTRIREG:
18734 case X86::VPCMPISTRIREG:
18735 case X86::PCMPISTRIMEM:
18736 case X86::VPCMPISTRIMEM:
18737 case X86::PCMPESTRIREG:
18738 case X86::VPCMPESTRIREG:
18739 case X86::PCMPESTRIMEM:
18740 case X86::VPCMPESTRIMEM:
18741 assert(Subtarget->hasSSE42() &&
18742 "Target must have SSE4.2 or AVX features enabled");
18743 return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18745 // Thread synchronization.
18747 return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
18752 return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
18754 case X86::VASTART_SAVE_XMM_REGS:
18755 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18757 case X86::VAARG_64:
18758 return EmitVAARG64WithCustomInserter(MI, BB);
18760 case X86::EH_SjLj_SetJmp32:
18761 case X86::EH_SjLj_SetJmp64:
18762 return emitEHSjLjSetJmp(MI, BB);
18764 case X86::EH_SjLj_LongJmp32:
18765 case X86::EH_SjLj_LongJmp64:
18766 return emitEHSjLjLongJmp(MI, BB);
18768 case TargetOpcode::STACKMAP:
18769 case TargetOpcode::PATCHPOINT:
18770 return emitPatchPoint(MI, BB);
18772 case X86::VFMADDPDr213r:
18773 case X86::VFMADDPSr213r:
18774 case X86::VFMADDSDr213r:
18775 case X86::VFMADDSSr213r:
18776 case X86::VFMSUBPDr213r:
18777 case X86::VFMSUBPSr213r:
18778 case X86::VFMSUBSDr213r:
18779 case X86::VFMSUBSSr213r:
18780 case X86::VFNMADDPDr213r:
18781 case X86::VFNMADDPSr213r:
18782 case X86::VFNMADDSDr213r:
18783 case X86::VFNMADDSSr213r:
18784 case X86::VFNMSUBPDr213r:
18785 case X86::VFNMSUBPSr213r:
18786 case X86::VFNMSUBSDr213r:
18787 case X86::VFNMSUBSSr213r:
18788 case X86::VFMADDPDr213rY:
18789 case X86::VFMADDPSr213rY:
18790 case X86::VFMSUBPDr213rY:
18791 case X86::VFMSUBPSr213rY:
18792 case X86::VFNMADDPDr213rY:
18793 case X86::VFNMADDPSr213rY:
18794 case X86::VFNMSUBPDr213rY:
18795 case X86::VFNMSUBPSr213rY:
18796 return emitFMA3Instr(MI, BB);
18800 //===----------------------------------------------------------------------===//
18801 // X86 Optimization Hooks
18802 //===----------------------------------------------------------------------===//
18804 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18807 const SelectionDAG &DAG,
18808 unsigned Depth) const {
18809 unsigned BitWidth = KnownZero.getBitWidth();
18810 unsigned Opc = Op.getOpcode();
18811 assert((Opc >= ISD::BUILTIN_OP_END ||
18812 Opc == ISD::INTRINSIC_WO_CHAIN ||
18813 Opc == ISD::INTRINSIC_W_CHAIN ||
18814 Opc == ISD::INTRINSIC_VOID) &&
18815 "Should use MaskedValueIsZero if you don't know whether Op"
18816 " is a target node!");
18818 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
18832 // These nodes' second result is a boolean.
18833 if (Op.getResNo() == 0)
18836 case X86ISD::SETCC:
18837 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18839 case ISD::INTRINSIC_WO_CHAIN: {
18840 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18841 unsigned NumLoBits = 0;
18844 case Intrinsic::x86_sse_movmsk_ps:
18845 case Intrinsic::x86_avx_movmsk_ps_256:
18846 case Intrinsic::x86_sse2_movmsk_pd:
18847 case Intrinsic::x86_avx_movmsk_pd_256:
18848 case Intrinsic::x86_mmx_pmovmskb:
18849 case Intrinsic::x86_sse2_pmovmskb_128:
18850 case Intrinsic::x86_avx2_pmovmskb: {
18851 // High bits of movmskp{s|d}, pmovmskb are known zero.
18853 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18854 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
18855 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
18856 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
18857 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
18858 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
18859 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
18860 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
18862 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18871 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18873 const SelectionDAG &,
18874 unsigned Depth) const {
18875 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18876 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18877 return Op.getValueType().getScalarType().getSizeInBits();
18883 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18884 /// node is a GlobalAddress + offset.
18885 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18886 const GlobalValue* &GA,
18887 int64_t &Offset) const {
18888 if (N->getOpcode() == X86ISD::Wrapper) {
18889 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18890 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18891 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18895 return TargetLowering::isGAPlusOffset(N, GA, Offset);
18898 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18899 /// same as extracting the high 128-bit part of 256-bit vector and then
18900 /// inserting the result into the low part of a new 256-bit vector
18901 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18902 EVT VT = SVOp->getValueType(0);
18903 unsigned NumElems = VT.getVectorNumElements();
18905 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18906 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18907 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18908 SVOp->getMaskElt(j) >= 0)
18914 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18915 /// same as extracting the low 128-bit part of 256-bit vector and then
18916 /// inserting the result into the high part of a new 256-bit vector
18917 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18918 EVT VT = SVOp->getValueType(0);
18919 unsigned NumElems = VT.getVectorNumElements();
18921 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18922 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18923 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18924 SVOp->getMaskElt(j) >= 0)
18930 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18931 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18932 TargetLowering::DAGCombinerInfo &DCI,
18933 const X86Subtarget* Subtarget) {
18935 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18936 SDValue V1 = SVOp->getOperand(0);
18937 SDValue V2 = SVOp->getOperand(1);
18938 EVT VT = SVOp->getValueType(0);
18939 unsigned NumElems = VT.getVectorNumElements();
18941 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18942 V2.getOpcode() == ISD::CONCAT_VECTORS) {
18946 // V UNDEF BUILD_VECTOR UNDEF
18948 // CONCAT_VECTOR CONCAT_VECTOR
18951 // RESULT: V + zero extended
18953 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18954 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18955 V1.getOperand(1).getOpcode() != ISD::UNDEF)
18958 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18961 // To match the shuffle mask, the first half of the mask should
18962 // be exactly the first vector, and all the rest a splat with the
18963 // first element of the second one.
18964 for (unsigned i = 0; i != NumElems/2; ++i)
18965 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18966 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18969 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18970 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18971 if (Ld->hasNUsesOfValue(1, 0)) {
18972 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18973 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18975 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18977 Ld->getPointerInfo(),
18978 Ld->getAlignment(),
18979 false/*isVolatile*/, true/*ReadMem*/,
18980 false/*WriteMem*/);
18982 // Make sure the newly-created LOAD is in the same position as Ld in
18983 // terms of dependency. We create a TokenFactor for Ld and ResNode,
18984 // and update uses of Ld's output chain to use the TokenFactor.
18985 if (Ld->hasAnyUseOfValue(1)) {
18986 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18987 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18988 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18989 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18990 SDValue(ResNode.getNode(), 1));
18993 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18997 // Emit a zeroed vector and insert the desired subvector on its
18999 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19000 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19001 return DCI.CombineTo(N, InsV);
19004 //===--------------------------------------------------------------------===//
19005 // Combine some shuffles into subvector extracts and inserts:
19008 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19009 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19010 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19011 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19012 return DCI.CombineTo(N, InsV);
19015 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19016 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19017 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19018 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19019 return DCI.CombineTo(N, InsV);
19025 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19028 /// This is the leaf of the recursive combinine below. When we have found some
19029 /// chain of single-use x86 shuffle instructions and accumulated the combined
19030 /// shuffle mask represented by them, this will try to pattern match that mask
19031 /// into either a single instruction if there is a special purpose instruction
19032 /// for this operation, or into a PSHUFB instruction which is a fully general
19033 /// instruction but should only be used to replace chains over a certain depth.
19034 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19035 int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19036 TargetLowering::DAGCombinerInfo &DCI,
19037 const X86Subtarget *Subtarget) {
19038 assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19040 // Find the operand that enters the chain. Note that multiple uses are OK
19041 // here, we're not going to remove the operand we find.
19042 SDValue Input = Op.getOperand(0);
19043 while (Input.getOpcode() == ISD::BITCAST)
19044 Input = Input.getOperand(0);
19046 MVT VT = Input.getSimpleValueType();
19047 MVT RootVT = Root.getSimpleValueType();
19050 // Just remove no-op shuffle masks.
19051 if (Mask.size() == 1) {
19052 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19057 // Use the float domain if the operand type is a floating point type.
19058 bool FloatDomain = VT.isFloatingPoint();
19060 // If we don't have access to VEX encodings, the generic PSHUF instructions
19061 // are preferable to some of the specialized forms despite requiring one more
19062 // byte to encode because they can implicitly copy.
19064 // IF we *do* have VEX encodings, than we can use shorter, more specific
19065 // shuffle instructions freely as they can copy due to the extra register
19067 if (Subtarget->hasAVX()) {
19068 // We have both floating point and integer variants of shuffles that dup
19069 // either the low or high half of the vector.
19070 if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19071 bool Lo = Mask.equals(0, 0);
19072 unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
19073 : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
19074 if (Depth == 1 && Root->getOpcode() == Shuffle)
19075 return false; // Nothing to do!
19076 MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
19077 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19078 DCI.AddToWorklist(Op.getNode());
19079 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19080 DCI.AddToWorklist(Op.getNode());
19081 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19086 // FIXME: We should match UNPCKLPS and UNPCKHPS here.
19088 // For the integer domain we have specialized instructions for duplicating
19089 // any element size from the low or high half.
19090 if (!FloatDomain &&
19091 (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19092 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19093 Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19094 Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19095 Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19097 bool Lo = Mask[0] == 0;
19098 unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19099 if (Depth == 1 && Root->getOpcode() == Shuffle)
19100 return false; // Nothing to do!
19102 switch (Mask.size()) {
19103 case 4: ShuffleVT = MVT::v4i32; break;
19104 case 8: ShuffleVT = MVT::v8i16; break;
19105 case 16: ShuffleVT = MVT::v16i8; break;
19107 Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19108 DCI.AddToWorklist(Op.getNode());
19109 Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19110 DCI.AddToWorklist(Op.getNode());
19111 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19117 // Don't try to re-form single instruction chains under any circumstances now
19118 // that we've done encoding canonicalization for them.
19122 // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19123 // can replace them with a single PSHUFB instruction profitably. Intel's
19124 // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19125 // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19126 if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19127 SmallVector<SDValue, 16> PSHUFBMask;
19128 assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19129 int Ratio = 16 / Mask.size();
19130 for (unsigned i = 0; i < 16; ++i) {
19131 int M = Mask[i / Ratio] != SM_SentinelZero
19132 ? Ratio * Mask[i / Ratio] + i % Ratio
19134 PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19136 Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19137 DCI.AddToWorklist(Op.getNode());
19138 SDValue PSHUFBMaskOp =
19139 DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19140 DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19141 Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19142 DCI.AddToWorklist(Op.getNode());
19143 DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19148 // Failed to find any combines.
19152 /// \brief Fully generic combining of x86 shuffle instructions.
19154 /// This should be the last combine run over the x86 shuffle instructions. Once
19155 /// they have been fully optimized, this will recursively consider all chains
19156 /// of single-use shuffle instructions, build a generic model of the cumulative
19157 /// shuffle operation, and check for simpler instructions which implement this
19158 /// operation. We use this primarily for two purposes:
19160 /// 1) Collapse generic shuffles to specialized single instructions when
19161 /// equivalent. In most cases, this is just an encoding size win, but
19162 /// sometimes we will collapse multiple generic shuffles into a single
19163 /// special-purpose shuffle.
19164 /// 2) Look for sequences of shuffle instructions with 3 or more total
19165 /// instructions, and replace them with the slightly more expensive SSSE3
19166 /// PSHUFB instruction if available. We do this as the last combining step
19167 /// to ensure we avoid using PSHUFB if we can implement the shuffle with
19168 /// a suitable short sequence of other instructions. The PHUFB will either
19169 /// use a register or have to read from memory and so is slightly (but only
19170 /// slightly) more expensive than the other shuffle instructions.
19172 /// Because this is inherently a quadratic operation (for each shuffle in
19173 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19174 /// This should never be an issue in practice as the shuffle lowering doesn't
19175 /// produce sequences of more than 8 instructions.
19177 /// FIXME: We will currently miss some cases where the redundant shuffling
19178 /// would simplify under the threshold for PSHUFB formation because of
19179 /// combine-ordering. To fix this, we should do the redundant instruction
19180 /// combining in this recursive walk.
19181 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19182 ArrayRef<int> RootMask,
19183 int Depth, bool HasPSHUFB,
19185 TargetLowering::DAGCombinerInfo &DCI,
19186 const X86Subtarget *Subtarget) {
19187 // Bound the depth of our recursive combine because this is ultimately
19188 // quadratic in nature.
19192 // Directly rip through bitcasts to find the underlying operand.
19193 while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19194 Op = Op.getOperand(0);
19196 MVT VT = Op.getSimpleValueType();
19197 if (!VT.isVector())
19198 return false; // Bail if we hit a non-vector.
19199 // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19200 // version should be added.
19201 if (VT.getSizeInBits() != 128)
19204 assert(Root.getSimpleValueType().isVector() &&
19205 "Shuffles operate on vector types!");
19206 assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19207 "Can only combine shuffles of the same vector register size.");
19209 if (!isTargetShuffle(Op.getOpcode()))
19211 SmallVector<int, 16> OpMask;
19213 bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19214 // We only can combine unary shuffles which we can decode the mask for.
19215 if (!HaveMask || !IsUnary)
19218 assert(VT.getVectorNumElements() == OpMask.size() &&
19219 "Different mask size from vector size!");
19220 assert(((RootMask.size() > OpMask.size() &&
19221 RootMask.size() % OpMask.size() == 0) ||
19222 (OpMask.size() > RootMask.size() &&
19223 OpMask.size() % RootMask.size() == 0) ||
19224 OpMask.size() == RootMask.size()) &&
19225 "The smaller number of elements must divide the larger.");
19226 int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19227 int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19228 assert(((RootRatio == 1 && OpRatio == 1) ||
19229 (RootRatio == 1) != (OpRatio == 1)) &&
19230 "Must not have a ratio for both incoming and op masks!");
19232 SmallVector<int, 16> Mask;
19233 Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19235 // Merge this shuffle operation's mask into our accumulated mask. Note that
19236 // this shuffle's mask will be the first applied to the input, followed by the
19237 // root mask to get us all the way to the root value arrangement. The reason
19238 // for this order is that we are recursing up the operation chain.
19239 for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19240 int RootIdx = i / RootRatio;
19241 if (RootMask[RootIdx] == SM_SentinelZero) {
19242 // This is a zero-ed lane, we're done.
19243 Mask.push_back(SM_SentinelZero);
19247 int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19248 int OpIdx = RootMaskedIdx / OpRatio;
19249 if (OpMask[OpIdx] == SM_SentinelZero) {
19250 // The incoming lanes are zero, it doesn't matter which ones we are using.
19251 Mask.push_back(SM_SentinelZero);
19255 // Ok, we have non-zero lanes, map them through.
19256 Mask.push_back(OpMask[OpIdx] * OpRatio +
19257 RootMaskedIdx % OpRatio);
19260 // See if we can recurse into the operand to combine more things.
19261 switch (Op.getOpcode()) {
19262 case X86ISD::PSHUFB:
19264 case X86ISD::PSHUFD:
19265 case X86ISD::PSHUFHW:
19266 case X86ISD::PSHUFLW:
19267 if (Op.getOperand(0).hasOneUse() &&
19268 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19269 HasPSHUFB, DAG, DCI, Subtarget))
19273 case X86ISD::UNPCKL:
19274 case X86ISD::UNPCKH:
19275 assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19276 // We can't check for single use, we have to check that this shuffle is the only user.
19277 if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19278 combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19279 HasPSHUFB, DAG, DCI, Subtarget))
19284 // Minor canonicalization of the accumulated shuffle mask to make it easier
19285 // to match below. All this does is detect masks with squential pairs of
19286 // elements, and shrink them to the half-width mask. It does this in a loop
19287 // so it will reduce the size of the mask to the minimal width mask which
19288 // performs an equivalent shuffle.
19289 while (Mask.size() > 1 && canWidenShuffleElements(Mask)) {
19290 for (int i = 0, e = Mask.size() / 2; i < e; ++i)
19291 Mask[i] = Mask[2 * i] / 2;
19292 Mask.resize(Mask.size() / 2);
19295 return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19299 /// \brief Get the PSHUF-style mask from PSHUF node.
19301 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19302 /// PSHUF-style masks that can be reused with such instructions.
19303 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19304 SmallVector<int, 4> Mask;
19306 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19310 switch (N.getOpcode()) {
19311 case X86ISD::PSHUFD:
19313 case X86ISD::PSHUFLW:
19316 case X86ISD::PSHUFHW:
19317 Mask.erase(Mask.begin(), Mask.begin() + 4);
19318 for (int &M : Mask)
19322 llvm_unreachable("No valid shuffle instruction found!");
19326 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19328 /// We walk up the chain and look for a combinable shuffle, skipping over
19329 /// shuffles that we could hoist this shuffle's transformation past without
19330 /// altering anything.
19331 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19333 TargetLowering::DAGCombinerInfo &DCI) {
19334 assert(N.getOpcode() == X86ISD::PSHUFD &&
19335 "Called with something other than an x86 128-bit half shuffle!");
19338 // Walk up a single-use chain looking for a combinable shuffle.
19339 SDValue V = N.getOperand(0);
19340 for (; V.hasOneUse(); V = V.getOperand(0)) {
19341 switch (V.getOpcode()) {
19343 return false; // Nothing combined!
19346 // Skip bitcasts as we always know the type for the target specific
19350 case X86ISD::PSHUFD:
19351 // Found another dword shuffle.
19354 case X86ISD::PSHUFLW:
19355 // Check that the low words (being shuffled) are the identity in the
19356 // dword shuffle, and the high words are self-contained.
19357 if (Mask[0] != 0 || Mask[1] != 1 ||
19358 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19363 case X86ISD::PSHUFHW:
19364 // Check that the high words (being shuffled) are the identity in the
19365 // dword shuffle, and the low words are self-contained.
19366 if (Mask[2] != 2 || Mask[3] != 3 ||
19367 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19372 case X86ISD::UNPCKL:
19373 case X86ISD::UNPCKH:
19374 // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19375 // shuffle into a preceding word shuffle.
19376 if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19379 // Search for a half-shuffle which we can combine with.
19380 unsigned CombineOp =
19381 V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19382 if (V.getOperand(0) != V.getOperand(1) ||
19383 !V->isOnlyUserOf(V.getOperand(0).getNode()))
19385 V = V.getOperand(0);
19387 switch (V.getOpcode()) {
19389 return false; // Nothing to combine.
19391 case X86ISD::PSHUFLW:
19392 case X86ISD::PSHUFHW:
19393 if (V.getOpcode() == CombineOp)
19398 V = V.getOperand(0);
19402 } while (V.hasOneUse());
19405 // Break out of the loop if we break out of the switch.
19409 if (!V.hasOneUse())
19410 // We fell out of the loop without finding a viable combining instruction.
19413 // Record the old value to use in RAUW-ing.
19416 // Merge this node's mask and our incoming mask.
19417 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19418 for (int &M : Mask)
19420 V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19421 getV4X86ShuffleImm8ForMask(Mask, DAG));
19423 // It is possible that one of the combinable shuffles was completely absorbed
19424 // by the other, just replace it and revisit all users in that case.
19425 if (Old.getNode() == V.getNode()) {
19426 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
19430 // Replace N with its operand as we're going to combine that shuffle away.
19431 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19433 // Replace the combinable shuffle with the combined one, updating all users
19434 // so that we re-evaluate the chain here.
19435 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19439 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19441 /// We walk up the chain, skipping shuffles of the other half and looking
19442 /// through shuffles which switch halves trying to find a shuffle of the same
19443 /// pair of dwords.
19444 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19446 TargetLowering::DAGCombinerInfo &DCI) {
19448 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19449 "Called with something other than an x86 128-bit half shuffle!");
19451 unsigned CombineOpcode = N.getOpcode();
19453 // Walk up a single-use chain looking for a combinable shuffle.
19454 SDValue V = N.getOperand(0);
19455 for (; V.hasOneUse(); V = V.getOperand(0)) {
19456 switch (V.getOpcode()) {
19458 return false; // Nothing combined!
19461 // Skip bitcasts as we always know the type for the target specific
19465 case X86ISD::PSHUFLW:
19466 case X86ISD::PSHUFHW:
19467 if (V.getOpcode() == CombineOpcode)
19470 // Other-half shuffles are no-ops.
19473 // Break out of the loop if we break out of the switch.
19477 if (!V.hasOneUse())
19478 // We fell out of the loop without finding a viable combining instruction.
19481 // Combine away the bottom node as its shuffle will be accumulated into
19482 // a preceding shuffle.
19483 DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19485 // Record the old value.
19488 // Merge this node's mask and our incoming mask (adjusted to account for all
19489 // the pshufd instructions encountered).
19490 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19491 for (int &M : Mask)
19493 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19494 getV4X86ShuffleImm8ForMask(Mask, DAG));
19496 // Check that the shuffles didn't cancel each other out. If not, we need to
19497 // combine to the new one.
19499 // Replace the combinable shuffle with the combined one, updating all users
19500 // so that we re-evaluate the chain here.
19501 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19506 /// \brief Try to combine x86 target specific shuffles.
19507 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19508 TargetLowering::DAGCombinerInfo &DCI,
19509 const X86Subtarget *Subtarget) {
19511 MVT VT = N.getSimpleValueType();
19512 SmallVector<int, 4> Mask;
19514 switch (N.getOpcode()) {
19515 case X86ISD::PSHUFD:
19516 case X86ISD::PSHUFLW:
19517 case X86ISD::PSHUFHW:
19518 Mask = getPSHUFShuffleMask(N);
19519 assert(Mask.size() == 4);
19525 // Nuke no-op shuffles that show up after combining.
19526 if (isNoopShuffleMask(Mask))
19527 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19529 // Look for simplifications involving one or two shuffle instructions.
19530 SDValue V = N.getOperand(0);
19531 switch (N.getOpcode()) {
19534 case X86ISD::PSHUFLW:
19535 case X86ISD::PSHUFHW:
19536 assert(VT == MVT::v8i16);
19539 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19540 return SDValue(); // We combined away this shuffle, so we're done.
19542 // See if this reduces to a PSHUFD which is no more expensive and can
19543 // combine with more operations.
19544 if (canWidenShuffleElements(Mask)) {
19545 int DMask[] = {-1, -1, -1, -1};
19546 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19547 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19548 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19549 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19550 DCI.AddToWorklist(V.getNode());
19551 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19552 getV4X86ShuffleImm8ForMask(DMask, DAG));
19553 DCI.AddToWorklist(V.getNode());
19554 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19557 // Look for shuffle patterns which can be implemented as a single unpack.
19558 // FIXME: This doesn't handle the location of the PSHUFD generically, and
19559 // only works when we have a PSHUFD followed by two half-shuffles.
19560 if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19561 (V.getOpcode() == X86ISD::PSHUFLW ||
19562 V.getOpcode() == X86ISD::PSHUFHW) &&
19563 V.getOpcode() != N.getOpcode() &&
19565 SDValue D = V.getOperand(0);
19566 while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19567 D = D.getOperand(0);
19568 if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19569 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19570 SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19571 int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19572 int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19574 for (int i = 0; i < 4; ++i) {
19575 WordMask[i + NOffset] = Mask[i] + NOffset;
19576 WordMask[i + VOffset] = VMask[i] + VOffset;
19578 // Map the word mask through the DWord mask.
19580 for (int i = 0; i < 8; ++i)
19581 MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19582 const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19583 const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19584 if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19585 std::begin(UnpackLoMask)) ||
19586 std::equal(std::begin(MappedMask), std::end(MappedMask),
19587 std::begin(UnpackHiMask))) {
19588 // We can replace all three shuffles with an unpack.
19589 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19590 DCI.AddToWorklist(V.getNode());
19591 return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19593 DL, MVT::v8i16, V, V);
19600 case X86ISD::PSHUFD:
19601 if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19602 return SDValue(); // We combined away this shuffle.
19610 /// PerformShuffleCombine - Performs several different shuffle combines.
19611 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19612 TargetLowering::DAGCombinerInfo &DCI,
19613 const X86Subtarget *Subtarget) {
19615 SDValue N0 = N->getOperand(0);
19616 SDValue N1 = N->getOperand(1);
19617 EVT VT = N->getValueType(0);
19619 // Don't create instructions with illegal types after legalize types has run.
19620 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19621 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19624 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19625 if (Subtarget->hasFp256() && VT.is256BitVector() &&
19626 N->getOpcode() == ISD::VECTOR_SHUFFLE)
19627 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19629 // During Type Legalization, when promoting illegal vector types,
19630 // the backend might introduce new shuffle dag nodes and bitcasts.
19632 // This code performs the following transformation:
19633 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19634 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19636 // We do this only if both the bitcast and the BINOP dag nodes have
19637 // one use. Also, perform this transformation only if the new binary
19638 // operation is legal. This is to avoid introducing dag nodes that
19639 // potentially need to be further expanded (or custom lowered) into a
19640 // less optimal sequence of dag nodes.
19641 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19642 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19643 N0.getOpcode() == ISD::BITCAST) {
19644 SDValue BC0 = N0.getOperand(0);
19645 EVT SVT = BC0.getValueType();
19646 unsigned Opcode = BC0.getOpcode();
19647 unsigned NumElts = VT.getVectorNumElements();
19649 if (BC0.hasOneUse() && SVT.isVector() &&
19650 SVT.getVectorNumElements() * 2 == NumElts &&
19651 TLI.isOperationLegal(Opcode, VT)) {
19652 bool CanFold = false;
19664 unsigned SVTNumElts = SVT.getVectorNumElements();
19665 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19666 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19667 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19668 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19669 CanFold = SVOp->getMaskElt(i) < 0;
19672 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19673 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19674 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19675 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19680 // Only handle 128 wide vector from here on.
19681 if (!VT.is128BitVector())
19684 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19685 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19686 // consecutive, non-overlapping, and in the right order.
19687 SmallVector<SDValue, 16> Elts;
19688 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19689 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19691 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19695 if (isTargetShuffle(N->getOpcode())) {
19697 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19698 if (Shuffle.getNode())
19701 // Try recursively combining arbitrary sequences of x86 shuffle
19702 // instructions into higher-order shuffles. We do this after combining
19703 // specific PSHUF instruction sequences into their minimal form so that we
19704 // can evaluate how many specialized shuffle instructions are involved in
19705 // a particular chain.
19706 SmallVector<int, 1> NonceMask; // Just a placeholder.
19707 NonceMask.push_back(0);
19708 if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19709 /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19711 return SDValue(); // This routine will use CombineTo to replace N.
19717 /// PerformTruncateCombine - Converts truncate operation to
19718 /// a sequence of vector shuffle operations.
19719 /// It is possible when we truncate 256-bit vector to 128-bit vector
19720 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19721 TargetLowering::DAGCombinerInfo &DCI,
19722 const X86Subtarget *Subtarget) {
19726 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19727 /// specific shuffle of a load can be folded into a single element load.
19728 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19729 /// shuffles have been customed lowered so we need to handle those here.
19730 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19731 TargetLowering::DAGCombinerInfo &DCI) {
19732 if (DCI.isBeforeLegalizeOps())
19735 SDValue InVec = N->getOperand(0);
19736 SDValue EltNo = N->getOperand(1);
19738 if (!isa<ConstantSDNode>(EltNo))
19741 EVT VT = InVec.getValueType();
19743 bool HasShuffleIntoBitcast = false;
19744 if (InVec.getOpcode() == ISD::BITCAST) {
19745 // Don't duplicate a load with other uses.
19746 if (!InVec.hasOneUse())
19748 EVT BCVT = InVec.getOperand(0).getValueType();
19749 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19751 InVec = InVec.getOperand(0);
19752 HasShuffleIntoBitcast = true;
19755 if (!isTargetShuffle(InVec.getOpcode()))
19758 // Don't duplicate a load with other uses.
19759 if (!InVec.hasOneUse())
19762 SmallVector<int, 16> ShuffleMask;
19764 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19768 // Select the input vector, guarding against out of range extract vector.
19769 unsigned NumElems = VT.getVectorNumElements();
19770 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19771 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19772 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19773 : InVec.getOperand(1);
19775 // If inputs to shuffle are the same for both ops, then allow 2 uses
19776 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19778 if (LdNode.getOpcode() == ISD::BITCAST) {
19779 // Don't duplicate a load with other uses.
19780 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19783 AllowedUses = 1; // only allow 1 load use if we have a bitcast
19784 LdNode = LdNode.getOperand(0);
19787 if (!ISD::isNormalLoad(LdNode.getNode()))
19790 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19792 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19795 if (HasShuffleIntoBitcast) {
19796 // If there's a bitcast before the shuffle, check if the load type and
19797 // alignment is valid.
19798 unsigned Align = LN0->getAlignment();
19799 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19800 unsigned NewAlign = TLI.getDataLayout()->
19801 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19803 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19807 // All checks match so transform back to vector_shuffle so that DAG combiner
19808 // can finish the job
19811 // Create shuffle node taking into account the case that its a unary shuffle
19812 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19813 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19814 InVec.getOperand(0), Shuffle,
19816 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19817 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19821 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19822 /// generation and convert it from being a bunch of shuffles and extracts
19823 /// to a simple store and scalar loads to extract the elements.
19824 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19825 TargetLowering::DAGCombinerInfo &DCI) {
19826 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19827 if (NewOp.getNode())
19830 SDValue InputVector = N->getOperand(0);
19832 // Detect whether we are trying to convert from mmx to i32 and the bitcast
19833 // from mmx to v2i32 has a single usage.
19834 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19835 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19836 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19837 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19838 N->getValueType(0),
19839 InputVector.getNode()->getOperand(0));
19841 // Only operate on vectors of 4 elements, where the alternative shuffling
19842 // gets to be more expensive.
19843 if (InputVector.getValueType() != MVT::v4i32)
19846 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19847 // single use which is a sign-extend or zero-extend, and all elements are
19849 SmallVector<SDNode *, 4> Uses;
19850 unsigned ExtractedElements = 0;
19851 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19852 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19853 if (UI.getUse().getResNo() != InputVector.getResNo())
19856 SDNode *Extract = *UI;
19857 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19860 if (Extract->getValueType(0) != MVT::i32)
19862 if (!Extract->hasOneUse())
19864 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19865 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19867 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19870 // Record which element was extracted.
19871 ExtractedElements |=
19872 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19874 Uses.push_back(Extract);
19877 // If not all the elements were used, this may not be worthwhile.
19878 if (ExtractedElements != 15)
19881 // Ok, we've now decided to do the transformation.
19882 SDLoc dl(InputVector);
19884 // Store the value to a temporary stack slot.
19885 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19886 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19887 MachinePointerInfo(), false, false, 0);
19889 // Replace each use (extract) with a load of the appropriate element.
19890 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19891 UE = Uses.end(); UI != UE; ++UI) {
19892 SDNode *Extract = *UI;
19894 // cOMpute the element's address.
19895 SDValue Idx = Extract->getOperand(1);
19897 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19898 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19899 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19900 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19902 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19903 StackPtr, OffsetVal);
19905 // Load the scalar.
19906 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19907 ScalarAddr, MachinePointerInfo(),
19908 false, false, false, 0);
19910 // Replace the exact with the load.
19911 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19914 // The replacement was made in place; don't return anything.
19918 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19919 static std::pair<unsigned, bool>
19920 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19921 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19922 if (!VT.isVector())
19923 return std::make_pair(0, false);
19925 bool NeedSplit = false;
19926 switch (VT.getSimpleVT().SimpleTy) {
19927 default: return std::make_pair(0, false);
19931 if (!Subtarget->hasAVX2())
19933 if (!Subtarget->hasAVX())
19934 return std::make_pair(0, false);
19939 if (!Subtarget->hasSSE2())
19940 return std::make_pair(0, false);
19943 // SSE2 has only a small subset of the operations.
19944 bool hasUnsigned = Subtarget->hasSSE41() ||
19945 (Subtarget->hasSSE2() && VT == MVT::v16i8);
19946 bool hasSigned = Subtarget->hasSSE41() ||
19947 (Subtarget->hasSSE2() && VT == MVT::v8i16);
19949 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19952 // Check for x CC y ? x : y.
19953 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19954 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19959 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19962 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19965 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19968 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19970 // Check for x CC y ? y : x -- a min/max with reversed arms.
19971 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19972 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19977 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19980 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19983 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19986 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19990 return std::make_pair(Opc, NeedSplit);
19994 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19995 const X86Subtarget *Subtarget) {
19997 SDValue Cond = N->getOperand(0);
19998 SDValue LHS = N->getOperand(1);
19999 SDValue RHS = N->getOperand(2);
20001 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20002 SDValue CondSrc = Cond->getOperand(0);
20003 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20004 Cond = CondSrc->getOperand(0);
20007 MVT VT = N->getSimpleValueType(0);
20008 MVT EltVT = VT.getVectorElementType();
20009 unsigned NumElems = VT.getVectorNumElements();
20010 // There is no blend with immediate in AVX-512.
20011 if (VT.is512BitVector())
20014 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
20016 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
20019 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20022 unsigned MaskValue = 0;
20023 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20026 SmallVector<int, 8> ShuffleMask(NumElems, -1);
20027 for (unsigned i = 0; i < NumElems; ++i) {
20028 // Be sure we emit undef where we can.
20029 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20030 ShuffleMask[i] = -1;
20032 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20035 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20038 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20040 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20041 TargetLowering::DAGCombinerInfo &DCI,
20042 const X86Subtarget *Subtarget) {
20044 SDValue Cond = N->getOperand(0);
20045 // Get the LHS/RHS of the select.
20046 SDValue LHS = N->getOperand(1);
20047 SDValue RHS = N->getOperand(2);
20048 EVT VT = LHS.getValueType();
20049 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20051 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20052 // instructions match the semantics of the common C idiom x<y?x:y but not
20053 // x<=y?x:y, because of how they handle negative zero (which can be
20054 // ignored in unsafe-math mode).
20055 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20056 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20057 (Subtarget->hasSSE2() ||
20058 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20059 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20061 unsigned Opcode = 0;
20062 // Check for x CC y ? x : y.
20063 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20064 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20068 // Converting this to a min would handle NaNs incorrectly, and swapping
20069 // the operands would cause it to handle comparisons between positive
20070 // and negative zero incorrectly.
20071 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20072 if (!DAG.getTarget().Options.UnsafeFPMath &&
20073 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20075 std::swap(LHS, RHS);
20077 Opcode = X86ISD::FMIN;
20080 // Converting this to a min would handle comparisons between positive
20081 // and negative zero incorrectly.
20082 if (!DAG.getTarget().Options.UnsafeFPMath &&
20083 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20085 Opcode = X86ISD::FMIN;
20088 // Converting this to a min would handle both negative zeros and NaNs
20089 // incorrectly, but we can swap the operands to fix both.
20090 std::swap(LHS, RHS);
20094 Opcode = X86ISD::FMIN;
20098 // Converting this to a max would handle comparisons between positive
20099 // and negative zero incorrectly.
20100 if (!DAG.getTarget().Options.UnsafeFPMath &&
20101 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20103 Opcode = X86ISD::FMAX;
20106 // Converting this to a max would handle NaNs incorrectly, and swapping
20107 // the operands would cause it to handle comparisons between positive
20108 // and negative zero incorrectly.
20109 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20110 if (!DAG.getTarget().Options.UnsafeFPMath &&
20111 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20113 std::swap(LHS, RHS);
20115 Opcode = X86ISD::FMAX;
20118 // Converting this to a max would handle both negative zeros and NaNs
20119 // incorrectly, but we can swap the operands to fix both.
20120 std::swap(LHS, RHS);
20124 Opcode = X86ISD::FMAX;
20127 // Check for x CC y ? y : x -- a min/max with reversed arms.
20128 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20129 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20133 // Converting this to a min would handle comparisons between positive
20134 // and negative zero incorrectly, and swapping the operands would
20135 // cause it to handle NaNs incorrectly.
20136 if (!DAG.getTarget().Options.UnsafeFPMath &&
20137 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20138 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20140 std::swap(LHS, RHS);
20142 Opcode = X86ISD::FMIN;
20145 // Converting this to a min would handle NaNs incorrectly.
20146 if (!DAG.getTarget().Options.UnsafeFPMath &&
20147 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20149 Opcode = X86ISD::FMIN;
20152 // Converting this to a min would handle both negative zeros and NaNs
20153 // incorrectly, but we can swap the operands to fix both.
20154 std::swap(LHS, RHS);
20158 Opcode = X86ISD::FMIN;
20162 // Converting this to a max would handle NaNs incorrectly.
20163 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20165 Opcode = X86ISD::FMAX;
20168 // Converting this to a max would handle comparisons between positive
20169 // and negative zero incorrectly, and swapping the operands would
20170 // cause it to handle NaNs incorrectly.
20171 if (!DAG.getTarget().Options.UnsafeFPMath &&
20172 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20173 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20175 std::swap(LHS, RHS);
20177 Opcode = X86ISD::FMAX;
20180 // Converting this to a max would handle both negative zeros and NaNs
20181 // incorrectly, but we can swap the operands to fix both.
20182 std::swap(LHS, RHS);
20186 Opcode = X86ISD::FMAX;
20192 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20195 EVT CondVT = Cond.getValueType();
20196 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20197 CondVT.getVectorElementType() == MVT::i1) {
20198 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20199 // lowering on AVX-512. In this case we convert it to
20200 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20201 // The same situation for all 128 and 256-bit vectors of i8 and i16
20202 EVT OpVT = LHS.getValueType();
20203 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20204 (OpVT.getVectorElementType() == MVT::i8 ||
20205 OpVT.getVectorElementType() == MVT::i16)) {
20206 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20207 DCI.AddToWorklist(Cond.getNode());
20208 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20211 // If this is a select between two integer constants, try to do some
20213 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20214 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20215 // Don't do this for crazy integer types.
20216 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20217 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20218 // so that TrueC (the true value) is larger than FalseC.
20219 bool NeedsCondInvert = false;
20221 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20222 // Efficiently invertible.
20223 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
20224 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
20225 isa<ConstantSDNode>(Cond.getOperand(1))))) {
20226 NeedsCondInvert = true;
20227 std::swap(TrueC, FalseC);
20230 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
20231 if (FalseC->getAPIntValue() == 0 &&
20232 TrueC->getAPIntValue().isPowerOf2()) {
20233 if (NeedsCondInvert) // Invert the condition if needed.
20234 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20235 DAG.getConstant(1, Cond.getValueType()));
20237 // Zero extend the condition if needed.
20238 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20240 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20241 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20242 DAG.getConstant(ShAmt, MVT::i8));
20245 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20246 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20247 if (NeedsCondInvert) // Invert the condition if needed.
20248 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20249 DAG.getConstant(1, Cond.getValueType()));
20251 // Zero extend the condition if needed.
20252 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20253 FalseC->getValueType(0), Cond);
20254 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20255 SDValue(FalseC, 0));
20258 // Optimize cases that will turn into an LEA instruction. This requires
20259 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20260 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20261 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20262 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20264 bool isFastMultiplier = false;
20266 switch ((unsigned char)Diff) {
20268 case 1: // result = add base, cond
20269 case 2: // result = lea base( , cond*2)
20270 case 3: // result = lea base(cond, cond*2)
20271 case 4: // result = lea base( , cond*4)
20272 case 5: // result = lea base(cond, cond*4)
20273 case 8: // result = lea base( , cond*8)
20274 case 9: // result = lea base(cond, cond*8)
20275 isFastMultiplier = true;
20280 if (isFastMultiplier) {
20281 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20282 if (NeedsCondInvert) // Invert the condition if needed.
20283 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20284 DAG.getConstant(1, Cond.getValueType()));
20286 // Zero extend the condition if needed.
20287 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20289 // Scale the condition by the difference.
20291 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20292 DAG.getConstant(Diff, Cond.getValueType()));
20294 // Add the base if non-zero.
20295 if (FalseC->getAPIntValue() != 0)
20296 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20297 SDValue(FalseC, 0));
20304 // Canonicalize max and min:
20305 // (x > y) ? x : y -> (x >= y) ? x : y
20306 // (x < y) ? x : y -> (x <= y) ? x : y
20307 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20308 // the need for an extra compare
20309 // against zero. e.g.
20310 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20312 // testl %edi, %edi
20314 // cmovgl %edi, %eax
20318 // cmovsl %eax, %edi
20319 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20320 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20321 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20322 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20327 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20328 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20329 Cond.getOperand(0), Cond.getOperand(1), NewCC);
20330 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20335 // Early exit check
20336 if (!TLI.isTypeLegal(VT))
20339 // Match VSELECTs into subs with unsigned saturation.
20340 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20341 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20342 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20343 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20344 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20346 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20347 // left side invert the predicate to simplify logic below.
20349 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20351 CC = ISD::getSetCCInverse(CC, true);
20352 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20356 if (Other.getNode() && Other->getNumOperands() == 2 &&
20357 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20358 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20359 SDValue CondRHS = Cond->getOperand(1);
20361 // Look for a general sub with unsigned saturation first.
20362 // x >= y ? x-y : 0 --> subus x, y
20363 // x > y ? x-y : 0 --> subus x, y
20364 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20365 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20366 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20368 if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20369 if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20370 if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20371 if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20372 // If the RHS is a constant we have to reverse the const
20373 // canonicalization.
20374 // x > C-1 ? x+-C : 0 --> subus x, C
20375 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20376 CondRHSConst->getAPIntValue() ==
20377 (-OpRHSConst->getAPIntValue() - 1))
20378 return DAG.getNode(
20379 X86ISD::SUBUS, DL, VT, OpLHS,
20380 DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20382 // Another special case: If C was a sign bit, the sub has been
20383 // canonicalized into a xor.
20384 // FIXME: Would it be better to use computeKnownBits to determine
20385 // whether it's safe to decanonicalize the xor?
20386 // x s< 0 ? x^C : 0 --> subus x, C
20387 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20388 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20389 OpRHSConst->getAPIntValue().isSignBit())
20390 // Note that we have to rebuild the RHS constant here to ensure we
20391 // don't rely on particular values of undef lanes.
20392 return DAG.getNode(
20393 X86ISD::SUBUS, DL, VT, OpLHS,
20394 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20399 // Try to match a min/max vector operation.
20400 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20401 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20402 unsigned Opc = ret.first;
20403 bool NeedSplit = ret.second;
20405 if (Opc && NeedSplit) {
20406 unsigned NumElems = VT.getVectorNumElements();
20407 // Extract the LHS vectors
20408 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20409 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20411 // Extract the RHS vectors
20412 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20413 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20415 // Create min/max for each subvector
20416 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20417 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20419 // Merge the result
20420 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20422 return DAG.getNode(Opc, DL, VT, LHS, RHS);
20425 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20426 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20427 // Check if SETCC has already been promoted
20428 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20429 // Check that condition value type matches vselect operand type
20432 assert(Cond.getValueType().isVector() &&
20433 "vector select expects a vector selector!");
20435 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20436 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20438 if (!TValIsAllOnes && !FValIsAllZeros) {
20439 // Try invert the condition if true value is not all 1s and false value
20441 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20442 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20444 if (TValIsAllZeros || FValIsAllOnes) {
20445 SDValue CC = Cond.getOperand(2);
20446 ISD::CondCode NewCC =
20447 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20448 Cond.getOperand(0).getValueType().isInteger());
20449 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20450 std::swap(LHS, RHS);
20451 TValIsAllOnes = FValIsAllOnes;
20452 FValIsAllZeros = TValIsAllZeros;
20456 if (TValIsAllOnes || FValIsAllZeros) {
20459 if (TValIsAllOnes && FValIsAllZeros)
20461 else if (TValIsAllOnes)
20462 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20463 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20464 else if (FValIsAllZeros)
20465 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20466 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20468 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20472 // Try to fold this VSELECT into a MOVSS/MOVSD
20473 if (N->getOpcode() == ISD::VSELECT &&
20474 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20475 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20476 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20477 bool CanFold = false;
20478 unsigned NumElems = Cond.getNumOperands();
20482 if (isZero(Cond.getOperand(0))) {
20485 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20486 // fold (vselect <0,-1> -> (movsd A, B)
20487 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20488 CanFold = isAllOnes(Cond.getOperand(i));
20489 } else if (isAllOnes(Cond.getOperand(0))) {
20493 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20494 // fold (vselect <-1,0> -> (movsd B, A)
20495 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20496 CanFold = isZero(Cond.getOperand(i));
20500 if (VT == MVT::v4i32 || VT == MVT::v4f32)
20501 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20502 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20505 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20506 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20507 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20508 // (v2i64 (bitcast B)))))
20510 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20511 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20512 // (v2f64 (bitcast B)))))
20514 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20515 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20516 // (v2i64 (bitcast A)))))
20518 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20519 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20520 // (v2f64 (bitcast A)))))
20522 CanFold = (isZero(Cond.getOperand(0)) &&
20523 isZero(Cond.getOperand(1)) &&
20524 isAllOnes(Cond.getOperand(2)) &&
20525 isAllOnes(Cond.getOperand(3)));
20527 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20528 isAllOnes(Cond.getOperand(1)) &&
20529 isZero(Cond.getOperand(2)) &&
20530 isZero(Cond.getOperand(3))) {
20532 std::swap(LHS, RHS);
20536 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20537 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20538 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20539 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20541 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20547 // If we know that this node is legal then we know that it is going to be
20548 // matched by one of the SSE/AVX BLEND instructions. These instructions only
20549 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20550 // to simplify previous instructions.
20551 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20552 !DCI.isBeforeLegalize() &&
20553 // We explicitly check against v8i16 and v16i16 because, although
20554 // they're marked as Custom, they might only be legal when Cond is a
20555 // build_vector of constants. This will be taken care in a later
20557 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20558 VT != MVT::v8i16)) {
20559 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20561 // Don't optimize vector selects that map to mask-registers.
20565 // Check all uses of that condition operand to check whether it will be
20566 // consumed by non-BLEND instructions, which may depend on all bits are set
20568 for (SDNode::use_iterator I = Cond->use_begin(),
20569 E = Cond->use_end(); I != E; ++I)
20570 if (I->getOpcode() != ISD::VSELECT)
20571 // TODO: Add other opcodes eventually lowered into BLEND.
20574 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20575 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20577 APInt KnownZero, KnownOne;
20578 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20579 DCI.isBeforeLegalizeOps());
20580 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20581 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20582 DCI.CommitTargetLoweringOpt(TLO);
20585 // We should generate an X86ISD::BLENDI from a vselect if its argument
20586 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20587 // constants. This specific pattern gets generated when we split a
20588 // selector for a 512 bit vector in a machine without AVX512 (but with
20589 // 256-bit vectors), during legalization:
20591 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20593 // Iff we find this pattern and the build_vectors are built from
20594 // constants, we translate the vselect into a shuffle_vector that we
20595 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20596 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20597 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20598 if (Shuffle.getNode())
20605 // Check whether a boolean test is testing a boolean value generated by
20606 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20609 // Simplify the following patterns:
20610 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20611 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20612 // to (Op EFLAGS Cond)
20614 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20615 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20616 // to (Op EFLAGS !Cond)
20618 // where Op could be BRCOND or CMOV.
20620 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20621 // Quit if not CMP and SUB with its value result used.
20622 if (Cmp.getOpcode() != X86ISD::CMP &&
20623 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20626 // Quit if not used as a boolean value.
20627 if (CC != X86::COND_E && CC != X86::COND_NE)
20630 // Check CMP operands. One of them should be 0 or 1 and the other should be
20631 // an SetCC or extended from it.
20632 SDValue Op1 = Cmp.getOperand(0);
20633 SDValue Op2 = Cmp.getOperand(1);
20636 const ConstantSDNode* C = nullptr;
20637 bool needOppositeCond = (CC == X86::COND_E);
20638 bool checkAgainstTrue = false; // Is it a comparison against 1?
20640 if ((C = dyn_cast<ConstantSDNode>(Op1)))
20642 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20644 else // Quit if all operands are not constants.
20647 if (C->getZExtValue() == 1) {
20648 needOppositeCond = !needOppositeCond;
20649 checkAgainstTrue = true;
20650 } else if (C->getZExtValue() != 0)
20651 // Quit if the constant is neither 0 or 1.
20654 bool truncatedToBoolWithAnd = false;
20655 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20656 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20657 SetCC.getOpcode() == ISD::TRUNCATE ||
20658 SetCC.getOpcode() == ISD::AND) {
20659 if (SetCC.getOpcode() == ISD::AND) {
20661 ConstantSDNode *CS;
20662 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20663 CS->getZExtValue() == 1)
20665 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20666 CS->getZExtValue() == 1)
20670 SetCC = SetCC.getOperand(OpIdx);
20671 truncatedToBoolWithAnd = true;
20673 SetCC = SetCC.getOperand(0);
20676 switch (SetCC.getOpcode()) {
20677 case X86ISD::SETCC_CARRY:
20678 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20679 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20680 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20681 // truncated to i1 using 'and'.
20682 if (checkAgainstTrue && !truncatedToBoolWithAnd)
20684 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20685 "Invalid use of SETCC_CARRY!");
20687 case X86ISD::SETCC:
20688 // Set the condition code or opposite one if necessary.
20689 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20690 if (needOppositeCond)
20691 CC = X86::GetOppositeBranchCondition(CC);
20692 return SetCC.getOperand(1);
20693 case X86ISD::CMOV: {
20694 // Check whether false/true value has canonical one, i.e. 0 or 1.
20695 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20696 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20697 // Quit if true value is not a constant.
20700 // Quit if false value is not a constant.
20702 SDValue Op = SetCC.getOperand(0);
20703 // Skip 'zext' or 'trunc' node.
20704 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20705 Op.getOpcode() == ISD::TRUNCATE)
20706 Op = Op.getOperand(0);
20707 // A special case for rdrand/rdseed, where 0 is set if false cond is
20709 if ((Op.getOpcode() != X86ISD::RDRAND &&
20710 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20713 // Quit if false value is not the constant 0 or 1.
20714 bool FValIsFalse = true;
20715 if (FVal && FVal->getZExtValue() != 0) {
20716 if (FVal->getZExtValue() != 1)
20718 // If FVal is 1, opposite cond is needed.
20719 needOppositeCond = !needOppositeCond;
20720 FValIsFalse = false;
20722 // Quit if TVal is not the constant opposite of FVal.
20723 if (FValIsFalse && TVal->getZExtValue() != 1)
20725 if (!FValIsFalse && TVal->getZExtValue() != 0)
20727 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20728 if (needOppositeCond)
20729 CC = X86::GetOppositeBranchCondition(CC);
20730 return SetCC.getOperand(3);
20737 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20738 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20739 TargetLowering::DAGCombinerInfo &DCI,
20740 const X86Subtarget *Subtarget) {
20743 // If the flag operand isn't dead, don't touch this CMOV.
20744 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20747 SDValue FalseOp = N->getOperand(0);
20748 SDValue TrueOp = N->getOperand(1);
20749 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20750 SDValue Cond = N->getOperand(3);
20752 if (CC == X86::COND_E || CC == X86::COND_NE) {
20753 switch (Cond.getOpcode()) {
20757 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20758 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20759 return (CC == X86::COND_E) ? FalseOp : TrueOp;
20765 Flags = checkBoolTestSetCCCombine(Cond, CC);
20766 if (Flags.getNode() &&
20767 // Extra check as FCMOV only supports a subset of X86 cond.
20768 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20769 SDValue Ops[] = { FalseOp, TrueOp,
20770 DAG.getConstant(CC, MVT::i8), Flags };
20771 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20774 // If this is a select between two integer constants, try to do some
20775 // optimizations. Note that the operands are ordered the opposite of SELECT
20777 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20778 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20779 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20780 // larger than FalseC (the false value).
20781 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20782 CC = X86::GetOppositeBranchCondition(CC);
20783 std::swap(TrueC, FalseC);
20784 std::swap(TrueOp, FalseOp);
20787 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
20788 // This is efficient for any integer data type (including i8/i16) and
20790 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20791 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20792 DAG.getConstant(CC, MVT::i8), Cond);
20794 // Zero extend the condition if needed.
20795 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20797 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20798 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20799 DAG.getConstant(ShAmt, MVT::i8));
20800 if (N->getNumValues() == 2) // Dead flag value?
20801 return DCI.CombineTo(N, Cond, SDValue());
20805 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
20806 // for any integer data type, including i8/i16.
20807 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20808 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20809 DAG.getConstant(CC, MVT::i8), Cond);
20811 // Zero extend the condition if needed.
20812 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20813 FalseC->getValueType(0), Cond);
20814 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20815 SDValue(FalseC, 0));
20817 if (N->getNumValues() == 2) // Dead flag value?
20818 return DCI.CombineTo(N, Cond, SDValue());
20822 // Optimize cases that will turn into an LEA instruction. This requires
20823 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20824 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20825 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20826 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20828 bool isFastMultiplier = false;
20830 switch ((unsigned char)Diff) {
20832 case 1: // result = add base, cond
20833 case 2: // result = lea base( , cond*2)
20834 case 3: // result = lea base(cond, cond*2)
20835 case 4: // result = lea base( , cond*4)
20836 case 5: // result = lea base(cond, cond*4)
20837 case 8: // result = lea base( , cond*8)
20838 case 9: // result = lea base(cond, cond*8)
20839 isFastMultiplier = true;
20844 if (isFastMultiplier) {
20845 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20846 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20847 DAG.getConstant(CC, MVT::i8), Cond);
20848 // Zero extend the condition if needed.
20849 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20851 // Scale the condition by the difference.
20853 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20854 DAG.getConstant(Diff, Cond.getValueType()));
20856 // Add the base if non-zero.
20857 if (FalseC->getAPIntValue() != 0)
20858 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20859 SDValue(FalseC, 0));
20860 if (N->getNumValues() == 2) // Dead flag value?
20861 return DCI.CombineTo(N, Cond, SDValue());
20868 // Handle these cases:
20869 // (select (x != c), e, c) -> select (x != c), e, x),
20870 // (select (x == c), c, e) -> select (x == c), x, e)
20871 // where the c is an integer constant, and the "select" is the combination
20872 // of CMOV and CMP.
20874 // The rationale for this change is that the conditional-move from a constant
20875 // needs two instructions, however, conditional-move from a register needs
20876 // only one instruction.
20878 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20879 // some instruction-combining opportunities. This opt needs to be
20880 // postponed as late as possible.
20882 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20883 // the DCI.xxxx conditions are provided to postpone the optimization as
20884 // late as possible.
20886 ConstantSDNode *CmpAgainst = nullptr;
20887 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20888 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20889 !isa<ConstantSDNode>(Cond.getOperand(0))) {
20891 if (CC == X86::COND_NE &&
20892 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20893 CC = X86::GetOppositeBranchCondition(CC);
20894 std::swap(TrueOp, FalseOp);
20897 if (CC == X86::COND_E &&
20898 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20899 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20900 DAG.getConstant(CC, MVT::i8), Cond };
20901 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20909 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20910 const X86Subtarget *Subtarget) {
20911 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20913 default: return SDValue();
20914 // SSE/AVX/AVX2 blend intrinsics.
20915 case Intrinsic::x86_avx2_pblendvb:
20916 case Intrinsic::x86_avx2_pblendw:
20917 case Intrinsic::x86_avx2_pblendd_128:
20918 case Intrinsic::x86_avx2_pblendd_256:
20919 // Don't try to simplify this intrinsic if we don't have AVX2.
20920 if (!Subtarget->hasAVX2())
20923 case Intrinsic::x86_avx_blend_pd_256:
20924 case Intrinsic::x86_avx_blend_ps_256:
20925 case Intrinsic::x86_avx_blendv_pd_256:
20926 case Intrinsic::x86_avx_blendv_ps_256:
20927 // Don't try to simplify this intrinsic if we don't have AVX.
20928 if (!Subtarget->hasAVX())
20931 case Intrinsic::x86_sse41_pblendw:
20932 case Intrinsic::x86_sse41_blendpd:
20933 case Intrinsic::x86_sse41_blendps:
20934 case Intrinsic::x86_sse41_blendvps:
20935 case Intrinsic::x86_sse41_blendvpd:
20936 case Intrinsic::x86_sse41_pblendvb: {
20937 SDValue Op0 = N->getOperand(1);
20938 SDValue Op1 = N->getOperand(2);
20939 SDValue Mask = N->getOperand(3);
20941 // Don't try to simplify this intrinsic if we don't have SSE4.1.
20942 if (!Subtarget->hasSSE41())
20945 // fold (blend A, A, Mask) -> A
20948 // fold (blend A, B, allZeros) -> A
20949 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20951 // fold (blend A, B, allOnes) -> B
20952 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20955 // Simplify the case where the mask is a constant i32 value.
20956 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20957 if (C->isNullValue())
20959 if (C->isAllOnesValue())
20966 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20967 case Intrinsic::x86_sse2_psrai_w:
20968 case Intrinsic::x86_sse2_psrai_d:
20969 case Intrinsic::x86_avx2_psrai_w:
20970 case Intrinsic::x86_avx2_psrai_d:
20971 case Intrinsic::x86_sse2_psra_w:
20972 case Intrinsic::x86_sse2_psra_d:
20973 case Intrinsic::x86_avx2_psra_w:
20974 case Intrinsic::x86_avx2_psra_d: {
20975 SDValue Op0 = N->getOperand(1);
20976 SDValue Op1 = N->getOperand(2);
20977 EVT VT = Op0.getValueType();
20978 assert(VT.isVector() && "Expected a vector type!");
20980 if (isa<BuildVectorSDNode>(Op1))
20981 Op1 = Op1.getOperand(0);
20983 if (!isa<ConstantSDNode>(Op1))
20986 EVT SVT = VT.getVectorElementType();
20987 unsigned SVTBits = SVT.getSizeInBits();
20989 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20990 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20991 uint64_t ShAmt = C.getZExtValue();
20993 // Don't try to convert this shift into a ISD::SRA if the shift
20994 // count is bigger than or equal to the element size.
20995 if (ShAmt >= SVTBits)
20998 // Trivial case: if the shift count is zero, then fold this
20999 // into the first operand.
21003 // Replace this packed shift intrinsic with a target independent
21005 SDValue Splat = DAG.getConstant(C, VT);
21006 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21011 /// PerformMulCombine - Optimize a single multiply with constant into two
21012 /// in order to implement it with two cheaper instructions, e.g.
21013 /// LEA + SHL, LEA + LEA.
21014 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21015 TargetLowering::DAGCombinerInfo &DCI) {
21016 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21019 EVT VT = N->getValueType(0);
21020 if (VT != MVT::i64)
21023 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21026 uint64_t MulAmt = C->getZExtValue();
21027 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21030 uint64_t MulAmt1 = 0;
21031 uint64_t MulAmt2 = 0;
21032 if ((MulAmt % 9) == 0) {
21034 MulAmt2 = MulAmt / 9;
21035 } else if ((MulAmt % 5) == 0) {
21037 MulAmt2 = MulAmt / 5;
21038 } else if ((MulAmt % 3) == 0) {
21040 MulAmt2 = MulAmt / 3;
21043 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21046 if (isPowerOf2_64(MulAmt2) &&
21047 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21048 // If second multiplifer is pow2, issue it first. We want the multiply by
21049 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21051 std::swap(MulAmt1, MulAmt2);
21054 if (isPowerOf2_64(MulAmt1))
21055 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21056 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21058 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21059 DAG.getConstant(MulAmt1, VT));
21061 if (isPowerOf2_64(MulAmt2))
21062 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21063 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21065 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21066 DAG.getConstant(MulAmt2, VT));
21068 // Do not add new nodes to DAG combiner worklist.
21069 DCI.CombineTo(N, NewMul, false);
21074 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21075 SDValue N0 = N->getOperand(0);
21076 SDValue N1 = N->getOperand(1);
21077 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21078 EVT VT = N0.getValueType();
21080 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21081 // since the result of setcc_c is all zero's or all ones.
21082 if (VT.isInteger() && !VT.isVector() &&
21083 N1C && N0.getOpcode() == ISD::AND &&
21084 N0.getOperand(1).getOpcode() == ISD::Constant) {
21085 SDValue N00 = N0.getOperand(0);
21086 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21087 ((N00.getOpcode() == ISD::ANY_EXTEND ||
21088 N00.getOpcode() == ISD::ZERO_EXTEND) &&
21089 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21090 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21091 APInt ShAmt = N1C->getAPIntValue();
21092 Mask = Mask.shl(ShAmt);
21094 return DAG.getNode(ISD::AND, SDLoc(N), VT,
21095 N00, DAG.getConstant(Mask, VT));
21099 // Hardware support for vector shifts is sparse which makes us scalarize the
21100 // vector operations in many cases. Also, on sandybridge ADD is faster than
21102 // (shl V, 1) -> add V,V
21103 if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21104 if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21105 assert(N0.getValueType().isVector() && "Invalid vector shift type");
21106 // We shift all of the values by one. In many cases we do not have
21107 // hardware support for this operation. This is better expressed as an ADD
21109 if (N1SplatC->getZExtValue() == 1)
21110 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21116 /// \brief Returns a vector of 0s if the node in input is a vector logical
21117 /// shift by a constant amount which is known to be bigger than or equal
21118 /// to the vector element size in bits.
21119 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21120 const X86Subtarget *Subtarget) {
21121 EVT VT = N->getValueType(0);
21123 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21124 (!Subtarget->hasInt256() ||
21125 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21128 SDValue Amt = N->getOperand(1);
21130 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21131 if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21132 APInt ShiftAmt = AmtSplat->getAPIntValue();
21133 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21135 // SSE2/AVX2 logical shifts always return a vector of 0s
21136 // if the shift amount is bigger than or equal to
21137 // the element size. The constant shift amount will be
21138 // encoded as a 8-bit immediate.
21139 if (ShiftAmt.trunc(8).uge(MaxAmount))
21140 return getZeroVector(VT, Subtarget, DAG, DL);
21146 /// PerformShiftCombine - Combine shifts.
21147 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21148 TargetLowering::DAGCombinerInfo &DCI,
21149 const X86Subtarget *Subtarget) {
21150 if (N->getOpcode() == ISD::SHL) {
21151 SDValue V = PerformSHLCombine(N, DAG);
21152 if (V.getNode()) return V;
21155 if (N->getOpcode() != ISD::SRA) {
21156 // Try to fold this logical shift into a zero vector.
21157 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21158 if (V.getNode()) return V;
21164 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
21165 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21166 // and friends. Likewise for OR -> CMPNEQSS.
21167 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21168 TargetLowering::DAGCombinerInfo &DCI,
21169 const X86Subtarget *Subtarget) {
21172 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21173 // we're requiring SSE2 for both.
21174 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21175 SDValue N0 = N->getOperand(0);
21176 SDValue N1 = N->getOperand(1);
21177 SDValue CMP0 = N0->getOperand(1);
21178 SDValue CMP1 = N1->getOperand(1);
21181 // The SETCCs should both refer to the same CMP.
21182 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21185 SDValue CMP00 = CMP0->getOperand(0);
21186 SDValue CMP01 = CMP0->getOperand(1);
21187 EVT VT = CMP00.getValueType();
21189 if (VT == MVT::f32 || VT == MVT::f64) {
21190 bool ExpectingFlags = false;
21191 // Check for any users that want flags:
21192 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21193 !ExpectingFlags && UI != UE; ++UI)
21194 switch (UI->getOpcode()) {
21199 ExpectingFlags = true;
21201 case ISD::CopyToReg:
21202 case ISD::SIGN_EXTEND:
21203 case ISD::ZERO_EXTEND:
21204 case ISD::ANY_EXTEND:
21208 if (!ExpectingFlags) {
21209 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21210 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21212 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21213 X86::CondCode tmp = cc0;
21218 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
21219 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21220 // FIXME: need symbolic constants for these magic numbers.
21221 // See X86ATTInstPrinter.cpp:printSSECC().
21222 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21223 if (Subtarget->hasAVX512()) {
21224 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21225 CMP01, DAG.getConstant(x86cc, MVT::i8));
21226 if (N->getValueType(0) != MVT::i1)
21227 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21231 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21232 CMP00.getValueType(), CMP00, CMP01,
21233 DAG.getConstant(x86cc, MVT::i8));
21235 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21236 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21238 if (is64BitFP && !Subtarget->is64Bit()) {
21239 // On a 32-bit target, we cannot bitcast the 64-bit float to a
21240 // 64-bit integer, since that's not a legal type. Since
21241 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21242 // bits, but can do this little dance to extract the lowest 32 bits
21243 // and work with those going forward.
21244 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21246 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21248 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21249 Vector32, DAG.getIntPtrConstant(0));
21253 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21254 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21255 DAG.getConstant(1, IntVT));
21256 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21257 return OneBitOfTruth;
21265 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21266 /// so it can be folded inside ANDNP.
21267 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21268 EVT VT = N->getValueType(0);
21270 // Match direct AllOnes for 128 and 256-bit vectors
21271 if (ISD::isBuildVectorAllOnes(N))
21274 // Look through a bit convert.
21275 if (N->getOpcode() == ISD::BITCAST)
21276 N = N->getOperand(0).getNode();
21278 // Sometimes the operand may come from a insert_subvector building a 256-bit
21280 if (VT.is256BitVector() &&
21281 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21282 SDValue V1 = N->getOperand(0);
21283 SDValue V2 = N->getOperand(1);
21285 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21286 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21287 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21288 ISD::isBuildVectorAllOnes(V2.getNode()))
21295 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21296 // register. In most cases we actually compare or select YMM-sized registers
21297 // and mixing the two types creates horrible code. This method optimizes
21298 // some of the transition sequences.
21299 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21300 TargetLowering::DAGCombinerInfo &DCI,
21301 const X86Subtarget *Subtarget) {
21302 EVT VT = N->getValueType(0);
21303 if (!VT.is256BitVector())
21306 assert((N->getOpcode() == ISD::ANY_EXTEND ||
21307 N->getOpcode() == ISD::ZERO_EXTEND ||
21308 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21310 SDValue Narrow = N->getOperand(0);
21311 EVT NarrowVT = Narrow->getValueType(0);
21312 if (!NarrowVT.is128BitVector())
21315 if (Narrow->getOpcode() != ISD::XOR &&
21316 Narrow->getOpcode() != ISD::AND &&
21317 Narrow->getOpcode() != ISD::OR)
21320 SDValue N0 = Narrow->getOperand(0);
21321 SDValue N1 = Narrow->getOperand(1);
21324 // The Left side has to be a trunc.
21325 if (N0.getOpcode() != ISD::TRUNCATE)
21328 // The type of the truncated inputs.
21329 EVT WideVT = N0->getOperand(0)->getValueType(0);
21333 // The right side has to be a 'trunc' or a constant vector.
21334 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21335 ConstantSDNode *RHSConstSplat = nullptr;
21336 if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21337 RHSConstSplat = RHSBV->getConstantSplatNode();
21338 if (!RHSTrunc && !RHSConstSplat)
21341 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21343 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21346 // Set N0 and N1 to hold the inputs to the new wide operation.
21347 N0 = N0->getOperand(0);
21348 if (RHSConstSplat) {
21349 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21350 SDValue(RHSConstSplat, 0));
21351 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21352 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21353 } else if (RHSTrunc) {
21354 N1 = N1->getOperand(0);
21357 // Generate the wide operation.
21358 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21359 unsigned Opcode = N->getOpcode();
21361 case ISD::ANY_EXTEND:
21363 case ISD::ZERO_EXTEND: {
21364 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21365 APInt Mask = APInt::getAllOnesValue(InBits);
21366 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21367 return DAG.getNode(ISD::AND, DL, VT,
21368 Op, DAG.getConstant(Mask, VT));
21370 case ISD::SIGN_EXTEND:
21371 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21372 Op, DAG.getValueType(NarrowVT));
21374 llvm_unreachable("Unexpected opcode");
21378 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21379 TargetLowering::DAGCombinerInfo &DCI,
21380 const X86Subtarget *Subtarget) {
21381 EVT VT = N->getValueType(0);
21382 if (DCI.isBeforeLegalizeOps())
21385 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21389 // Create BEXTR instructions
21390 // BEXTR is ((X >> imm) & (2**size-1))
21391 if (VT == MVT::i32 || VT == MVT::i64) {
21392 SDValue N0 = N->getOperand(0);
21393 SDValue N1 = N->getOperand(1);
21396 // Check for BEXTR.
21397 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21398 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21399 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21400 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21401 if (MaskNode && ShiftNode) {
21402 uint64_t Mask = MaskNode->getZExtValue();
21403 uint64_t Shift = ShiftNode->getZExtValue();
21404 if (isMask_64(Mask)) {
21405 uint64_t MaskSize = CountPopulation_64(Mask);
21406 if (Shift + MaskSize <= VT.getSizeInBits())
21407 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21408 DAG.getConstant(Shift | (MaskSize << 8), VT));
21416 // Want to form ANDNP nodes:
21417 // 1) In the hopes of then easily combining them with OR and AND nodes
21418 // to form PBLEND/PSIGN.
21419 // 2) To match ANDN packed intrinsics
21420 if (VT != MVT::v2i64 && VT != MVT::v4i64)
21423 SDValue N0 = N->getOperand(0);
21424 SDValue N1 = N->getOperand(1);
21427 // Check LHS for vnot
21428 if (N0.getOpcode() == ISD::XOR &&
21429 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21430 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21431 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21433 // Check RHS for vnot
21434 if (N1.getOpcode() == ISD::XOR &&
21435 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21436 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21437 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21442 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21443 TargetLowering::DAGCombinerInfo &DCI,
21444 const X86Subtarget *Subtarget) {
21445 if (DCI.isBeforeLegalizeOps())
21448 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21452 SDValue N0 = N->getOperand(0);
21453 SDValue N1 = N->getOperand(1);
21454 EVT VT = N->getValueType(0);
21456 // look for psign/blend
21457 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21458 if (!Subtarget->hasSSSE3() ||
21459 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21462 // Canonicalize pandn to RHS
21463 if (N0.getOpcode() == X86ISD::ANDNP)
21465 // or (and (m, y), (pandn m, x))
21466 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21467 SDValue Mask = N1.getOperand(0);
21468 SDValue X = N1.getOperand(1);
21470 if (N0.getOperand(0) == Mask)
21471 Y = N0.getOperand(1);
21472 if (N0.getOperand(1) == Mask)
21473 Y = N0.getOperand(0);
21475 // Check to see if the mask appeared in both the AND and ANDNP and
21479 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21480 // Look through mask bitcast.
21481 if (Mask.getOpcode() == ISD::BITCAST)
21482 Mask = Mask.getOperand(0);
21483 if (X.getOpcode() == ISD::BITCAST)
21484 X = X.getOperand(0);
21485 if (Y.getOpcode() == ISD::BITCAST)
21486 Y = Y.getOperand(0);
21488 EVT MaskVT = Mask.getValueType();
21490 // Validate that the Mask operand is a vector sra node.
21491 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21492 // there is no psrai.b
21493 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21494 unsigned SraAmt = ~0;
21495 if (Mask.getOpcode() == ISD::SRA) {
21496 if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21497 if (auto *AmtConst = AmtBV->getConstantSplatNode())
21498 SraAmt = AmtConst->getZExtValue();
21499 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21500 SDValue SraC = Mask.getOperand(1);
21501 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
21503 if ((SraAmt + 1) != EltBits)
21508 // Now we know we at least have a plendvb with the mask val. See if
21509 // we can form a psignb/w/d.
21510 // psign = x.type == y.type == mask.type && y = sub(0, x);
21511 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21512 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21513 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21514 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21515 "Unsupported VT for PSIGN");
21516 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21517 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21519 // PBLENDVB only available on SSE 4.1
21520 if (!Subtarget->hasSSE41())
21523 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21525 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21526 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21527 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21528 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21529 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21533 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21536 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21537 MachineFunction &MF = DAG.getMachineFunction();
21538 bool OptForSize = MF.getFunction()->getAttributes().
21539 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21541 // SHLD/SHRD instructions have lower register pressure, but on some
21542 // platforms they have higher latency than the equivalent
21543 // series of shifts/or that would otherwise be generated.
21544 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21545 // have higher latencies and we are not optimizing for size.
21546 if (!OptForSize && Subtarget->isSHLDSlow())
21549 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21551 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21553 if (!N0.hasOneUse() || !N1.hasOneUse())
21556 SDValue ShAmt0 = N0.getOperand(1);
21557 if (ShAmt0.getValueType() != MVT::i8)
21559 SDValue ShAmt1 = N1.getOperand(1);
21560 if (ShAmt1.getValueType() != MVT::i8)
21562 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21563 ShAmt0 = ShAmt0.getOperand(0);
21564 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21565 ShAmt1 = ShAmt1.getOperand(0);
21568 unsigned Opc = X86ISD::SHLD;
21569 SDValue Op0 = N0.getOperand(0);
21570 SDValue Op1 = N1.getOperand(0);
21571 if (ShAmt0.getOpcode() == ISD::SUB) {
21572 Opc = X86ISD::SHRD;
21573 std::swap(Op0, Op1);
21574 std::swap(ShAmt0, ShAmt1);
21577 unsigned Bits = VT.getSizeInBits();
21578 if (ShAmt1.getOpcode() == ISD::SUB) {
21579 SDValue Sum = ShAmt1.getOperand(0);
21580 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21581 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21582 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21583 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21584 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21585 return DAG.getNode(Opc, DL, VT,
21587 DAG.getNode(ISD::TRUNCATE, DL,
21590 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21591 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21593 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21594 return DAG.getNode(Opc, DL, VT,
21595 N0.getOperand(0), N1.getOperand(0),
21596 DAG.getNode(ISD::TRUNCATE, DL,
21603 // Generate NEG and CMOV for integer abs.
21604 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21605 EVT VT = N->getValueType(0);
21607 // Since X86 does not have CMOV for 8-bit integer, we don't convert
21608 // 8-bit integer abs to NEG and CMOV.
21609 if (VT.isInteger() && VT.getSizeInBits() == 8)
21612 SDValue N0 = N->getOperand(0);
21613 SDValue N1 = N->getOperand(1);
21616 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21617 // and change it to SUB and CMOV.
21618 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21619 N0.getOpcode() == ISD::ADD &&
21620 N0.getOperand(1) == N1 &&
21621 N1.getOpcode() == ISD::SRA &&
21622 N1.getOperand(0) == N0.getOperand(0))
21623 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21624 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21625 // Generate SUB & CMOV.
21626 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21627 DAG.getConstant(0, VT), N0.getOperand(0));
21629 SDValue Ops[] = { N0.getOperand(0), Neg,
21630 DAG.getConstant(X86::COND_GE, MVT::i8),
21631 SDValue(Neg.getNode(), 1) };
21632 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21637 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21638 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21639 TargetLowering::DAGCombinerInfo &DCI,
21640 const X86Subtarget *Subtarget) {
21641 if (DCI.isBeforeLegalizeOps())
21644 if (Subtarget->hasCMov()) {
21645 SDValue RV = performIntegerAbsCombine(N, DAG);
21653 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21654 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21655 TargetLowering::DAGCombinerInfo &DCI,
21656 const X86Subtarget *Subtarget) {
21657 LoadSDNode *Ld = cast<LoadSDNode>(N);
21658 EVT RegVT = Ld->getValueType(0);
21659 EVT MemVT = Ld->getMemoryVT();
21661 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21663 // On Sandybridge unaligned 256bit loads are inefficient.
21664 ISD::LoadExtType Ext = Ld->getExtensionType();
21665 unsigned Alignment = Ld->getAlignment();
21666 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21667 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21668 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21669 unsigned NumElems = RegVT.getVectorNumElements();
21673 SDValue Ptr = Ld->getBasePtr();
21674 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21676 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21678 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21679 Ld->getPointerInfo(), Ld->isVolatile(),
21680 Ld->isNonTemporal(), Ld->isInvariant(),
21682 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21683 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21684 Ld->getPointerInfo(), Ld->isVolatile(),
21685 Ld->isNonTemporal(), Ld->isInvariant(),
21686 std::min(16U, Alignment));
21687 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21689 Load2.getValue(1));
21691 SDValue NewVec = DAG.getUNDEF(RegVT);
21692 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21693 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21694 return DCI.CombineTo(N, NewVec, TF, true);
21700 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21701 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21702 const X86Subtarget *Subtarget) {
21703 StoreSDNode *St = cast<StoreSDNode>(N);
21704 EVT VT = St->getValue().getValueType();
21705 EVT StVT = St->getMemoryVT();
21707 SDValue StoredVal = St->getOperand(1);
21708 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21710 // If we are saving a concatenation of two XMM registers, perform two stores.
21711 // On Sandy Bridge, 256-bit memory operations are executed by two
21712 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21713 // memory operation.
21714 unsigned Alignment = St->getAlignment();
21715 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21716 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21717 StVT == VT && !IsAligned) {
21718 unsigned NumElems = VT.getVectorNumElements();
21722 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21723 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21725 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21726 SDValue Ptr0 = St->getBasePtr();
21727 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21729 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21730 St->getPointerInfo(), St->isVolatile(),
21731 St->isNonTemporal(), Alignment);
21732 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21733 St->getPointerInfo(), St->isVolatile(),
21734 St->isNonTemporal(),
21735 std::min(16U, Alignment));
21736 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21739 // Optimize trunc store (of multiple scalars) to shuffle and store.
21740 // First, pack all of the elements in one place. Next, store to memory
21741 // in fewer chunks.
21742 if (St->isTruncatingStore() && VT.isVector()) {
21743 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21744 unsigned NumElems = VT.getVectorNumElements();
21745 assert(StVT != VT && "Cannot truncate to the same type");
21746 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21747 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21749 // From, To sizes and ElemCount must be pow of two
21750 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21751 // We are going to use the original vector elt for storing.
21752 // Accumulated smaller vector elements must be a multiple of the store size.
21753 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21755 unsigned SizeRatio = FromSz / ToSz;
21757 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21759 // Create a type on which we perform the shuffle
21760 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21761 StVT.getScalarType(), NumElems*SizeRatio);
21763 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21765 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21766 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21767 for (unsigned i = 0; i != NumElems; ++i)
21768 ShuffleVec[i] = i * SizeRatio;
21770 // Can't shuffle using an illegal type.
21771 if (!TLI.isTypeLegal(WideVecVT))
21774 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21775 DAG.getUNDEF(WideVecVT),
21777 // At this point all of the data is stored at the bottom of the
21778 // register. We now need to save it to mem.
21780 // Find the largest store unit
21781 MVT StoreType = MVT::i8;
21782 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21783 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21784 MVT Tp = (MVT::SimpleValueType)tp;
21785 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21789 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21790 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21791 (64 <= NumElems * ToSz))
21792 StoreType = MVT::f64;
21794 // Bitcast the original vector into a vector of store-size units
21795 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21796 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21797 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21798 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21799 SmallVector<SDValue, 8> Chains;
21800 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21801 TLI.getPointerTy());
21802 SDValue Ptr = St->getBasePtr();
21804 // Perform one or more big stores into memory.
21805 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21806 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21807 StoreType, ShuffWide,
21808 DAG.getIntPtrConstant(i));
21809 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21810 St->getPointerInfo(), St->isVolatile(),
21811 St->isNonTemporal(), St->getAlignment());
21812 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21813 Chains.push_back(Ch);
21816 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21819 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
21820 // the FP state in cases where an emms may be missing.
21821 // A preferable solution to the general problem is to figure out the right
21822 // places to insert EMMS. This qualifies as a quick hack.
21824 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21825 if (VT.getSizeInBits() != 64)
21828 const Function *F = DAG.getMachineFunction().getFunction();
21829 bool NoImplicitFloatOps = F->getAttributes().
21830 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21831 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21832 && Subtarget->hasSSE2();
21833 if ((VT.isVector() ||
21834 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21835 isa<LoadSDNode>(St->getValue()) &&
21836 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21837 St->getChain().hasOneUse() && !St->isVolatile()) {
21838 SDNode* LdVal = St->getValue().getNode();
21839 LoadSDNode *Ld = nullptr;
21840 int TokenFactorIndex = -1;
21841 SmallVector<SDValue, 8> Ops;
21842 SDNode* ChainVal = St->getChain().getNode();
21843 // Must be a store of a load. We currently handle two cases: the load
21844 // is a direct child, and it's under an intervening TokenFactor. It is
21845 // possible to dig deeper under nested TokenFactors.
21846 if (ChainVal == LdVal)
21847 Ld = cast<LoadSDNode>(St->getChain());
21848 else if (St->getValue().hasOneUse() &&
21849 ChainVal->getOpcode() == ISD::TokenFactor) {
21850 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21851 if (ChainVal->getOperand(i).getNode() == LdVal) {
21852 TokenFactorIndex = i;
21853 Ld = cast<LoadSDNode>(St->getValue());
21855 Ops.push_back(ChainVal->getOperand(i));
21859 if (!Ld || !ISD::isNormalLoad(Ld))
21862 // If this is not the MMX case, i.e. we are just turning i64 load/store
21863 // into f64 load/store, avoid the transformation if there are multiple
21864 // uses of the loaded value.
21865 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21870 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21871 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21873 if (Subtarget->is64Bit() || F64IsLegal) {
21874 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21875 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21876 Ld->getPointerInfo(), Ld->isVolatile(),
21877 Ld->isNonTemporal(), Ld->isInvariant(),
21878 Ld->getAlignment());
21879 SDValue NewChain = NewLd.getValue(1);
21880 if (TokenFactorIndex != -1) {
21881 Ops.push_back(NewChain);
21882 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21884 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21885 St->getPointerInfo(),
21886 St->isVolatile(), St->isNonTemporal(),
21887 St->getAlignment());
21890 // Otherwise, lower to two pairs of 32-bit loads / stores.
21891 SDValue LoAddr = Ld->getBasePtr();
21892 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21893 DAG.getConstant(4, MVT::i32));
21895 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21896 Ld->getPointerInfo(),
21897 Ld->isVolatile(), Ld->isNonTemporal(),
21898 Ld->isInvariant(), Ld->getAlignment());
21899 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21900 Ld->getPointerInfo().getWithOffset(4),
21901 Ld->isVolatile(), Ld->isNonTemporal(),
21903 MinAlign(Ld->getAlignment(), 4));
21905 SDValue NewChain = LoLd.getValue(1);
21906 if (TokenFactorIndex != -1) {
21907 Ops.push_back(LoLd);
21908 Ops.push_back(HiLd);
21909 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21912 LoAddr = St->getBasePtr();
21913 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21914 DAG.getConstant(4, MVT::i32));
21916 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21917 St->getPointerInfo(),
21918 St->isVolatile(), St->isNonTemporal(),
21919 St->getAlignment());
21920 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21921 St->getPointerInfo().getWithOffset(4),
21923 St->isNonTemporal(),
21924 MinAlign(St->getAlignment(), 4));
21925 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21930 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21931 /// and return the operands for the horizontal operation in LHS and RHS. A
21932 /// horizontal operation performs the binary operation on successive elements
21933 /// of its first operand, then on successive elements of its second operand,
21934 /// returning the resulting values in a vector. For example, if
21935 /// A = < float a0, float a1, float a2, float a3 >
21937 /// B = < float b0, float b1, float b2, float b3 >
21938 /// then the result of doing a horizontal operation on A and B is
21939 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21940 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21941 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21942 /// set to A, RHS to B, and the routine returns 'true'.
21943 /// Note that the binary operation should have the property that if one of the
21944 /// operands is UNDEF then the result is UNDEF.
21945 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21946 // Look for the following pattern: if
21947 // A = < float a0, float a1, float a2, float a3 >
21948 // B = < float b0, float b1, float b2, float b3 >
21950 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21951 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21952 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21953 // which is A horizontal-op B.
21955 // At least one of the operands should be a vector shuffle.
21956 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21957 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21960 MVT VT = LHS.getSimpleValueType();
21962 assert((VT.is128BitVector() || VT.is256BitVector()) &&
21963 "Unsupported vector type for horizontal add/sub");
21965 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21966 // operate independently on 128-bit lanes.
21967 unsigned NumElts = VT.getVectorNumElements();
21968 unsigned NumLanes = VT.getSizeInBits()/128;
21969 unsigned NumLaneElts = NumElts / NumLanes;
21970 assert((NumLaneElts % 2 == 0) &&
21971 "Vector type should have an even number of elements in each lane");
21972 unsigned HalfLaneElts = NumLaneElts/2;
21974 // View LHS in the form
21975 // LHS = VECTOR_SHUFFLE A, B, LMask
21976 // If LHS is not a shuffle then pretend it is the shuffle
21977 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21978 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21981 SmallVector<int, 16> LMask(NumElts);
21982 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21983 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21984 A = LHS.getOperand(0);
21985 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21986 B = LHS.getOperand(1);
21987 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21988 std::copy(Mask.begin(), Mask.end(), LMask.begin());
21990 if (LHS.getOpcode() != ISD::UNDEF)
21992 for (unsigned i = 0; i != NumElts; ++i)
21996 // Likewise, view RHS in the form
21997 // RHS = VECTOR_SHUFFLE C, D, RMask
21999 SmallVector<int, 16> RMask(NumElts);
22000 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22001 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22002 C = RHS.getOperand(0);
22003 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22004 D = RHS.getOperand(1);
22005 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22006 std::copy(Mask.begin(), Mask.end(), RMask.begin());
22008 if (RHS.getOpcode() != ISD::UNDEF)
22010 for (unsigned i = 0; i != NumElts; ++i)
22014 // Check that the shuffles are both shuffling the same vectors.
22015 if (!(A == C && B == D) && !(A == D && B == C))
22018 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22019 if (!A.getNode() && !B.getNode())
22022 // If A and B occur in reverse order in RHS, then "swap" them (which means
22023 // rewriting the mask).
22025 CommuteVectorShuffleMask(RMask, NumElts);
22027 // At this point LHS and RHS are equivalent to
22028 // LHS = VECTOR_SHUFFLE A, B, LMask
22029 // RHS = VECTOR_SHUFFLE A, B, RMask
22030 // Check that the masks correspond to performing a horizontal operation.
22031 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22032 for (unsigned i = 0; i != NumLaneElts; ++i) {
22033 int LIdx = LMask[i+l], RIdx = RMask[i+l];
22035 // Ignore any UNDEF components.
22036 if (LIdx < 0 || RIdx < 0 ||
22037 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22038 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22041 // Check that successive elements are being operated on. If not, this is
22042 // not a horizontal operation.
22043 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22044 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22045 if (!(LIdx == Index && RIdx == Index + 1) &&
22046 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22051 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22052 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22056 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22057 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22058 const X86Subtarget *Subtarget) {
22059 EVT VT = N->getValueType(0);
22060 SDValue LHS = N->getOperand(0);
22061 SDValue RHS = N->getOperand(1);
22063 // Try to synthesize horizontal adds from adds of shuffles.
22064 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22065 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22066 isHorizontalBinOp(LHS, RHS, true))
22067 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22071 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22072 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22073 const X86Subtarget *Subtarget) {
22074 EVT VT = N->getValueType(0);
22075 SDValue LHS = N->getOperand(0);
22076 SDValue RHS = N->getOperand(1);
22078 // Try to synthesize horizontal subs from subs of shuffles.
22079 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22080 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22081 isHorizontalBinOp(LHS, RHS, false))
22082 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22086 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22087 /// X86ISD::FXOR nodes.
22088 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22089 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22090 // F[X]OR(0.0, x) -> x
22091 // F[X]OR(x, 0.0) -> x
22092 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22093 if (C->getValueAPF().isPosZero())
22094 return N->getOperand(1);
22095 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22096 if (C->getValueAPF().isPosZero())
22097 return N->getOperand(0);
22101 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22102 /// X86ISD::FMAX nodes.
22103 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22104 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22106 // Only perform optimizations if UnsafeMath is used.
22107 if (!DAG.getTarget().Options.UnsafeFPMath)
22110 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22111 // into FMINC and FMAXC, which are Commutative operations.
22112 unsigned NewOp = 0;
22113 switch (N->getOpcode()) {
22114 default: llvm_unreachable("unknown opcode");
22115 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
22116 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
22119 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22120 N->getOperand(0), N->getOperand(1));
22123 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22124 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22125 // FAND(0.0, x) -> 0.0
22126 // FAND(x, 0.0) -> 0.0
22127 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22128 if (C->getValueAPF().isPosZero())
22129 return N->getOperand(0);
22130 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22131 if (C->getValueAPF().isPosZero())
22132 return N->getOperand(1);
22136 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22137 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22138 // FANDN(x, 0.0) -> 0.0
22139 // FANDN(0.0, x) -> x
22140 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22141 if (C->getValueAPF().isPosZero())
22142 return N->getOperand(1);
22143 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22144 if (C->getValueAPF().isPosZero())
22145 return N->getOperand(1);
22149 static SDValue PerformBTCombine(SDNode *N,
22151 TargetLowering::DAGCombinerInfo &DCI) {
22152 // BT ignores high bits in the bit index operand.
22153 SDValue Op1 = N->getOperand(1);
22154 if (Op1.hasOneUse()) {
22155 unsigned BitWidth = Op1.getValueSizeInBits();
22156 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22157 APInt KnownZero, KnownOne;
22158 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22159 !DCI.isBeforeLegalizeOps());
22160 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22161 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22162 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22163 DCI.CommitTargetLoweringOpt(TLO);
22168 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22169 SDValue Op = N->getOperand(0);
22170 if (Op.getOpcode() == ISD::BITCAST)
22171 Op = Op.getOperand(0);
22172 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22173 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22174 VT.getVectorElementType().getSizeInBits() ==
22175 OpVT.getVectorElementType().getSizeInBits()) {
22176 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22181 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22182 const X86Subtarget *Subtarget) {
22183 EVT VT = N->getValueType(0);
22184 if (!VT.isVector())
22187 SDValue N0 = N->getOperand(0);
22188 SDValue N1 = N->getOperand(1);
22189 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22192 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22193 // both SSE and AVX2 since there is no sign-extended shift right
22194 // operation on a vector with 64-bit elements.
22195 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22196 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22197 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22198 N0.getOpcode() == ISD::SIGN_EXTEND)) {
22199 SDValue N00 = N0.getOperand(0);
22201 // EXTLOAD has a better solution on AVX2,
22202 // it may be replaced with X86ISD::VSEXT node.
22203 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22204 if (!ISD::isNormalLoad(N00.getNode()))
22207 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22208 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22210 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22216 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22217 TargetLowering::DAGCombinerInfo &DCI,
22218 const X86Subtarget *Subtarget) {
22219 if (!DCI.isBeforeLegalizeOps())
22222 if (!Subtarget->hasFp256())
22225 EVT VT = N->getValueType(0);
22226 if (VT.isVector() && VT.getSizeInBits() == 256) {
22227 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22235 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22236 const X86Subtarget* Subtarget) {
22238 EVT VT = N->getValueType(0);
22240 // Let legalize expand this if it isn't a legal type yet.
22241 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22244 EVT ScalarVT = VT.getScalarType();
22245 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22246 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22249 SDValue A = N->getOperand(0);
22250 SDValue B = N->getOperand(1);
22251 SDValue C = N->getOperand(2);
22253 bool NegA = (A.getOpcode() == ISD::FNEG);
22254 bool NegB = (B.getOpcode() == ISD::FNEG);
22255 bool NegC = (C.getOpcode() == ISD::FNEG);
22257 // Negative multiplication when NegA xor NegB
22258 bool NegMul = (NegA != NegB);
22260 A = A.getOperand(0);
22262 B = B.getOperand(0);
22264 C = C.getOperand(0);
22268 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22270 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22272 return DAG.getNode(Opcode, dl, VT, A, B, C);
22275 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22276 TargetLowering::DAGCombinerInfo &DCI,
22277 const X86Subtarget *Subtarget) {
22278 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
22279 // (and (i32 x86isd::setcc_carry), 1)
22280 // This eliminates the zext. This transformation is necessary because
22281 // ISD::SETCC is always legalized to i8.
22283 SDValue N0 = N->getOperand(0);
22284 EVT VT = N->getValueType(0);
22286 if (N0.getOpcode() == ISD::AND &&
22288 N0.getOperand(0).hasOneUse()) {
22289 SDValue N00 = N0.getOperand(0);
22290 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22291 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22292 if (!C || C->getZExtValue() != 1)
22294 return DAG.getNode(ISD::AND, dl, VT,
22295 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22296 N00.getOperand(0), N00.getOperand(1)),
22297 DAG.getConstant(1, VT));
22301 if (N0.getOpcode() == ISD::TRUNCATE &&
22303 N0.getOperand(0).hasOneUse()) {
22304 SDValue N00 = N0.getOperand(0);
22305 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22306 return DAG.getNode(ISD::AND, dl, VT,
22307 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22308 N00.getOperand(0), N00.getOperand(1)),
22309 DAG.getConstant(1, VT));
22312 if (VT.is256BitVector()) {
22313 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22321 // Optimize x == -y --> x+y == 0
22322 // x != -y --> x+y != 0
22323 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22324 const X86Subtarget* Subtarget) {
22325 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22326 SDValue LHS = N->getOperand(0);
22327 SDValue RHS = N->getOperand(1);
22328 EVT VT = N->getValueType(0);
22331 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22332 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22333 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22334 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22335 LHS.getValueType(), RHS, LHS.getOperand(1));
22336 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22337 addV, DAG.getConstant(0, addV.getValueType()), CC);
22339 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22340 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22341 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22342 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22343 RHS.getValueType(), LHS, RHS.getOperand(1));
22344 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22345 addV, DAG.getConstant(0, addV.getValueType()), CC);
22348 if (VT.getScalarType() == MVT::i1) {
22349 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22350 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22351 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22352 if (!IsSEXT0 && !IsVZero0)
22354 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22355 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22356 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22358 if (!IsSEXT1 && !IsVZero1)
22361 if (IsSEXT0 && IsVZero1) {
22362 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22363 if (CC == ISD::SETEQ)
22364 return DAG.getNOT(DL, LHS.getOperand(0), VT);
22365 return LHS.getOperand(0);
22367 if (IsSEXT1 && IsVZero0) {
22368 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22369 if (CC == ISD::SETEQ)
22370 return DAG.getNOT(DL, RHS.getOperand(0), VT);
22371 return RHS.getOperand(0);
22378 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22379 const X86Subtarget *Subtarget) {
22381 MVT VT = N->getOperand(1)->getSimpleValueType(0);
22382 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22383 "X86insertps is only defined for v4x32");
22385 SDValue Ld = N->getOperand(1);
22386 if (MayFoldLoad(Ld)) {
22387 // Extract the countS bits from the immediate so we can get the proper
22388 // address when narrowing the vector load to a specific element.
22389 // When the second source op is a memory address, interps doesn't use
22390 // countS and just gets an f32 from that address.
22391 unsigned DestIndex =
22392 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22393 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22397 // Create this as a scalar to vector to match the instruction pattern.
22398 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22399 // countS bits are ignored when loading from memory on insertps, which
22400 // means we don't need to explicitly set them to 0.
22401 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22402 LoadScalarToVector, N->getOperand(2));
22405 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22406 // as "sbb reg,reg", since it can be extended without zext and produces
22407 // an all-ones bit which is more useful than 0/1 in some cases.
22408 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22411 return DAG.getNode(ISD::AND, DL, VT,
22412 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22413 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22414 DAG.getConstant(1, VT));
22415 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22416 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22417 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22418 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22421 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22422 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22423 TargetLowering::DAGCombinerInfo &DCI,
22424 const X86Subtarget *Subtarget) {
22426 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22427 SDValue EFLAGS = N->getOperand(1);
22429 if (CC == X86::COND_A) {
22430 // Try to convert COND_A into COND_B in an attempt to facilitate
22431 // materializing "setb reg".
22433 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22434 // cannot take an immediate as its first operand.
22436 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22437 EFLAGS.getValueType().isInteger() &&
22438 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22439 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22440 EFLAGS.getNode()->getVTList(),
22441 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22442 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22443 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22447 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22448 // a zext and produces an all-ones bit which is more useful than 0/1 in some
22450 if (CC == X86::COND_B)
22451 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22455 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22456 if (Flags.getNode()) {
22457 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22458 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22464 // Optimize branch condition evaluation.
22466 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22467 TargetLowering::DAGCombinerInfo &DCI,
22468 const X86Subtarget *Subtarget) {
22470 SDValue Chain = N->getOperand(0);
22471 SDValue Dest = N->getOperand(1);
22472 SDValue EFLAGS = N->getOperand(3);
22473 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22477 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22478 if (Flags.getNode()) {
22479 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22480 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22487 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22488 SelectionDAG &DAG) {
22489 // Take advantage of vector comparisons producing 0 or -1 in each lane to
22490 // optimize away operation when it's from a constant.
22492 // The general transformation is:
22493 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22494 // AND(VECTOR_CMP(x,y), constant2)
22495 // constant2 = UNARYOP(constant)
22497 // Early exit if this isn't a vector operation, the operand of the
22498 // unary operation isn't a bitwise AND, or if the sizes of the operations
22499 // aren't the same.
22500 EVT VT = N->getValueType(0);
22501 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22502 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22503 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22506 // Now check that the other operand of the AND is a constant. We could
22507 // make the transformation for non-constant splats as well, but it's unclear
22508 // that would be a benefit as it would not eliminate any operations, just
22509 // perform one more step in scalar code before moving to the vector unit.
22510 if (BuildVectorSDNode *BV =
22511 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22512 // Bail out if the vector isn't a constant.
22513 if (!BV->isConstant())
22516 // Everything checks out. Build up the new and improved node.
22518 EVT IntVT = BV->getValueType(0);
22519 // Create a new constant of the appropriate type for the transformed
22521 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22522 // The AND node needs bitcasts to/from an integer vector type around it.
22523 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22524 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22525 N->getOperand(0)->getOperand(0), MaskConst);
22526 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22533 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22534 const X86TargetLowering *XTLI) {
22535 // First try to optimize away the conversion entirely when it's
22536 // conditionally from a constant. Vectors only.
22537 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22538 if (Res != SDValue())
22541 // Now move on to more general possibilities.
22542 SDValue Op0 = N->getOperand(0);
22543 EVT InVT = Op0->getValueType(0);
22545 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22546 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22548 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22549 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22550 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22553 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22554 // a 32-bit target where SSE doesn't support i64->FP operations.
22555 if (Op0.getOpcode() == ISD::LOAD) {
22556 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22557 EVT VT = Ld->getValueType(0);
22558 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22559 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22560 !XTLI->getSubtarget()->is64Bit() &&
22562 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22563 Ld->getChain(), Op0, DAG);
22564 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22571 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22572 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22573 X86TargetLowering::DAGCombinerInfo &DCI) {
22574 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22575 // the result is either zero or one (depending on the input carry bit).
22576 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22577 if (X86::isZeroNode(N->getOperand(0)) &&
22578 X86::isZeroNode(N->getOperand(1)) &&
22579 // We don't have a good way to replace an EFLAGS use, so only do this when
22581 SDValue(N, 1).use_empty()) {
22583 EVT VT = N->getValueType(0);
22584 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22585 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22586 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22587 DAG.getConstant(X86::COND_B,MVT::i8),
22589 DAG.getConstant(1, VT));
22590 return DCI.CombineTo(N, Res1, CarryOut);
22596 // fold (add Y, (sete X, 0)) -> adc 0, Y
22597 // (add Y, (setne X, 0)) -> sbb -1, Y
22598 // (sub (sete X, 0), Y) -> sbb 0, Y
22599 // (sub (setne X, 0), Y) -> adc -1, Y
22600 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22603 // Look through ZExts.
22604 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22605 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22608 SDValue SetCC = Ext.getOperand(0);
22609 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22612 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22613 if (CC != X86::COND_E && CC != X86::COND_NE)
22616 SDValue Cmp = SetCC.getOperand(1);
22617 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22618 !X86::isZeroNode(Cmp.getOperand(1)) ||
22619 !Cmp.getOperand(0).getValueType().isInteger())
22622 SDValue CmpOp0 = Cmp.getOperand(0);
22623 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22624 DAG.getConstant(1, CmpOp0.getValueType()));
22626 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22627 if (CC == X86::COND_NE)
22628 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22629 DL, OtherVal.getValueType(), OtherVal,
22630 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22631 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22632 DL, OtherVal.getValueType(), OtherVal,
22633 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22636 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22637 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22638 const X86Subtarget *Subtarget) {
22639 EVT VT = N->getValueType(0);
22640 SDValue Op0 = N->getOperand(0);
22641 SDValue Op1 = N->getOperand(1);
22643 // Try to synthesize horizontal adds from adds of shuffles.
22644 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22645 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22646 isHorizontalBinOp(Op0, Op1, true))
22647 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22649 return OptimizeConditionalInDecrement(N, DAG);
22652 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22653 const X86Subtarget *Subtarget) {
22654 SDValue Op0 = N->getOperand(0);
22655 SDValue Op1 = N->getOperand(1);
22657 // X86 can't encode an immediate LHS of a sub. See if we can push the
22658 // negation into a preceding instruction.
22659 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22660 // If the RHS of the sub is a XOR with one use and a constant, invert the
22661 // immediate. Then add one to the LHS of the sub so we can turn
22662 // X-Y -> X+~Y+1, saving one register.
22663 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22664 isa<ConstantSDNode>(Op1.getOperand(1))) {
22665 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22666 EVT VT = Op0.getValueType();
22667 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22669 DAG.getConstant(~XorC, VT));
22670 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22671 DAG.getConstant(C->getAPIntValue()+1, VT));
22675 // Try to synthesize horizontal adds from adds of shuffles.
22676 EVT VT = N->getValueType(0);
22677 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22678 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22679 isHorizontalBinOp(Op0, Op1, true))
22680 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22682 return OptimizeConditionalInDecrement(N, DAG);
22685 /// performVZEXTCombine - Performs build vector combines
22686 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22687 TargetLowering::DAGCombinerInfo &DCI,
22688 const X86Subtarget *Subtarget) {
22689 // (vzext (bitcast (vzext (x)) -> (vzext x)
22690 SDValue In = N->getOperand(0);
22691 while (In.getOpcode() == ISD::BITCAST)
22692 In = In.getOperand(0);
22694 if (In.getOpcode() != X86ISD::VZEXT)
22697 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22701 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22702 DAGCombinerInfo &DCI) const {
22703 SelectionDAG &DAG = DCI.DAG;
22704 switch (N->getOpcode()) {
22706 case ISD::EXTRACT_VECTOR_ELT:
22707 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22709 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22710 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22711 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
22712 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
22713 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
22714 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
22717 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
22718 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
22719 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
22720 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
22721 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
22722 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
22723 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
22724 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
22725 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
22727 case X86ISD::FOR: return PerformFORCombine(N, DAG);
22729 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
22730 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
22731 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
22732 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
22733 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
22734 case ISD::ANY_EXTEND:
22735 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
22736 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
22737 case ISD::SIGN_EXTEND_INREG:
22738 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22739 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22740 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
22741 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22742 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22743 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
22744 case X86ISD::SHUFP: // Handle all target specific shuffles
22745 case X86ISD::PALIGNR:
22746 case X86ISD::UNPCKH:
22747 case X86ISD::UNPCKL:
22748 case X86ISD::MOVHLPS:
22749 case X86ISD::MOVLHPS:
22750 case X86ISD::PSHUFB:
22751 case X86ISD::PSHUFD:
22752 case X86ISD::PSHUFHW:
22753 case X86ISD::PSHUFLW:
22754 case X86ISD::MOVSS:
22755 case X86ISD::MOVSD:
22756 case X86ISD::VPERMILP:
22757 case X86ISD::VPERM2X128:
22758 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22759 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
22760 case ISD::INTRINSIC_WO_CHAIN:
22761 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22762 case X86ISD::INSERTPS:
22763 return PerformINSERTPSCombine(N, DAG, Subtarget);
22764 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22770 /// isTypeDesirableForOp - Return true if the target has native support for
22771 /// the specified value type and it is 'desirable' to use the type for the
22772 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22773 /// instruction encodings are longer and some i16 instructions are slow.
22774 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22775 if (!isTypeLegal(VT))
22777 if (VT != MVT::i16)
22784 case ISD::SIGN_EXTEND:
22785 case ISD::ZERO_EXTEND:
22786 case ISD::ANY_EXTEND:
22799 /// IsDesirableToPromoteOp - This method query the target whether it is
22800 /// beneficial for dag combiner to promote the specified node. If true, it
22801 /// should return the desired promotion type by reference.
22802 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22803 EVT VT = Op.getValueType();
22804 if (VT != MVT::i16)
22807 bool Promote = false;
22808 bool Commute = false;
22809 switch (Op.getOpcode()) {
22812 LoadSDNode *LD = cast<LoadSDNode>(Op);
22813 // If the non-extending load has a single use and it's not live out, then it
22814 // might be folded.
22815 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22816 Op.hasOneUse()*/) {
22817 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22818 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22819 // The only case where we'd want to promote LOAD (rather then it being
22820 // promoted as an operand is when it's only use is liveout.
22821 if (UI->getOpcode() != ISD::CopyToReg)
22828 case ISD::SIGN_EXTEND:
22829 case ISD::ZERO_EXTEND:
22830 case ISD::ANY_EXTEND:
22835 SDValue N0 = Op.getOperand(0);
22836 // Look out for (store (shl (load), x)).
22837 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22850 SDValue N0 = Op.getOperand(0);
22851 SDValue N1 = Op.getOperand(1);
22852 if (!Commute && MayFoldLoad(N1))
22854 // Avoid disabling potential load folding opportunities.
22855 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22857 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22867 //===----------------------------------------------------------------------===//
22868 // X86 Inline Assembly Support
22869 //===----------------------------------------------------------------------===//
22872 // Helper to match a string separated by whitespace.
22873 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22874 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22876 for (unsigned i = 0, e = args.size(); i != e; ++i) {
22877 StringRef piece(*args[i]);
22878 if (!s.startswith(piece)) // Check if the piece matches.
22881 s = s.substr(piece.size());
22882 StringRef::size_type pos = s.find_first_not_of(" \t");
22883 if (pos == 0) // We matched a prefix.
22891 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22894 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22896 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22897 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22898 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22899 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22901 if (AsmPieces.size() == 3)
22903 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22910 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22911 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22913 std::string AsmStr = IA->getAsmString();
22915 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22916 if (!Ty || Ty->getBitWidth() % 16 != 0)
22919 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22920 SmallVector<StringRef, 4> AsmPieces;
22921 SplitString(AsmStr, AsmPieces, ";\n");
22923 switch (AsmPieces.size()) {
22924 default: return false;
22926 // FIXME: this should verify that we are targeting a 486 or better. If not,
22927 // we will turn this bswap into something that will be lowered to logical
22928 // ops instead of emitting the bswap asm. For now, we don't support 486 or
22929 // lower so don't worry about this.
22931 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22932 matchAsm(AsmPieces[0], "bswapl", "$0") ||
22933 matchAsm(AsmPieces[0], "bswapq", "$0") ||
22934 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22935 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22936 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22937 // No need to check constraints, nothing other than the equivalent of
22938 // "=r,0" would be valid here.
22939 return IntrinsicLowering::LowerToByteSwap(CI);
22942 // rorw $$8, ${0:w} --> llvm.bswap.i16
22943 if (CI->getType()->isIntegerTy(16) &&
22944 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22945 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22946 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22948 const std::string &ConstraintsStr = IA->getConstraintString();
22949 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22950 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22951 if (clobbersFlagRegisters(AsmPieces))
22952 return IntrinsicLowering::LowerToByteSwap(CI);
22956 if (CI->getType()->isIntegerTy(32) &&
22957 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22958 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22959 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22960 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22962 const std::string &ConstraintsStr = IA->getConstraintString();
22963 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22964 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22965 if (clobbersFlagRegisters(AsmPieces))
22966 return IntrinsicLowering::LowerToByteSwap(CI);
22969 if (CI->getType()->isIntegerTy(64)) {
22970 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22971 if (Constraints.size() >= 2 &&
22972 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22973 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22974 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
22975 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22976 matchAsm(AsmPieces[1], "bswap", "%edx") &&
22977 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22978 return IntrinsicLowering::LowerToByteSwap(CI);
22986 /// getConstraintType - Given a constraint letter, return the type of
22987 /// constraint it is for this target.
22988 X86TargetLowering::ConstraintType
22989 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22990 if (Constraint.size() == 1) {
22991 switch (Constraint[0]) {
23002 return C_RegisterClass;
23026 return TargetLowering::getConstraintType(Constraint);
23029 /// Examine constraint type and operand type and determine a weight value.
23030 /// This object must already have been set up with the operand type
23031 /// and the current alternative constraint selected.
23032 TargetLowering::ConstraintWeight
23033 X86TargetLowering::getSingleConstraintMatchWeight(
23034 AsmOperandInfo &info, const char *constraint) const {
23035 ConstraintWeight weight = CW_Invalid;
23036 Value *CallOperandVal = info.CallOperandVal;
23037 // If we don't have a value, we can't do a match,
23038 // but allow it at the lowest weight.
23039 if (!CallOperandVal)
23041 Type *type = CallOperandVal->getType();
23042 // Look at the constraint type.
23043 switch (*constraint) {
23045 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23056 if (CallOperandVal->getType()->isIntegerTy())
23057 weight = CW_SpecificReg;
23062 if (type->isFloatingPointTy())
23063 weight = CW_SpecificReg;
23066 if (type->isX86_MMXTy() && Subtarget->hasMMX())
23067 weight = CW_SpecificReg;
23071 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23072 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23073 weight = CW_Register;
23076 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23077 if (C->getZExtValue() <= 31)
23078 weight = CW_Constant;
23082 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23083 if (C->getZExtValue() <= 63)
23084 weight = CW_Constant;
23088 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23089 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23090 weight = CW_Constant;
23094 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23095 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23096 weight = CW_Constant;
23100 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23101 if (C->getZExtValue() <= 3)
23102 weight = CW_Constant;
23106 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23107 if (C->getZExtValue() <= 0xff)
23108 weight = CW_Constant;
23113 if (dyn_cast<ConstantFP>(CallOperandVal)) {
23114 weight = CW_Constant;
23118 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23119 if ((C->getSExtValue() >= -0x80000000LL) &&
23120 (C->getSExtValue() <= 0x7fffffffLL))
23121 weight = CW_Constant;
23125 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23126 if (C->getZExtValue() <= 0xffffffff)
23127 weight = CW_Constant;
23134 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23135 /// with another that has more specific requirements based on the type of the
23136 /// corresponding operand.
23137 const char *X86TargetLowering::
23138 LowerXConstraint(EVT ConstraintVT) const {
23139 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23140 // 'f' like normal targets.
23141 if (ConstraintVT.isFloatingPoint()) {
23142 if (Subtarget->hasSSE2())
23144 if (Subtarget->hasSSE1())
23148 return TargetLowering::LowerXConstraint(ConstraintVT);
23151 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23152 /// vector. If it is invalid, don't add anything to Ops.
23153 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23154 std::string &Constraint,
23155 std::vector<SDValue>&Ops,
23156 SelectionDAG &DAG) const {
23159 // Only support length 1 constraints for now.
23160 if (Constraint.length() > 1) return;
23162 char ConstraintLetter = Constraint[0];
23163 switch (ConstraintLetter) {
23166 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23167 if (C->getZExtValue() <= 31) {
23168 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23174 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23175 if (C->getZExtValue() <= 63) {
23176 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23182 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23183 if (isInt<8>(C->getSExtValue())) {
23184 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23190 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23191 if (C->getZExtValue() <= 255) {
23192 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23198 // 32-bit signed value
23199 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23200 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23201 C->getSExtValue())) {
23202 // Widen to 64 bits here to get it sign extended.
23203 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23206 // FIXME gcc accepts some relocatable values here too, but only in certain
23207 // memory models; it's complicated.
23212 // 32-bit unsigned value
23213 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23214 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23215 C->getZExtValue())) {
23216 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23220 // FIXME gcc accepts some relocatable values here too, but only in certain
23221 // memory models; it's complicated.
23225 // Literal immediates are always ok.
23226 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23227 // Widen to 64 bits here to get it sign extended.
23228 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23232 // In any sort of PIC mode addresses need to be computed at runtime by
23233 // adding in a register or some sort of table lookup. These can't
23234 // be used as immediates.
23235 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23238 // If we are in non-pic codegen mode, we allow the address of a global (with
23239 // an optional displacement) to be used with 'i'.
23240 GlobalAddressSDNode *GA = nullptr;
23241 int64_t Offset = 0;
23243 // Match either (GA), (GA+C), (GA+C1+C2), etc.
23245 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23246 Offset += GA->getOffset();
23248 } else if (Op.getOpcode() == ISD::ADD) {
23249 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23250 Offset += C->getZExtValue();
23251 Op = Op.getOperand(0);
23254 } else if (Op.getOpcode() == ISD::SUB) {
23255 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23256 Offset += -C->getZExtValue();
23257 Op = Op.getOperand(0);
23262 // Otherwise, this isn't something we can handle, reject it.
23266 const GlobalValue *GV = GA->getGlobal();
23267 // If we require an extra load to get this address, as in PIC mode, we
23268 // can't accept it.
23269 if (isGlobalStubReference(
23270 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23273 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23274 GA->getValueType(0), Offset);
23279 if (Result.getNode()) {
23280 Ops.push_back(Result);
23283 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23286 std::pair<unsigned, const TargetRegisterClass*>
23287 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23289 // First, see if this is a constraint that directly corresponds to an LLVM
23291 if (Constraint.size() == 1) {
23292 // GCC Constraint Letters
23293 switch (Constraint[0]) {
23295 // TODO: Slight differences here in allocation order and leaving
23296 // RIP in the class. Do they matter any more here than they do
23297 // in the normal allocation?
23298 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23299 if (Subtarget->is64Bit()) {
23300 if (VT == MVT::i32 || VT == MVT::f32)
23301 return std::make_pair(0U, &X86::GR32RegClass);
23302 if (VT == MVT::i16)
23303 return std::make_pair(0U, &X86::GR16RegClass);
23304 if (VT == MVT::i8 || VT == MVT::i1)
23305 return std::make_pair(0U, &X86::GR8RegClass);
23306 if (VT == MVT::i64 || VT == MVT::f64)
23307 return std::make_pair(0U, &X86::GR64RegClass);
23310 // 32-bit fallthrough
23311 case 'Q': // Q_REGS
23312 if (VT == MVT::i32 || VT == MVT::f32)
23313 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23314 if (VT == MVT::i16)
23315 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23316 if (VT == MVT::i8 || VT == MVT::i1)
23317 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23318 if (VT == MVT::i64)
23319 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23321 case 'r': // GENERAL_REGS
23322 case 'l': // INDEX_REGS
23323 if (VT == MVT::i8 || VT == MVT::i1)
23324 return std::make_pair(0U, &X86::GR8RegClass);
23325 if (VT == MVT::i16)
23326 return std::make_pair(0U, &X86::GR16RegClass);
23327 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23328 return std::make_pair(0U, &X86::GR32RegClass);
23329 return std::make_pair(0U, &X86::GR64RegClass);
23330 case 'R': // LEGACY_REGS
23331 if (VT == MVT::i8 || VT == MVT::i1)
23332 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23333 if (VT == MVT::i16)
23334 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23335 if (VT == MVT::i32 || !Subtarget->is64Bit())
23336 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23337 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23338 case 'f': // FP Stack registers.
23339 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23340 // value to the correct fpstack register class.
23341 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23342 return std::make_pair(0U, &X86::RFP32RegClass);
23343 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23344 return std::make_pair(0U, &X86::RFP64RegClass);
23345 return std::make_pair(0U, &X86::RFP80RegClass);
23346 case 'y': // MMX_REGS if MMX allowed.
23347 if (!Subtarget->hasMMX()) break;
23348 return std::make_pair(0U, &X86::VR64RegClass);
23349 case 'Y': // SSE_REGS if SSE2 allowed
23350 if (!Subtarget->hasSSE2()) break;
23352 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23353 if (!Subtarget->hasSSE1()) break;
23355 switch (VT.SimpleTy) {
23357 // Scalar SSE types.
23360 return std::make_pair(0U, &X86::FR32RegClass);
23363 return std::make_pair(0U, &X86::FR64RegClass);
23371 return std::make_pair(0U, &X86::VR128RegClass);
23379 return std::make_pair(0U, &X86::VR256RegClass);
23384 return std::make_pair(0U, &X86::VR512RegClass);
23390 // Use the default implementation in TargetLowering to convert the register
23391 // constraint into a member of a register class.
23392 std::pair<unsigned, const TargetRegisterClass*> Res;
23393 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23395 // Not found as a standard register?
23397 // Map st(0) -> st(7) -> ST0
23398 if (Constraint.size() == 7 && Constraint[0] == '{' &&
23399 tolower(Constraint[1]) == 's' &&
23400 tolower(Constraint[2]) == 't' &&
23401 Constraint[3] == '(' &&
23402 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23403 Constraint[5] == ')' &&
23404 Constraint[6] == '}') {
23406 Res.first = X86::FP0+Constraint[4]-'0';
23407 Res.second = &X86::RFP80RegClass;
23411 // GCC allows "st(0)" to be called just plain "st".
23412 if (StringRef("{st}").equals_lower(Constraint)) {
23413 Res.first = X86::FP0;
23414 Res.second = &X86::RFP80RegClass;
23419 if (StringRef("{flags}").equals_lower(Constraint)) {
23420 Res.first = X86::EFLAGS;
23421 Res.second = &X86::CCRRegClass;
23425 // 'A' means EAX + EDX.
23426 if (Constraint == "A") {
23427 Res.first = X86::EAX;
23428 Res.second = &X86::GR32_ADRegClass;
23434 // Otherwise, check to see if this is a register class of the wrong value
23435 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23436 // turn into {ax},{dx}.
23437 if (Res.second->hasType(VT))
23438 return Res; // Correct type already, nothing to do.
23440 // All of the single-register GCC register classes map their values onto
23441 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
23442 // really want an 8-bit or 32-bit register, map to the appropriate register
23443 // class and return the appropriate register.
23444 if (Res.second == &X86::GR16RegClass) {
23445 if (VT == MVT::i8 || VT == MVT::i1) {
23446 unsigned DestReg = 0;
23447 switch (Res.first) {
23449 case X86::AX: DestReg = X86::AL; break;
23450 case X86::DX: DestReg = X86::DL; break;
23451 case X86::CX: DestReg = X86::CL; break;
23452 case X86::BX: DestReg = X86::BL; break;
23455 Res.first = DestReg;
23456 Res.second = &X86::GR8RegClass;
23458 } else if (VT == MVT::i32 || VT == MVT::f32) {
23459 unsigned DestReg = 0;
23460 switch (Res.first) {
23462 case X86::AX: DestReg = X86::EAX; break;
23463 case X86::DX: DestReg = X86::EDX; break;
23464 case X86::CX: DestReg = X86::ECX; break;
23465 case X86::BX: DestReg = X86::EBX; break;
23466 case X86::SI: DestReg = X86::ESI; break;
23467 case X86::DI: DestReg = X86::EDI; break;
23468 case X86::BP: DestReg = X86::EBP; break;
23469 case X86::SP: DestReg = X86::ESP; break;
23472 Res.first = DestReg;
23473 Res.second = &X86::GR32RegClass;
23475 } else if (VT == MVT::i64 || VT == MVT::f64) {
23476 unsigned DestReg = 0;
23477 switch (Res.first) {
23479 case X86::AX: DestReg = X86::RAX; break;
23480 case X86::DX: DestReg = X86::RDX; break;
23481 case X86::CX: DestReg = X86::RCX; break;
23482 case X86::BX: DestReg = X86::RBX; break;
23483 case X86::SI: DestReg = X86::RSI; break;
23484 case X86::DI: DestReg = X86::RDI; break;
23485 case X86::BP: DestReg = X86::RBP; break;
23486 case X86::SP: DestReg = X86::RSP; break;
23489 Res.first = DestReg;
23490 Res.second = &X86::GR64RegClass;
23493 } else if (Res.second == &X86::FR32RegClass ||
23494 Res.second == &X86::FR64RegClass ||
23495 Res.second == &X86::VR128RegClass ||
23496 Res.second == &X86::VR256RegClass ||
23497 Res.second == &X86::FR32XRegClass ||
23498 Res.second == &X86::FR64XRegClass ||
23499 Res.second == &X86::VR128XRegClass ||
23500 Res.second == &X86::VR256XRegClass ||
23501 Res.second == &X86::VR512RegClass) {
23502 // Handle references to XMM physical registers that got mapped into the
23503 // wrong class. This can happen with constraints like {xmm0} where the
23504 // target independent register mapper will just pick the first match it can
23505 // find, ignoring the required type.
23507 if (VT == MVT::f32 || VT == MVT::i32)
23508 Res.second = &X86::FR32RegClass;
23509 else if (VT == MVT::f64 || VT == MVT::i64)
23510 Res.second = &X86::FR64RegClass;
23511 else if (X86::VR128RegClass.hasType(VT))
23512 Res.second = &X86::VR128RegClass;
23513 else if (X86::VR256RegClass.hasType(VT))
23514 Res.second = &X86::VR256RegClass;
23515 else if (X86::VR512RegClass.hasType(VT))
23516 Res.second = &X86::VR512RegClass;
23522 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23524 // Scaling factors are not free at all.
23525 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23526 // will take 2 allocations in the out of order engine instead of 1
23527 // for plain addressing mode, i.e. inst (reg1).
23529 // vaddps (%rsi,%drx), %ymm0, %ymm1
23530 // Requires two allocations (one for the load, one for the computation)
23532 // vaddps (%rsi), %ymm0, %ymm1
23533 // Requires just 1 allocation, i.e., freeing allocations for other operations
23534 // and having less micro operations to execute.
23536 // For some X86 architectures, this is even worse because for instance for
23537 // stores, the complex addressing mode forces the instruction to use the
23538 // "load" ports instead of the dedicated "store" port.
23539 // E.g., on Haswell:
23540 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23541 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
23542 if (isLegalAddressingMode(AM, Ty))
23543 // Scale represents reg2 * scale, thus account for 1
23544 // as soon as we use a second register.
23545 return AM.Scale != 0;
23549 bool X86TargetLowering::isTargetFTOL() const {
23550 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();