1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
57 #define DEBUG_TYPE "x86-isel"
59 STATISTIC(NumTailCalls, "Number of tail calls");
61 static cl::opt<bool> ExperimentalVectorShuffleLowering(
62 "x86-experimental-vector-shuffle-lowering", cl::init(false),
63 cl::desc("Enable an experimental vector shuffle lowering code path."),
66 // Forward declarations.
67 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
70 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
71 SelectionDAG &DAG, SDLoc dl,
72 unsigned vectorWidth) {
73 assert((vectorWidth == 128 || vectorWidth == 256) &&
74 "Unsupported vector width");
75 EVT VT = Vec.getValueType();
76 EVT ElVT = VT.getVectorElementType();
77 unsigned Factor = VT.getSizeInBits()/vectorWidth;
78 EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
79 VT.getVectorNumElements()/Factor);
81 // Extract from UNDEF is UNDEF.
82 if (Vec.getOpcode() == ISD::UNDEF)
83 return DAG.getUNDEF(ResultVT);
85 // Extract the relevant vectorWidth bits. Generate an EXTRACT_SUBVECTOR
86 unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
88 // This is the index of the first element of the vectorWidth-bit chunk
90 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
93 // If the input is a buildvector just emit a smaller one.
94 if (Vec.getOpcode() == ISD::BUILD_VECTOR)
95 return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
96 makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
99 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
100 SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
106 /// Generate a DAG to grab 128-bits from a vector > 128 bits. This
107 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
108 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
109 /// instructions or a simple subregister reference. Idx is an index in the
110 /// 128 bits we want. It need not be aligned to a 128-bit bounday. That makes
111 /// lowering EXTRACT_VECTOR_ELT operations easier.
112 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
113 SelectionDAG &DAG, SDLoc dl) {
114 assert((Vec.getValueType().is256BitVector() ||
115 Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
116 return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
119 /// Generate a DAG to grab 256-bits from a 512-bit vector.
120 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
121 SelectionDAG &DAG, SDLoc dl) {
122 assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
123 return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
126 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
127 unsigned IdxVal, SelectionDAG &DAG,
128 SDLoc dl, unsigned vectorWidth) {
129 assert((vectorWidth == 128 || vectorWidth == 256) &&
130 "Unsupported vector width");
131 // Inserting UNDEF is Result
132 if (Vec.getOpcode() == ISD::UNDEF)
134 EVT VT = Vec.getValueType();
135 EVT ElVT = VT.getVectorElementType();
136 EVT ResultVT = Result.getValueType();
138 // Insert the relevant vectorWidth bits.
139 unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
141 // This is the index of the first element of the vectorWidth-bit chunk
143 unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
146 SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
147 return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
150 /// Generate a DAG to put 128-bits into a vector > 128 bits. This
151 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
152 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
153 /// simple superregister reference. Idx is an index in the 128 bits
154 /// we want. It need not be aligned to a 128-bit bounday. That makes
155 /// lowering INSERT_VECTOR_ELT operations easier.
156 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
157 unsigned IdxVal, SelectionDAG &DAG,
159 assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
160 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
163 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
164 unsigned IdxVal, SelectionDAG &DAG,
166 assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
167 return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
170 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
171 /// instructions. This is used because creating CONCAT_VECTOR nodes of
172 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
173 /// large BUILD_VECTORS.
174 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
175 unsigned NumElems, SelectionDAG &DAG,
177 SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178 return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
181 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
182 unsigned NumElems, SelectionDAG &DAG,
184 SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
185 return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
188 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
189 if (TT.isOSBinFormatMachO()) {
190 if (TT.getArch() == Triple::x86_64)
191 return new X86_64MachoTargetObjectFile();
192 return new TargetLoweringObjectFileMachO();
196 return new X86LinuxTargetObjectFile();
197 if (TT.isOSBinFormatELF())
198 return new TargetLoweringObjectFileELF();
199 if (TT.isKnownWindowsMSVCEnvironment())
200 return new X86WindowsTargetObjectFile();
201 if (TT.isOSBinFormatCOFF())
202 return new TargetLoweringObjectFileCOFF();
203 llvm_unreachable("unknown subtarget type");
206 // FIXME: This should stop caching the target machine as soon as
207 // we can remove resetOperationActions et al.
208 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
209 : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
210 Subtarget = &TM.getSubtarget<X86Subtarget>();
211 X86ScalarSSEf64 = Subtarget->hasSSE2();
212 X86ScalarSSEf32 = Subtarget->hasSSE1();
213 TD = getDataLayout();
215 resetOperationActions();
218 void X86TargetLowering::resetOperationActions() {
219 const TargetMachine &TM = getTargetMachine();
220 static bool FirstTimeThrough = true;
222 // If none of the target options have changed, then we don't need to reset the
223 // operation actions.
224 if (!FirstTimeThrough && TO == TM.Options) return;
226 if (!FirstTimeThrough) {
227 // Reinitialize the actions.
229 FirstTimeThrough = false;
234 // Set up the TargetLowering object.
235 static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
237 // X86 is weird, it always uses i8 for shift amounts and setcc results.
238 setBooleanContents(ZeroOrOneBooleanContent);
239 // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
240 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
242 // For 64-bit since we have so many registers use the ILP scheduler, for
243 // 32-bit code use the register pressure specific scheduling.
244 // For Atom, always use ILP scheduling.
245 if (Subtarget->isAtom())
246 setSchedulingPreference(Sched::ILP);
247 else if (Subtarget->is64Bit())
248 setSchedulingPreference(Sched::ILP);
250 setSchedulingPreference(Sched::RegPressure);
251 const X86RegisterInfo *RegInfo =
252 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
253 setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
255 // Bypass expensive divides on Atom when compiling with O2
256 if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
257 addBypassSlowDiv(32, 8);
258 if (Subtarget->is64Bit())
259 addBypassSlowDiv(64, 16);
262 if (Subtarget->isTargetKnownWindowsMSVC()) {
263 // Setup Windows compiler runtime calls.
264 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
265 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
266 setLibcallName(RTLIB::SREM_I64, "_allrem");
267 setLibcallName(RTLIB::UREM_I64, "_aullrem");
268 setLibcallName(RTLIB::MUL_I64, "_allmul");
269 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
270 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
271 setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
272 setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
273 setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
275 // The _ftol2 runtime function has an unusual calling conv, which
276 // is modeled by a special pseudo-instruction.
277 setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
278 setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
279 setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
280 setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
283 if (Subtarget->isTargetDarwin()) {
284 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
285 setUseUnderscoreSetJmp(false);
286 setUseUnderscoreLongJmp(false);
287 } else if (Subtarget->isTargetWindowsGNU()) {
288 // MS runtime is weird: it exports _setjmp, but longjmp!
289 setUseUnderscoreSetJmp(true);
290 setUseUnderscoreLongJmp(false);
292 setUseUnderscoreSetJmp(true);
293 setUseUnderscoreLongJmp(true);
296 // Set up the register classes.
297 addRegisterClass(MVT::i8, &X86::GR8RegClass);
298 addRegisterClass(MVT::i16, &X86::GR16RegClass);
299 addRegisterClass(MVT::i32, &X86::GR32RegClass);
300 if (Subtarget->is64Bit())
301 addRegisterClass(MVT::i64, &X86::GR64RegClass);
303 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
305 // We don't accept any truncstore of integer registers.
306 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
307 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
308 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
309 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
310 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
311 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
313 // SETOEQ and SETUNE require checking two conditions.
314 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
315 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
316 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
317 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
318 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
319 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
321 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
323 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
324 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
325 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
327 if (Subtarget->is64Bit()) {
328 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
329 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
330 } else if (!TM.Options.UseSoftFloat) {
331 // We have an algorithm for SSE2->double, and we turn this into a
332 // 64-bit FILD followed by conditional FADD for other targets.
333 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
334 // We have an algorithm for SSE2, and we turn this into a 64-bit
335 // FILD for other targets.
336 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
339 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
341 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
342 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
344 if (!TM.Options.UseSoftFloat) {
345 // SSE has no i16 to fp conversion, only i32
346 if (X86ScalarSSEf32) {
347 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
348 // f32 and f64 cases are Legal, f80 case is not
349 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
351 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
352 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
355 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
356 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
359 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
360 // are Legal, f80 is custom lowered.
361 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
362 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
364 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
366 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
367 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
369 if (X86ScalarSSEf32) {
370 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
371 // f32 and f64 cases are Legal, f80 case is not
372 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
374 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
375 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
378 // Handle FP_TO_UINT by promoting the destination to a larger signed
380 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
381 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
382 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
384 if (Subtarget->is64Bit()) {
385 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
386 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
387 } else if (!TM.Options.UseSoftFloat) {
388 // Since AVX is a superset of SSE3, only check for SSE here.
389 if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
390 // Expand FP_TO_UINT into a select.
391 // FIXME: We would like to use a Custom expander here eventually to do
392 // the optimal thing for SSE vs. the default expansion in the legalizer.
393 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
395 // With SSE3 we can use fisttpll to convert to a signed i64; without
396 // SSE, we're stuck with a fistpll.
397 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
400 if (isTargetFTOL()) {
401 // Use the _ftol2 runtime function, which has a pseudo-instruction
402 // to handle its weird calling convention.
403 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Custom);
406 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
407 if (!X86ScalarSSEf64) {
408 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
409 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
410 if (Subtarget->is64Bit()) {
411 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
412 // Without SSE, i64->f64 goes through memory.
413 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
417 // Scalar integer divide and remainder are lowered to use operations that
418 // produce two results, to match the available instructions. This exposes
419 // the two-result form to trivial CSE, which is able to combine x/y and x%y
420 // into a single instruction.
422 // Scalar integer multiply-high is also lowered to use two-result
423 // operations, to match the available instructions. However, plain multiply
424 // (low) operations are left as Legal, as there are single-result
425 // instructions for this in x86. Using the two-result multiply instructions
426 // when both high and low results are needed must be arranged by dagcombine.
427 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
429 setOperationAction(ISD::MULHS, VT, Expand);
430 setOperationAction(ISD::MULHU, VT, Expand);
431 setOperationAction(ISD::SDIV, VT, Expand);
432 setOperationAction(ISD::UDIV, VT, Expand);
433 setOperationAction(ISD::SREM, VT, Expand);
434 setOperationAction(ISD::UREM, VT, Expand);
436 // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
437 setOperationAction(ISD::ADDC, VT, Custom);
438 setOperationAction(ISD::ADDE, VT, Custom);
439 setOperationAction(ISD::SUBC, VT, Custom);
440 setOperationAction(ISD::SUBE, VT, Custom);
443 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
444 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
445 setOperationAction(ISD::BR_CC , MVT::f32, Expand);
446 setOperationAction(ISD::BR_CC , MVT::f64, Expand);
447 setOperationAction(ISD::BR_CC , MVT::f80, Expand);
448 setOperationAction(ISD::BR_CC , MVT::i8, Expand);
449 setOperationAction(ISD::BR_CC , MVT::i16, Expand);
450 setOperationAction(ISD::BR_CC , MVT::i32, Expand);
451 setOperationAction(ISD::BR_CC , MVT::i64, Expand);
452 setOperationAction(ISD::SELECT_CC , MVT::f32, Expand);
453 setOperationAction(ISD::SELECT_CC , MVT::f64, Expand);
454 setOperationAction(ISD::SELECT_CC , MVT::f80, Expand);
455 setOperationAction(ISD::SELECT_CC , MVT::i8, Expand);
456 setOperationAction(ISD::SELECT_CC , MVT::i16, Expand);
457 setOperationAction(ISD::SELECT_CC , MVT::i32, Expand);
458 setOperationAction(ISD::SELECT_CC , MVT::i64, Expand);
459 if (Subtarget->is64Bit())
460 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
461 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
462 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
463 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
464 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
465 setOperationAction(ISD::FREM , MVT::f32 , Expand);
466 setOperationAction(ISD::FREM , MVT::f64 , Expand);
467 setOperationAction(ISD::FREM , MVT::f80 , Expand);
468 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
470 // Promote the i8 variants and force them on up to i32 which has a shorter
472 setOperationAction(ISD::CTTZ , MVT::i8 , Promote);
473 AddPromotedToType (ISD::CTTZ , MVT::i8 , MVT::i32);
474 setOperationAction(ISD::CTTZ_ZERO_UNDEF , MVT::i8 , Promote);
475 AddPromotedToType (ISD::CTTZ_ZERO_UNDEF , MVT::i8 , MVT::i32);
476 if (Subtarget->hasBMI()) {
477 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16 , Expand);
478 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32 , Expand);
479 if (Subtarget->is64Bit())
480 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
482 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
483 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
484 if (Subtarget->is64Bit())
485 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
488 if (Subtarget->hasLZCNT()) {
489 // When promoting the i8 variants, force them to i32 for a shorter
491 setOperationAction(ISD::CTLZ , MVT::i8 , Promote);
492 AddPromotedToType (ISD::CTLZ , MVT::i8 , MVT::i32);
493 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Promote);
494 AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8 , MVT::i32);
495 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Expand);
496 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Expand);
497 if (Subtarget->is64Bit())
498 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
500 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
501 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
502 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
503 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8 , Custom);
504 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16 , Custom);
505 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32 , Custom);
506 if (Subtarget->is64Bit()) {
507 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
508 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
512 if (Subtarget->hasPOPCNT()) {
513 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
515 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
516 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
517 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
518 if (Subtarget->is64Bit())
519 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
522 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
524 if (!Subtarget->hasMOVBE())
525 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
527 // These should be promoted to a larger select which is supported.
528 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
529 // X86 wants to expand cmov itself.
530 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
531 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
532 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
533 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
534 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
535 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
536 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
537 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
538 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
539 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
540 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
541 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
542 if (Subtarget->is64Bit()) {
543 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
544 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
546 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
547 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
548 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
549 // support continuation, user-level threading, and etc.. As a result, no
550 // other SjLj exception interfaces are implemented and please don't build
551 // your own exception handling based on them.
552 // LLVM/Clang supports zero-cost DWARF exception handling.
553 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
554 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
557 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
558 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
559 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
560 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
561 if (Subtarget->is64Bit())
562 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
563 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
564 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
565 if (Subtarget->is64Bit()) {
566 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
567 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
568 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
569 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
570 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
572 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
573 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
574 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
575 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
576 if (Subtarget->is64Bit()) {
577 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
578 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
579 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
582 if (Subtarget->hasSSE1())
583 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
585 setOperationAction(ISD::ATOMIC_FENCE , MVT::Other, Custom);
587 // Expand certain atomics
588 for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
590 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
591 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
592 setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
595 if (Subtarget->hasCmpxchg16b()) {
596 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
599 // FIXME - use subtarget debug flags
600 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
601 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
602 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
605 if (Subtarget->is64Bit()) {
606 setExceptionPointerRegister(X86::RAX);
607 setExceptionSelectorRegister(X86::RDX);
609 setExceptionPointerRegister(X86::EAX);
610 setExceptionSelectorRegister(X86::EDX);
612 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
613 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
615 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
616 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
618 setOperationAction(ISD::TRAP, MVT::Other, Legal);
619 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
621 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
622 setOperationAction(ISD::VASTART , MVT::Other, Custom);
623 setOperationAction(ISD::VAEND , MVT::Other, Expand);
624 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
625 // TargetInfo::X86_64ABIBuiltinVaList
626 setOperationAction(ISD::VAARG , MVT::Other, Custom);
627 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
629 // TargetInfo::CharPtrBuiltinVaList
630 setOperationAction(ISD::VAARG , MVT::Other, Expand);
631 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
634 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
635 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
637 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
638 MVT::i64 : MVT::i32, Custom);
640 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
641 // f32 and f64 use SSE.
642 // Set up the FP register classes.
643 addRegisterClass(MVT::f32, &X86::FR32RegClass);
644 addRegisterClass(MVT::f64, &X86::FR64RegClass);
646 // Use ANDPD to simulate FABS.
647 setOperationAction(ISD::FABS , MVT::f64, Custom);
648 setOperationAction(ISD::FABS , MVT::f32, Custom);
650 // Use XORP to simulate FNEG.
651 setOperationAction(ISD::FNEG , MVT::f64, Custom);
652 setOperationAction(ISD::FNEG , MVT::f32, Custom);
654 // Use ANDPD and ORPD to simulate FCOPYSIGN.
655 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
656 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
658 // Lower this to FGETSIGNx86 plus an AND.
659 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
660 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
662 // We don't support sin/cos/fmod
663 setOperationAction(ISD::FSIN , MVT::f64, Expand);
664 setOperationAction(ISD::FCOS , MVT::f64, Expand);
665 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
666 setOperationAction(ISD::FSIN , MVT::f32, Expand);
667 setOperationAction(ISD::FCOS , MVT::f32, Expand);
668 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
670 // Expand FP immediates into loads from the stack, except for the special
672 addLegalFPImmediate(APFloat(+0.0)); // xorpd
673 addLegalFPImmediate(APFloat(+0.0f)); // xorps
674 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
675 // Use SSE for f32, x87 for f64.
676 // Set up the FP register classes.
677 addRegisterClass(MVT::f32, &X86::FR32RegClass);
678 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
680 // Use ANDPS to simulate FABS.
681 setOperationAction(ISD::FABS , MVT::f32, Custom);
683 // Use XORP to simulate FNEG.
684 setOperationAction(ISD::FNEG , MVT::f32, Custom);
686 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
688 // Use ANDPS and ORPS to simulate FCOPYSIGN.
689 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
690 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
692 // We don't support sin/cos/fmod
693 setOperationAction(ISD::FSIN , MVT::f32, Expand);
694 setOperationAction(ISD::FCOS , MVT::f32, Expand);
695 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
697 // Special cases we handle for FP constants.
698 addLegalFPImmediate(APFloat(+0.0f)); // xorps
699 addLegalFPImmediate(APFloat(+0.0)); // FLD0
700 addLegalFPImmediate(APFloat(+1.0)); // FLD1
701 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
702 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
704 if (!TM.Options.UnsafeFPMath) {
705 setOperationAction(ISD::FSIN , MVT::f64, Expand);
706 setOperationAction(ISD::FCOS , MVT::f64, Expand);
707 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
709 } else if (!TM.Options.UseSoftFloat) {
710 // f32 and f64 in x87.
711 // Set up the FP register classes.
712 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
713 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
715 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
716 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
717 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
718 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
720 if (!TM.Options.UnsafeFPMath) {
721 setOperationAction(ISD::FSIN , MVT::f64, Expand);
722 setOperationAction(ISD::FSIN , MVT::f32, Expand);
723 setOperationAction(ISD::FCOS , MVT::f64, Expand);
724 setOperationAction(ISD::FCOS , MVT::f32, Expand);
725 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
726 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
728 addLegalFPImmediate(APFloat(+0.0)); // FLD0
729 addLegalFPImmediate(APFloat(+1.0)); // FLD1
730 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
731 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
732 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
733 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
734 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
735 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
738 // We don't support FMA.
739 setOperationAction(ISD::FMA, MVT::f64, Expand);
740 setOperationAction(ISD::FMA, MVT::f32, Expand);
742 // Long double always uses X87.
743 if (!TM.Options.UseSoftFloat) {
744 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
745 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
746 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
748 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
749 addLegalFPImmediate(TmpFlt); // FLD0
751 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
754 APFloat TmpFlt2(+1.0);
755 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
757 addLegalFPImmediate(TmpFlt2); // FLD1
758 TmpFlt2.changeSign();
759 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
762 if (!TM.Options.UnsafeFPMath) {
763 setOperationAction(ISD::FSIN , MVT::f80, Expand);
764 setOperationAction(ISD::FCOS , MVT::f80, Expand);
765 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
768 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
769 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
770 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
771 setOperationAction(ISD::FRINT, MVT::f80, Expand);
772 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
773 setOperationAction(ISD::FMA, MVT::f80, Expand);
776 // Always use a library call for pow.
777 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
778 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
779 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
781 setOperationAction(ISD::FLOG, MVT::f80, Expand);
782 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
783 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
784 setOperationAction(ISD::FEXP, MVT::f80, Expand);
785 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
787 // First set operation action for all vector types to either promote
788 // (for widening) or expand (for scalarization). Then we will selectively
789 // turn on ones that can be effectively codegen'd.
790 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
791 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
792 MVT VT = (MVT::SimpleValueType)i;
793 setOperationAction(ISD::ADD , VT, Expand);
794 setOperationAction(ISD::SUB , VT, Expand);
795 setOperationAction(ISD::FADD, VT, Expand);
796 setOperationAction(ISD::FNEG, VT, Expand);
797 setOperationAction(ISD::FSUB, VT, Expand);
798 setOperationAction(ISD::MUL , VT, Expand);
799 setOperationAction(ISD::FMUL, VT, Expand);
800 setOperationAction(ISD::SDIV, VT, Expand);
801 setOperationAction(ISD::UDIV, VT, Expand);
802 setOperationAction(ISD::FDIV, VT, Expand);
803 setOperationAction(ISD::SREM, VT, Expand);
804 setOperationAction(ISD::UREM, VT, Expand);
805 setOperationAction(ISD::LOAD, VT, Expand);
806 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
807 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
808 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
809 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
810 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
811 setOperationAction(ISD::FABS, VT, Expand);
812 setOperationAction(ISD::FSIN, VT, Expand);
813 setOperationAction(ISD::FSINCOS, VT, Expand);
814 setOperationAction(ISD::FCOS, VT, Expand);
815 setOperationAction(ISD::FSINCOS, VT, Expand);
816 setOperationAction(ISD::FREM, VT, Expand);
817 setOperationAction(ISD::FMA, VT, Expand);
818 setOperationAction(ISD::FPOWI, VT, Expand);
819 setOperationAction(ISD::FSQRT, VT, Expand);
820 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
821 setOperationAction(ISD::FFLOOR, VT, Expand);
822 setOperationAction(ISD::FCEIL, VT, Expand);
823 setOperationAction(ISD::FTRUNC, VT, Expand);
824 setOperationAction(ISD::FRINT, VT, Expand);
825 setOperationAction(ISD::FNEARBYINT, VT, Expand);
826 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
827 setOperationAction(ISD::MULHS, VT, Expand);
828 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
829 setOperationAction(ISD::MULHU, VT, Expand);
830 setOperationAction(ISD::SDIVREM, VT, Expand);
831 setOperationAction(ISD::UDIVREM, VT, Expand);
832 setOperationAction(ISD::FPOW, VT, Expand);
833 setOperationAction(ISD::CTPOP, VT, Expand);
834 setOperationAction(ISD::CTTZ, VT, Expand);
835 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
836 setOperationAction(ISD::CTLZ, VT, Expand);
837 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
838 setOperationAction(ISD::SHL, VT, Expand);
839 setOperationAction(ISD::SRA, VT, Expand);
840 setOperationAction(ISD::SRL, VT, Expand);
841 setOperationAction(ISD::ROTL, VT, Expand);
842 setOperationAction(ISD::ROTR, VT, Expand);
843 setOperationAction(ISD::BSWAP, VT, Expand);
844 setOperationAction(ISD::SETCC, VT, Expand);
845 setOperationAction(ISD::FLOG, VT, Expand);
846 setOperationAction(ISD::FLOG2, VT, Expand);
847 setOperationAction(ISD::FLOG10, VT, Expand);
848 setOperationAction(ISD::FEXP, VT, Expand);
849 setOperationAction(ISD::FEXP2, VT, Expand);
850 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
851 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
852 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
853 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
854 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
855 setOperationAction(ISD::TRUNCATE, VT, Expand);
856 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
857 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
858 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
859 setOperationAction(ISD::VSELECT, VT, Expand);
860 setOperationAction(ISD::SELECT_CC, VT, Expand);
861 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
862 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
863 setTruncStoreAction(VT,
864 (MVT::SimpleValueType)InnerVT, Expand);
865 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
866 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
867 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
870 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
871 // with -msoft-float, disable use of MMX as well.
872 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
873 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
874 // No operations on x86mmx supported, everything uses intrinsics.
877 // MMX-sized vectors (other than x86mmx) are expected to be expanded
878 // into smaller operations.
879 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
880 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
881 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
882 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
883 setOperationAction(ISD::AND, MVT::v8i8, Expand);
884 setOperationAction(ISD::AND, MVT::v4i16, Expand);
885 setOperationAction(ISD::AND, MVT::v2i32, Expand);
886 setOperationAction(ISD::AND, MVT::v1i64, Expand);
887 setOperationAction(ISD::OR, MVT::v8i8, Expand);
888 setOperationAction(ISD::OR, MVT::v4i16, Expand);
889 setOperationAction(ISD::OR, MVT::v2i32, Expand);
890 setOperationAction(ISD::OR, MVT::v1i64, Expand);
891 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
892 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
893 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
894 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
895 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
896 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
897 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
898 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
899 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
900 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
901 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
902 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
903 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
904 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
905 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
906 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
907 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
909 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
910 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
912 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
913 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
914 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
915 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
916 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
917 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
918 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
919 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
920 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
921 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
922 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
923 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
926 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
927 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
929 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
930 // registers cannot be used even for integer operations.
931 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
932 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
933 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
934 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
936 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
937 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
938 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
939 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
940 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
941 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
942 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
943 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
944 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
945 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
946 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
947 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
948 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
949 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
950 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
951 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
952 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
953 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
954 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
955 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
956 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
957 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
959 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
960 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
961 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
962 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
964 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
965 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
966 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
967 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
968 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
970 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
971 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
972 MVT VT = (MVT::SimpleValueType)i;
973 // Do not attempt to custom lower non-power-of-2 vectors
974 if (!isPowerOf2_32(VT.getVectorNumElements()))
976 // Do not attempt to custom lower non-128-bit vectors
977 if (!VT.is128BitVector())
979 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
980 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
981 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
984 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
985 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
986 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
987 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
988 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
989 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
991 if (Subtarget->is64Bit()) {
992 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
993 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
996 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
997 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
998 MVT VT = (MVT::SimpleValueType)i;
1000 // Do not attempt to promote non-128-bit vectors
1001 if (!VT.is128BitVector())
1004 setOperationAction(ISD::AND, VT, Promote);
1005 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1006 setOperationAction(ISD::OR, VT, Promote);
1007 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1008 setOperationAction(ISD::XOR, VT, Promote);
1009 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1010 setOperationAction(ISD::LOAD, VT, Promote);
1011 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1012 setOperationAction(ISD::SELECT, VT, Promote);
1013 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1016 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1018 // Custom lower v2i64 and v2f64 selects.
1019 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1020 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1021 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1022 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1024 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1025 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1027 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1028 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1029 // As there is no 64-bit GPR available, we need build a special custom
1030 // sequence to convert from v2i32 to v2f32.
1031 if (!Subtarget->is64Bit())
1032 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1034 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1035 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1037 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1039 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1040 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1041 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1044 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1045 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1046 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1047 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1048 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1049 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1050 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1051 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1052 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1053 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1054 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1056 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1057 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1058 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1059 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1060 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1061 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1062 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1063 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1064 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1065 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1067 // FIXME: Do we need to handle scalar-to-vector here?
1068 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1070 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1071 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1072 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1073 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1074 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1075 // There is no BLENDI for byte vectors. We don't need to custom lower
1076 // some vselects for now.
1077 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1079 // i8 and i16 vectors are custom , because the source register and source
1080 // source memory operand types are not the same width. f32 vectors are
1081 // custom since the immediate controlling the insert encodes additional
1083 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1084 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1085 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1086 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1088 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1089 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1090 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1091 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1093 // FIXME: these should be Legal but thats only for the case where
1094 // the index is constant. For now custom expand to deal with that.
1095 if (Subtarget->is64Bit()) {
1096 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1097 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1101 if (Subtarget->hasSSE2()) {
1102 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1103 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1105 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1106 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1108 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1109 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1111 // In the customized shift lowering, the legal cases in AVX2 will be
1113 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1114 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1116 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1117 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1119 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1122 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1123 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1124 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1125 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1126 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1127 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1128 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1130 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1131 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1132 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1134 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1135 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1136 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1137 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1138 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1139 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1140 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1141 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1142 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1143 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1144 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1145 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1147 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1148 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1149 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1150 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1151 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1152 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1153 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1154 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1155 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1156 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1157 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1158 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1160 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1161 // even though v8i16 is a legal type.
1162 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1163 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1164 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1166 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1167 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1168 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1170 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1171 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1173 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1175 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1176 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1178 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1179 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1181 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1182 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1184 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1185 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1186 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1187 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1189 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1190 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1191 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1193 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1194 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1195 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1196 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1198 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1199 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1200 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1201 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1202 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1203 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1204 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1205 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1206 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1207 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1208 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1209 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1211 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1212 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1213 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1214 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1215 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1216 setOperationAction(ISD::FMA, MVT::f32, Legal);
1217 setOperationAction(ISD::FMA, MVT::f64, Legal);
1220 if (Subtarget->hasInt256()) {
1221 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1222 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1223 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1224 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1226 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1227 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1228 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1229 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1231 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1232 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1233 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1234 // Don't lower v32i8 because there is no 128-bit byte mul
1236 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1237 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1238 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1239 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1241 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1242 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1244 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1245 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1246 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1247 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1249 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1250 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1251 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1252 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1254 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1255 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1256 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1257 // Don't lower v32i8 because there is no 128-bit byte mul
1260 // In the customized shift lowering, the legal cases in AVX2 will be
1262 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1263 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1265 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1266 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1268 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1270 // Custom lower several nodes for 256-bit types.
1271 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1272 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1273 MVT VT = (MVT::SimpleValueType)i;
1275 // Extract subvector is special because the value type
1276 // (result) is 128-bit but the source is 256-bit wide.
1277 if (VT.is128BitVector())
1278 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1280 // Do not attempt to custom lower other non-256-bit vectors
1281 if (!VT.is256BitVector())
1284 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1285 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1286 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1287 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1288 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1289 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1290 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1293 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1294 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1295 MVT VT = (MVT::SimpleValueType)i;
1297 // Do not attempt to promote non-256-bit vectors
1298 if (!VT.is256BitVector())
1301 setOperationAction(ISD::AND, VT, Promote);
1302 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1303 setOperationAction(ISD::OR, VT, Promote);
1304 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1305 setOperationAction(ISD::XOR, VT, Promote);
1306 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1307 setOperationAction(ISD::LOAD, VT, Promote);
1308 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1309 setOperationAction(ISD::SELECT, VT, Promote);
1310 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1314 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1315 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1316 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1317 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1318 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1320 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1321 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1322 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1324 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1325 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1326 setOperationAction(ISD::XOR, MVT::i1, Legal);
1327 setOperationAction(ISD::OR, MVT::i1, Legal);
1328 setOperationAction(ISD::AND, MVT::i1, Legal);
1329 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1330 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1331 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1332 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1333 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1334 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1336 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1337 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1338 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1339 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1340 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1341 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1343 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1344 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1345 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1346 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1347 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1348 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1349 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1350 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1352 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1353 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1354 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1355 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1356 if (Subtarget->is64Bit()) {
1357 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1358 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1359 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1360 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1362 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1363 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1364 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1365 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1366 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1367 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1368 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1369 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1370 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1371 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1373 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1374 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1375 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1376 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1377 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1378 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1379 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1380 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1381 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1382 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1383 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1384 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1385 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1387 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1388 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1389 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1390 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1391 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1392 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1394 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1395 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1397 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1399 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1400 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1401 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1402 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1403 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1404 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1405 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1406 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1407 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1409 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1410 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1412 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1413 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1415 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1417 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1418 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1420 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1421 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1423 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1424 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1426 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1427 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1428 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1429 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1430 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1431 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1433 if (Subtarget->hasCDI()) {
1434 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1435 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1438 // Custom lower several nodes.
1439 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1440 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1441 MVT VT = (MVT::SimpleValueType)i;
1443 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1444 // Extract subvector is special because the value type
1445 // (result) is 256/128-bit but the source is 512-bit wide.
1446 if (VT.is128BitVector() || VT.is256BitVector())
1447 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1449 if (VT.getVectorElementType() == MVT::i1)
1450 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1452 // Do not attempt to custom lower other non-512-bit vectors
1453 if (!VT.is512BitVector())
1456 if ( EltSize >= 32) {
1457 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1458 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1459 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1460 setOperationAction(ISD::VSELECT, VT, Legal);
1461 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1462 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1463 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1466 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1467 MVT VT = (MVT::SimpleValueType)i;
1469 // Do not attempt to promote non-256-bit vectors
1470 if (!VT.is512BitVector())
1473 setOperationAction(ISD::SELECT, VT, Promote);
1474 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1478 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1479 // of this type with custom code.
1480 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1481 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1482 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1486 // We want to custom lower some of our intrinsics.
1487 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1488 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1489 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1490 if (!Subtarget->is64Bit())
1491 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1493 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1494 // handle type legalization for these operations here.
1496 // FIXME: We really should do custom legalization for addition and
1497 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1498 // than generic legalization for 64-bit multiplication-with-overflow, though.
1499 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1500 // Add/Sub/Mul with overflow operations are custom lowered.
1502 setOperationAction(ISD::SADDO, VT, Custom);
1503 setOperationAction(ISD::UADDO, VT, Custom);
1504 setOperationAction(ISD::SSUBO, VT, Custom);
1505 setOperationAction(ISD::USUBO, VT, Custom);
1506 setOperationAction(ISD::SMULO, VT, Custom);
1507 setOperationAction(ISD::UMULO, VT, Custom);
1510 // There are no 8-bit 3-address imul/mul instructions
1511 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1512 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1514 if (!Subtarget->is64Bit()) {
1515 // These libcalls are not available in 32-bit.
1516 setLibcallName(RTLIB::SHL_I128, nullptr);
1517 setLibcallName(RTLIB::SRL_I128, nullptr);
1518 setLibcallName(RTLIB::SRA_I128, nullptr);
1521 // Combine sin / cos into one node or libcall if possible.
1522 if (Subtarget->hasSinCos()) {
1523 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1524 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1525 if (Subtarget->isTargetDarwin()) {
1526 // For MacOSX, we don't want to the normal expansion of a libcall to
1527 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1529 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1530 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1534 if (Subtarget->isTargetWin64()) {
1535 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1536 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1537 setOperationAction(ISD::SREM, MVT::i128, Custom);
1538 setOperationAction(ISD::UREM, MVT::i128, Custom);
1539 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1540 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1543 // We have target-specific dag combine patterns for the following nodes:
1544 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1545 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1546 setTargetDAGCombine(ISD::VSELECT);
1547 setTargetDAGCombine(ISD::SELECT);
1548 setTargetDAGCombine(ISD::SHL);
1549 setTargetDAGCombine(ISD::SRA);
1550 setTargetDAGCombine(ISD::SRL);
1551 setTargetDAGCombine(ISD::OR);
1552 setTargetDAGCombine(ISD::AND);
1553 setTargetDAGCombine(ISD::ADD);
1554 setTargetDAGCombine(ISD::FADD);
1555 setTargetDAGCombine(ISD::FSUB);
1556 setTargetDAGCombine(ISD::FMA);
1557 setTargetDAGCombine(ISD::SUB);
1558 setTargetDAGCombine(ISD::LOAD);
1559 setTargetDAGCombine(ISD::STORE);
1560 setTargetDAGCombine(ISD::ZERO_EXTEND);
1561 setTargetDAGCombine(ISD::ANY_EXTEND);
1562 setTargetDAGCombine(ISD::SIGN_EXTEND);
1563 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1564 setTargetDAGCombine(ISD::TRUNCATE);
1565 setTargetDAGCombine(ISD::SINT_TO_FP);
1566 setTargetDAGCombine(ISD::SETCC);
1567 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1568 setTargetDAGCombine(ISD::BUILD_VECTOR);
1569 if (Subtarget->is64Bit())
1570 setTargetDAGCombine(ISD::MUL);
1571 setTargetDAGCombine(ISD::XOR);
1573 computeRegisterProperties();
1575 // On Darwin, -Os means optimize for size without hurting performance,
1576 // do not reduce the limit.
1577 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1578 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1579 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1580 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1581 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1582 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1583 setPrefLoopAlignment(4); // 2^4 bytes.
1585 // Predictable cmov don't hurt on atom because it's in-order.
1586 PredictableSelectIsExpensive = !Subtarget->isAtom();
1588 setPrefFunctionAlignment(4); // 2^4 bytes.
1591 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1593 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1595 if (Subtarget->hasAVX512())
1596 switch(VT.getVectorNumElements()) {
1597 case 8: return MVT::v8i1;
1598 case 16: return MVT::v16i1;
1601 return VT.changeVectorElementTypeToInteger();
1604 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1605 /// the desired ByVal argument alignment.
1606 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1609 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1610 if (VTy->getBitWidth() == 128)
1612 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1613 unsigned EltAlign = 0;
1614 getMaxByValAlign(ATy->getElementType(), EltAlign);
1615 if (EltAlign > MaxAlign)
1616 MaxAlign = EltAlign;
1617 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1618 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1619 unsigned EltAlign = 0;
1620 getMaxByValAlign(STy->getElementType(i), EltAlign);
1621 if (EltAlign > MaxAlign)
1622 MaxAlign = EltAlign;
1629 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1630 /// function arguments in the caller parameter area. For X86, aggregates
1631 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1632 /// are at 4-byte boundaries.
1633 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1634 if (Subtarget->is64Bit()) {
1635 // Max of 8 and alignment of type.
1636 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1643 if (Subtarget->hasSSE1())
1644 getMaxByValAlign(Ty, Align);
1648 /// getOptimalMemOpType - Returns the target specific optimal type for load
1649 /// and store operations as a result of memset, memcpy, and memmove
1650 /// lowering. If DstAlign is zero that means it's safe to destination
1651 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1652 /// means there isn't a need to check it against alignment requirement,
1653 /// probably because the source does not need to be loaded. If 'IsMemset' is
1654 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1655 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1656 /// source is constant so it does not need to be loaded.
1657 /// It returns EVT::Other if the type should be determined using generic
1658 /// target-independent logic.
1660 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1661 unsigned DstAlign, unsigned SrcAlign,
1662 bool IsMemset, bool ZeroMemset,
1664 MachineFunction &MF) const {
1665 const Function *F = MF.getFunction();
1666 if ((!IsMemset || ZeroMemset) &&
1667 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1668 Attribute::NoImplicitFloat)) {
1670 (Subtarget->isUnalignedMemAccessFast() ||
1671 ((DstAlign == 0 || DstAlign >= 16) &&
1672 (SrcAlign == 0 || SrcAlign >= 16)))) {
1674 if (Subtarget->hasInt256())
1676 if (Subtarget->hasFp256())
1679 if (Subtarget->hasSSE2())
1681 if (Subtarget->hasSSE1())
1683 } else if (!MemcpyStrSrc && Size >= 8 &&
1684 !Subtarget->is64Bit() &&
1685 Subtarget->hasSSE2()) {
1686 // Do not use f64 to lower memcpy if source is string constant. It's
1687 // better to use i32 to avoid the loads.
1691 if (Subtarget->is64Bit() && Size >= 8)
1696 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1698 return X86ScalarSSEf32;
1699 else if (VT == MVT::f64)
1700 return X86ScalarSSEf64;
1705 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1709 *Fast = Subtarget->isUnalignedMemAccessFast();
1713 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1714 /// current function. The returned value is a member of the
1715 /// MachineJumpTableInfo::JTEntryKind enum.
1716 unsigned X86TargetLowering::getJumpTableEncoding() const {
1717 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1719 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1720 Subtarget->isPICStyleGOT())
1721 return MachineJumpTableInfo::EK_Custom32;
1723 // Otherwise, use the normal jump table encoding heuristics.
1724 return TargetLowering::getJumpTableEncoding();
1728 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1729 const MachineBasicBlock *MBB,
1730 unsigned uid,MCContext &Ctx) const{
1731 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1732 Subtarget->isPICStyleGOT());
1733 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1735 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1736 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1739 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1741 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1742 SelectionDAG &DAG) const {
1743 if (!Subtarget->is64Bit())
1744 // This doesn't have SDLoc associated with it, but is not really the
1745 // same as a Register.
1746 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1750 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1751 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1753 const MCExpr *X86TargetLowering::
1754 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1755 MCContext &Ctx) const {
1756 // X86-64 uses RIP relative addressing based on the jump table label.
1757 if (Subtarget->isPICStyleRIPRel())
1758 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1760 // Otherwise, the reference is relative to the PIC base.
1761 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1764 // FIXME: Why this routine is here? Move to RegInfo!
1765 std::pair<const TargetRegisterClass*, uint8_t>
1766 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1767 const TargetRegisterClass *RRC = nullptr;
1769 switch (VT.SimpleTy) {
1771 return TargetLowering::findRepresentativeClass(VT);
1772 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1773 RRC = Subtarget->is64Bit() ?
1774 (const TargetRegisterClass*)&X86::GR64RegClass :
1775 (const TargetRegisterClass*)&X86::GR32RegClass;
1778 RRC = &X86::VR64RegClass;
1780 case MVT::f32: case MVT::f64:
1781 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1782 case MVT::v4f32: case MVT::v2f64:
1783 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1785 RRC = &X86::VR128RegClass;
1788 return std::make_pair(RRC, Cost);
1791 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1792 unsigned &Offset) const {
1793 if (!Subtarget->isTargetLinux())
1796 if (Subtarget->is64Bit()) {
1797 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1799 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1811 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1812 unsigned DestAS) const {
1813 assert(SrcAS != DestAS && "Expected different address spaces!");
1815 return SrcAS < 256 && DestAS < 256;
1818 //===----------------------------------------------------------------------===//
1819 // Return Value Calling Convention Implementation
1820 //===----------------------------------------------------------------------===//
1822 #include "X86GenCallingConv.inc"
1825 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1826 MachineFunction &MF, bool isVarArg,
1827 const SmallVectorImpl<ISD::OutputArg> &Outs,
1828 LLVMContext &Context) const {
1829 SmallVector<CCValAssign, 16> RVLocs;
1830 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1832 return CCInfo.CheckReturn(Outs, RetCC_X86);
1835 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1836 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1841 X86TargetLowering::LowerReturn(SDValue Chain,
1842 CallingConv::ID CallConv, bool isVarArg,
1843 const SmallVectorImpl<ISD::OutputArg> &Outs,
1844 const SmallVectorImpl<SDValue> &OutVals,
1845 SDLoc dl, SelectionDAG &DAG) const {
1846 MachineFunction &MF = DAG.getMachineFunction();
1847 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1849 SmallVector<CCValAssign, 16> RVLocs;
1850 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1851 RVLocs, *DAG.getContext());
1852 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1855 SmallVector<SDValue, 6> RetOps;
1856 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1857 // Operand #1 = Bytes To Pop
1858 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1861 // Copy the result values into the output registers.
1862 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1863 CCValAssign &VA = RVLocs[i];
1864 assert(VA.isRegLoc() && "Can only return in registers!");
1865 SDValue ValToCopy = OutVals[i];
1866 EVT ValVT = ValToCopy.getValueType();
1868 // Promote values to the appropriate types
1869 if (VA.getLocInfo() == CCValAssign::SExt)
1870 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1871 else if (VA.getLocInfo() == CCValAssign::ZExt)
1872 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1873 else if (VA.getLocInfo() == CCValAssign::AExt)
1874 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1875 else if (VA.getLocInfo() == CCValAssign::BCvt)
1876 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1878 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1879 "Unexpected FP-extend for return value.");
1881 // If this is x86-64, and we disabled SSE, we can't return FP values,
1882 // or SSE or MMX vectors.
1883 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1884 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1885 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1886 report_fatal_error("SSE register return with SSE disabled");
1888 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1889 // llvm-gcc has never done it right and no one has noticed, so this
1890 // should be OK for now.
1891 if (ValVT == MVT::f64 &&
1892 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1893 report_fatal_error("SSE2 register return with SSE2 disabled");
1895 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1896 // the RET instruction and handled by the FP Stackifier.
1897 if (VA.getLocReg() == X86::ST0 ||
1898 VA.getLocReg() == X86::ST1) {
1899 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1900 // change the value to the FP stack register class.
1901 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1902 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1903 RetOps.push_back(ValToCopy);
1904 // Don't emit a copytoreg.
1908 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1909 // which is returned in RAX / RDX.
1910 if (Subtarget->is64Bit()) {
1911 if (ValVT == MVT::x86mmx) {
1912 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1913 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1914 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1916 // If we don't have SSE2 available, convert to v4f32 so the generated
1917 // register is legal.
1918 if (!Subtarget->hasSSE2())
1919 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1924 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1925 Flag = Chain.getValue(1);
1926 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1929 // The x86-64 ABIs require that for returning structs by value we copy
1930 // the sret argument into %rax/%eax (depending on ABI) for the return.
1931 // Win32 requires us to put the sret argument to %eax as well.
1932 // We saved the argument into a virtual register in the entry block,
1933 // so now we copy the value out and into %rax/%eax.
1934 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1935 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1936 MachineFunction &MF = DAG.getMachineFunction();
1937 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1938 unsigned Reg = FuncInfo->getSRetReturnReg();
1940 "SRetReturnReg should have been set in LowerFormalArguments().");
1941 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1944 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1945 X86::RAX : X86::EAX;
1946 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1947 Flag = Chain.getValue(1);
1949 // RAX/EAX now acts like a return value.
1950 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1953 RetOps[0] = Chain; // Update chain.
1955 // Add the flag if we have it.
1957 RetOps.push_back(Flag);
1959 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1962 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1963 if (N->getNumValues() != 1)
1965 if (!N->hasNUsesOfValue(1, 0))
1968 SDValue TCChain = Chain;
1969 SDNode *Copy = *N->use_begin();
1970 if (Copy->getOpcode() == ISD::CopyToReg) {
1971 // If the copy has a glue operand, we conservatively assume it isn't safe to
1972 // perform a tail call.
1973 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1975 TCChain = Copy->getOperand(0);
1976 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1979 bool HasRet = false;
1980 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1982 if (UI->getOpcode() != X86ISD::RET_FLAG)
1995 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1996 ISD::NodeType ExtendKind) const {
1998 // TODO: Is this also valid on 32-bit?
1999 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2000 ReturnMVT = MVT::i8;
2002 ReturnMVT = MVT::i32;
2004 MVT MinVT = getRegisterType(ReturnMVT);
2005 return VT.bitsLT(MinVT) ? MinVT : VT;
2008 /// LowerCallResult - Lower the result values of a call into the
2009 /// appropriate copies out of appropriate physical registers.
2012 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2013 CallingConv::ID CallConv, bool isVarArg,
2014 const SmallVectorImpl<ISD::InputArg> &Ins,
2015 SDLoc dl, SelectionDAG &DAG,
2016 SmallVectorImpl<SDValue> &InVals) const {
2018 // Assign locations to each value returned by this call.
2019 SmallVector<CCValAssign, 16> RVLocs;
2020 bool Is64Bit = Subtarget->is64Bit();
2021 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2022 DAG.getTarget(), RVLocs, *DAG.getContext());
2023 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2025 // Copy all of the result registers out of their specified physreg.
2026 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2027 CCValAssign &VA = RVLocs[i];
2028 EVT CopyVT = VA.getValVT();
2030 // If this is x86-64, and we disabled SSE, we can't return FP values
2031 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2032 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2033 report_fatal_error("SSE register return with SSE disabled");
2038 // If this is a call to a function that returns an fp value on the floating
2039 // point stack, we must guarantee the value is popped from the stack, so
2040 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2041 // if the return value is not used. We use the FpPOP_RETVAL instruction
2043 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2044 // If we prefer to use the value in xmm registers, copy it out as f80 and
2045 // use a truncate to move it from fp stack reg to xmm reg.
2046 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2047 SDValue Ops[] = { Chain, InFlag };
2048 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2049 MVT::Other, MVT::Glue, Ops), 1);
2050 Val = Chain.getValue(0);
2052 // Round the f80 to the right size, which also moves it to the appropriate
2054 if (CopyVT != VA.getValVT())
2055 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2056 // This truncation won't change the value.
2057 DAG.getIntPtrConstant(1));
2059 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2060 CopyVT, InFlag).getValue(1);
2061 Val = Chain.getValue(0);
2063 InFlag = Chain.getValue(2);
2064 InVals.push_back(Val);
2070 //===----------------------------------------------------------------------===//
2071 // C & StdCall & Fast Calling Convention implementation
2072 //===----------------------------------------------------------------------===//
2073 // StdCall calling convention seems to be standard for many Windows' API
2074 // routines and around. It differs from C calling convention just a little:
2075 // callee should clean up the stack, not caller. Symbols should be also
2076 // decorated in some fancy way :) It doesn't support any vector arguments.
2077 // For info on fast calling convention see Fast Calling Convention (tail call)
2078 // implementation LowerX86_32FastCCCallTo.
2080 /// CallIsStructReturn - Determines whether a call uses struct return
2082 enum StructReturnType {
2087 static StructReturnType
2088 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2090 return NotStructReturn;
2092 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2093 if (!Flags.isSRet())
2094 return NotStructReturn;
2095 if (Flags.isInReg())
2096 return RegStructReturn;
2097 return StackStructReturn;
2100 /// ArgsAreStructReturn - Determines whether a function uses struct
2101 /// return semantics.
2102 static StructReturnType
2103 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2105 return NotStructReturn;
2107 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2108 if (!Flags.isSRet())
2109 return NotStructReturn;
2110 if (Flags.isInReg())
2111 return RegStructReturn;
2112 return StackStructReturn;
2115 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2116 /// by "Src" to address "Dst" with size and alignment information specified by
2117 /// the specific parameter attribute. The copy will be passed as a byval
2118 /// function parameter.
2120 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2121 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2123 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2125 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2126 /*isVolatile*/false, /*AlwaysInline=*/true,
2127 MachinePointerInfo(), MachinePointerInfo());
2130 /// IsTailCallConvention - Return true if the calling convention is one that
2131 /// supports tail call optimization.
2132 static bool IsTailCallConvention(CallingConv::ID CC) {
2133 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2134 CC == CallingConv::HiPE);
2137 /// \brief Return true if the calling convention is a C calling convention.
2138 static bool IsCCallConvention(CallingConv::ID CC) {
2139 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2140 CC == CallingConv::X86_64_SysV);
2143 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2144 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2148 CallingConv::ID CalleeCC = CS.getCallingConv();
2149 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2155 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2156 /// a tailcall target by changing its ABI.
2157 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2158 bool GuaranteedTailCallOpt) {
2159 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2163 X86TargetLowering::LowerMemArgument(SDValue Chain,
2164 CallingConv::ID CallConv,
2165 const SmallVectorImpl<ISD::InputArg> &Ins,
2166 SDLoc dl, SelectionDAG &DAG,
2167 const CCValAssign &VA,
2168 MachineFrameInfo *MFI,
2170 // Create the nodes corresponding to a load from this parameter slot.
2171 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2172 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2173 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2174 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2177 // If value is passed by pointer we have address passed instead of the value
2179 if (VA.getLocInfo() == CCValAssign::Indirect)
2180 ValVT = VA.getLocVT();
2182 ValVT = VA.getValVT();
2184 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2185 // changed with more analysis.
2186 // In case of tail call optimization mark all arguments mutable. Since they
2187 // could be overwritten by lowering of arguments in case of a tail call.
2188 if (Flags.isByVal()) {
2189 unsigned Bytes = Flags.getByValSize();
2190 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2191 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2192 return DAG.getFrameIndex(FI, getPointerTy());
2194 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2195 VA.getLocMemOffset(), isImmutable);
2196 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2197 return DAG.getLoad(ValVT, dl, Chain, FIN,
2198 MachinePointerInfo::getFixedStack(FI),
2199 false, false, false, 0);
2204 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2205 CallingConv::ID CallConv,
2207 const SmallVectorImpl<ISD::InputArg> &Ins,
2210 SmallVectorImpl<SDValue> &InVals)
2212 MachineFunction &MF = DAG.getMachineFunction();
2213 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2215 const Function* Fn = MF.getFunction();
2216 if (Fn->hasExternalLinkage() &&
2217 Subtarget->isTargetCygMing() &&
2218 Fn->getName() == "main")
2219 FuncInfo->setForceFramePointer(true);
2221 MachineFrameInfo *MFI = MF.getFrameInfo();
2222 bool Is64Bit = Subtarget->is64Bit();
2223 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2225 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2226 "Var args not supported with calling convention fastcc, ghc or hipe");
2228 // Assign locations to all of the incoming arguments.
2229 SmallVector<CCValAssign, 16> ArgLocs;
2230 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2231 ArgLocs, *DAG.getContext());
2233 // Allocate shadow area for Win64
2235 CCInfo.AllocateStack(32, 8);
2237 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2239 unsigned LastVal = ~0U;
2241 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2242 CCValAssign &VA = ArgLocs[i];
2243 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2245 assert(VA.getValNo() != LastVal &&
2246 "Don't support value assigned to multiple locs yet");
2248 LastVal = VA.getValNo();
2250 if (VA.isRegLoc()) {
2251 EVT RegVT = VA.getLocVT();
2252 const TargetRegisterClass *RC;
2253 if (RegVT == MVT::i32)
2254 RC = &X86::GR32RegClass;
2255 else if (Is64Bit && RegVT == MVT::i64)
2256 RC = &X86::GR64RegClass;
2257 else if (RegVT == MVT::f32)
2258 RC = &X86::FR32RegClass;
2259 else if (RegVT == MVT::f64)
2260 RC = &X86::FR64RegClass;
2261 else if (RegVT.is512BitVector())
2262 RC = &X86::VR512RegClass;
2263 else if (RegVT.is256BitVector())
2264 RC = &X86::VR256RegClass;
2265 else if (RegVT.is128BitVector())
2266 RC = &X86::VR128RegClass;
2267 else if (RegVT == MVT::x86mmx)
2268 RC = &X86::VR64RegClass;
2269 else if (RegVT == MVT::i1)
2270 RC = &X86::VK1RegClass;
2271 else if (RegVT == MVT::v8i1)
2272 RC = &X86::VK8RegClass;
2273 else if (RegVT == MVT::v16i1)
2274 RC = &X86::VK16RegClass;
2276 llvm_unreachable("Unknown argument type!");
2278 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2279 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2281 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2282 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2284 if (VA.getLocInfo() == CCValAssign::SExt)
2285 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2286 DAG.getValueType(VA.getValVT()));
2287 else if (VA.getLocInfo() == CCValAssign::ZExt)
2288 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2289 DAG.getValueType(VA.getValVT()));
2290 else if (VA.getLocInfo() == CCValAssign::BCvt)
2291 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2293 if (VA.isExtInLoc()) {
2294 // Handle MMX values passed in XMM regs.
2295 if (RegVT.isVector())
2296 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2298 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2301 assert(VA.isMemLoc());
2302 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2305 // If value is passed via pointer - do a load.
2306 if (VA.getLocInfo() == CCValAssign::Indirect)
2307 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2308 MachinePointerInfo(), false, false, false, 0);
2310 InVals.push_back(ArgValue);
2313 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2314 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2315 // The x86-64 ABIs require that for returning structs by value we copy
2316 // the sret argument into %rax/%eax (depending on ABI) for the return.
2317 // Win32 requires us to put the sret argument to %eax as well.
2318 // Save the argument into a virtual register so that we can access it
2319 // from the return points.
2320 if (Ins[i].Flags.isSRet()) {
2321 unsigned Reg = FuncInfo->getSRetReturnReg();
2323 MVT PtrTy = getPointerTy();
2324 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2325 FuncInfo->setSRetReturnReg(Reg);
2327 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2328 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2334 unsigned StackSize = CCInfo.getNextStackOffset();
2335 // Align stack specially for tail calls.
2336 if (FuncIsMadeTailCallSafe(CallConv,
2337 MF.getTarget().Options.GuaranteedTailCallOpt))
2338 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2340 // If the function takes variable number of arguments, make a frame index for
2341 // the start of the first vararg value... for expansion of llvm.va_start.
2343 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2344 CallConv != CallingConv::X86_ThisCall)) {
2345 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2348 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2350 // FIXME: We should really autogenerate these arrays
2351 static const MCPhysReg GPR64ArgRegsWin64[] = {
2352 X86::RCX, X86::RDX, X86::R8, X86::R9
2354 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2355 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2357 static const MCPhysReg XMMArgRegs64Bit[] = {
2358 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2359 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2361 const MCPhysReg *GPR64ArgRegs;
2362 unsigned NumXMMRegs = 0;
2365 // The XMM registers which might contain var arg parameters are shadowed
2366 // in their paired GPR. So we only need to save the GPR to their home
2368 TotalNumIntRegs = 4;
2369 GPR64ArgRegs = GPR64ArgRegsWin64;
2371 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2372 GPR64ArgRegs = GPR64ArgRegs64Bit;
2374 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2377 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2380 bool NoImplicitFloatOps = Fn->getAttributes().
2381 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2382 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2383 "SSE register cannot be used when SSE is disabled!");
2384 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2385 NoImplicitFloatOps) &&
2386 "SSE register cannot be used when SSE is disabled!");
2387 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2388 !Subtarget->hasSSE1())
2389 // Kernel mode asks for SSE to be disabled, so don't push them
2391 TotalNumXMMRegs = 0;
2394 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2395 // Get to the caller-allocated home save location. Add 8 to account
2396 // for the return address.
2397 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2398 FuncInfo->setRegSaveFrameIndex(
2399 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2400 // Fixup to set vararg frame on shadow area (4 x i64).
2402 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2404 // For X86-64, if there are vararg parameters that are passed via
2405 // registers, then we must store them to their spots on the stack so
2406 // they may be loaded by deferencing the result of va_next.
2407 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2408 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2409 FuncInfo->setRegSaveFrameIndex(
2410 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2414 // Store the integer parameter registers.
2415 SmallVector<SDValue, 8> MemOps;
2416 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2418 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2419 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2420 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2421 DAG.getIntPtrConstant(Offset));
2422 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2423 &X86::GR64RegClass);
2424 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2426 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2427 MachinePointerInfo::getFixedStack(
2428 FuncInfo->getRegSaveFrameIndex(), Offset),
2430 MemOps.push_back(Store);
2434 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2435 // Now store the XMM (fp + vector) parameter registers.
2436 SmallVector<SDValue, 11> SaveXMMOps;
2437 SaveXMMOps.push_back(Chain);
2439 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2440 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2441 SaveXMMOps.push_back(ALVal);
2443 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2444 FuncInfo->getRegSaveFrameIndex()));
2445 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2446 FuncInfo->getVarArgsFPOffset()));
2448 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2449 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2450 &X86::VR128RegClass);
2451 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2452 SaveXMMOps.push_back(Val);
2454 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2455 MVT::Other, SaveXMMOps));
2458 if (!MemOps.empty())
2459 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2463 // Some CCs need callee pop.
2464 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2465 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2466 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2468 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2469 // If this is an sret function, the return should pop the hidden pointer.
2470 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2471 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2472 argsAreStructReturn(Ins) == StackStructReturn)
2473 FuncInfo->setBytesToPopOnReturn(4);
2477 // RegSaveFrameIndex is X86-64 only.
2478 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2479 if (CallConv == CallingConv::X86_FastCall ||
2480 CallConv == CallingConv::X86_ThisCall)
2481 // fastcc functions can't have varargs.
2482 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2485 FuncInfo->setArgumentStackSize(StackSize);
2491 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2492 SDValue StackPtr, SDValue Arg,
2493 SDLoc dl, SelectionDAG &DAG,
2494 const CCValAssign &VA,
2495 ISD::ArgFlagsTy Flags) const {
2496 unsigned LocMemOffset = VA.getLocMemOffset();
2497 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2498 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2499 if (Flags.isByVal())
2500 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2502 return DAG.getStore(Chain, dl, Arg, PtrOff,
2503 MachinePointerInfo::getStack(LocMemOffset),
2507 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2508 /// optimization is performed and it is required.
2510 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2511 SDValue &OutRetAddr, SDValue Chain,
2512 bool IsTailCall, bool Is64Bit,
2513 int FPDiff, SDLoc dl) const {
2514 // Adjust the Return address stack slot.
2515 EVT VT = getPointerTy();
2516 OutRetAddr = getReturnAddressFrameIndex(DAG);
2518 // Load the "old" Return address.
2519 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2520 false, false, false, 0);
2521 return SDValue(OutRetAddr.getNode(), 1);
2524 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2525 /// optimization is performed and it is required (FPDiff!=0).
2526 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2527 SDValue Chain, SDValue RetAddrFrIdx,
2528 EVT PtrVT, unsigned SlotSize,
2529 int FPDiff, SDLoc dl) {
2530 // Store the return address to the appropriate stack slot.
2531 if (!FPDiff) return Chain;
2532 // Calculate the new stack slot for the return address.
2533 int NewReturnAddrFI =
2534 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2536 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2537 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2538 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2544 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2545 SmallVectorImpl<SDValue> &InVals) const {
2546 SelectionDAG &DAG = CLI.DAG;
2548 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2549 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2550 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2551 SDValue Chain = CLI.Chain;
2552 SDValue Callee = CLI.Callee;
2553 CallingConv::ID CallConv = CLI.CallConv;
2554 bool &isTailCall = CLI.IsTailCall;
2555 bool isVarArg = CLI.IsVarArg;
2557 MachineFunction &MF = DAG.getMachineFunction();
2558 bool Is64Bit = Subtarget->is64Bit();
2559 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2560 StructReturnType SR = callIsStructReturn(Outs);
2561 bool IsSibcall = false;
2563 if (MF.getTarget().Options.DisableTailCalls)
2566 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2568 // Force this to be a tail call. The verifier rules are enough to ensure
2569 // that we can lower this successfully without moving the return address
2572 } else if (isTailCall) {
2573 // Check if it's really possible to do a tail call.
2574 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2575 isVarArg, SR != NotStructReturn,
2576 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2577 Outs, OutVals, Ins, DAG);
2579 // Sibcalls are automatically detected tailcalls which do not require
2581 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2588 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2589 "Var args not supported with calling convention fastcc, ghc or hipe");
2591 // Analyze operands of the call, assigning locations to each operand.
2592 SmallVector<CCValAssign, 16> ArgLocs;
2593 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2594 ArgLocs, *DAG.getContext());
2596 // Allocate shadow area for Win64
2598 CCInfo.AllocateStack(32, 8);
2600 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2602 // Get a count of how many bytes are to be pushed on the stack.
2603 unsigned NumBytes = CCInfo.getNextStackOffset();
2605 // This is a sibcall. The memory operands are available in caller's
2606 // own caller's stack.
2608 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2609 IsTailCallConvention(CallConv))
2610 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2613 if (isTailCall && !IsSibcall && !IsMustTail) {
2614 // Lower arguments at fp - stackoffset + fpdiff.
2615 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2616 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2618 FPDiff = NumBytesCallerPushed - NumBytes;
2620 // Set the delta of movement of the returnaddr stackslot.
2621 // But only set if delta is greater than previous delta.
2622 if (FPDiff < X86Info->getTCReturnAddrDelta())
2623 X86Info->setTCReturnAddrDelta(FPDiff);
2626 unsigned NumBytesToPush = NumBytes;
2627 unsigned NumBytesToPop = NumBytes;
2629 // If we have an inalloca argument, all stack space has already been allocated
2630 // for us and be right at the top of the stack. We don't support multiple
2631 // arguments passed in memory when using inalloca.
2632 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2634 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2635 "an inalloca argument must be the only memory argument");
2639 Chain = DAG.getCALLSEQ_START(
2640 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2642 SDValue RetAddrFrIdx;
2643 // Load return address for tail calls.
2644 if (isTailCall && FPDiff)
2645 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2646 Is64Bit, FPDiff, dl);
2648 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2649 SmallVector<SDValue, 8> MemOpChains;
2652 // Walk the register/memloc assignments, inserting copies/loads. In the case
2653 // of tail call optimization arguments are handle later.
2654 const X86RegisterInfo *RegInfo =
2655 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2656 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2657 // Skip inalloca arguments, they have already been written.
2658 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2659 if (Flags.isInAlloca())
2662 CCValAssign &VA = ArgLocs[i];
2663 EVT RegVT = VA.getLocVT();
2664 SDValue Arg = OutVals[i];
2665 bool isByVal = Flags.isByVal();
2667 // Promote the value if needed.
2668 switch (VA.getLocInfo()) {
2669 default: llvm_unreachable("Unknown loc info!");
2670 case CCValAssign::Full: break;
2671 case CCValAssign::SExt:
2672 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2674 case CCValAssign::ZExt:
2675 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2677 case CCValAssign::AExt:
2678 if (RegVT.is128BitVector()) {
2679 // Special case: passing MMX values in XMM registers.
2680 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2681 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2682 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2684 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2686 case CCValAssign::BCvt:
2687 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2689 case CCValAssign::Indirect: {
2690 // Store the argument.
2691 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2692 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2693 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2694 MachinePointerInfo::getFixedStack(FI),
2701 if (VA.isRegLoc()) {
2702 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2703 if (isVarArg && IsWin64) {
2704 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2705 // shadow reg if callee is a varargs function.
2706 unsigned ShadowReg = 0;
2707 switch (VA.getLocReg()) {
2708 case X86::XMM0: ShadowReg = X86::RCX; break;
2709 case X86::XMM1: ShadowReg = X86::RDX; break;
2710 case X86::XMM2: ShadowReg = X86::R8; break;
2711 case X86::XMM3: ShadowReg = X86::R9; break;
2714 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2716 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2717 assert(VA.isMemLoc());
2718 if (!StackPtr.getNode())
2719 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2721 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2722 dl, DAG, VA, Flags));
2726 if (!MemOpChains.empty())
2727 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2729 if (Subtarget->isPICStyleGOT()) {
2730 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2733 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2734 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2736 // If we are tail calling and generating PIC/GOT style code load the
2737 // address of the callee into ECX. The value in ecx is used as target of
2738 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2739 // for tail calls on PIC/GOT architectures. Normally we would just put the
2740 // address of GOT into ebx and then call target@PLT. But for tail calls
2741 // ebx would be restored (since ebx is callee saved) before jumping to the
2744 // Note: The actual moving to ECX is done further down.
2745 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2746 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2747 !G->getGlobal()->hasProtectedVisibility())
2748 Callee = LowerGlobalAddress(Callee, DAG);
2749 else if (isa<ExternalSymbolSDNode>(Callee))
2750 Callee = LowerExternalSymbol(Callee, DAG);
2754 if (Is64Bit && isVarArg && !IsWin64) {
2755 // From AMD64 ABI document:
2756 // For calls that may call functions that use varargs or stdargs
2757 // (prototype-less calls or calls to functions containing ellipsis (...) in
2758 // the declaration) %al is used as hidden argument to specify the number
2759 // of SSE registers used. The contents of %al do not need to match exactly
2760 // the number of registers, but must be an ubound on the number of SSE
2761 // registers used and is in the range 0 - 8 inclusive.
2763 // Count the number of XMM registers allocated.
2764 static const MCPhysReg XMMArgRegs[] = {
2765 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2766 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2768 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2769 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2770 && "SSE registers cannot be used when SSE is disabled");
2772 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2773 DAG.getConstant(NumXMMRegs, MVT::i8)));
2776 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2777 // don't need this because the eligibility check rejects calls that require
2778 // shuffling arguments passed in memory.
2779 if (!IsSibcall && isTailCall) {
2780 // Force all the incoming stack arguments to be loaded from the stack
2781 // before any new outgoing arguments are stored to the stack, because the
2782 // outgoing stack slots may alias the incoming argument stack slots, and
2783 // the alias isn't otherwise explicit. This is slightly more conservative
2784 // than necessary, because it means that each store effectively depends
2785 // on every argument instead of just those arguments it would clobber.
2786 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2788 SmallVector<SDValue, 8> MemOpChains2;
2791 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2792 CCValAssign &VA = ArgLocs[i];
2795 assert(VA.isMemLoc());
2796 SDValue Arg = OutVals[i];
2797 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2798 // Skip inalloca arguments. They don't require any work.
2799 if (Flags.isInAlloca())
2801 // Create frame index.
2802 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2803 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2804 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2805 FIN = DAG.getFrameIndex(FI, getPointerTy());
2807 if (Flags.isByVal()) {
2808 // Copy relative to framepointer.
2809 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2810 if (!StackPtr.getNode())
2811 StackPtr = DAG.getCopyFromReg(Chain, dl,
2812 RegInfo->getStackRegister(),
2814 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2816 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2820 // Store relative to framepointer.
2821 MemOpChains2.push_back(
2822 DAG.getStore(ArgChain, dl, Arg, FIN,
2823 MachinePointerInfo::getFixedStack(FI),
2828 if (!MemOpChains2.empty())
2829 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2831 // Store the return address to the appropriate stack slot.
2832 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2833 getPointerTy(), RegInfo->getSlotSize(),
2837 // Build a sequence of copy-to-reg nodes chained together with token chain
2838 // and flag operands which copy the outgoing args into registers.
2840 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2841 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2842 RegsToPass[i].second, InFlag);
2843 InFlag = Chain.getValue(1);
2846 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2847 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2848 // In the 64-bit large code model, we have to make all calls
2849 // through a register, since the call instruction's 32-bit
2850 // pc-relative offset may not be large enough to hold the whole
2852 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2853 // If the callee is a GlobalAddress node (quite common, every direct call
2854 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2857 // We should use extra load for direct calls to dllimported functions in
2859 const GlobalValue *GV = G->getGlobal();
2860 if (!GV->hasDLLImportStorageClass()) {
2861 unsigned char OpFlags = 0;
2862 bool ExtraLoad = false;
2863 unsigned WrapperKind = ISD::DELETED_NODE;
2865 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2866 // external symbols most go through the PLT in PIC mode. If the symbol
2867 // has hidden or protected visibility, or if it is static or local, then
2868 // we don't need to use the PLT - we can directly call it.
2869 if (Subtarget->isTargetELF() &&
2870 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2871 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2872 OpFlags = X86II::MO_PLT;
2873 } else if (Subtarget->isPICStyleStubAny() &&
2874 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2875 (!Subtarget->getTargetTriple().isMacOSX() ||
2876 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2877 // PC-relative references to external symbols should go through $stub,
2878 // unless we're building with the leopard linker or later, which
2879 // automatically synthesizes these stubs.
2880 OpFlags = X86II::MO_DARWIN_STUB;
2881 } else if (Subtarget->isPICStyleRIPRel() &&
2882 isa<Function>(GV) &&
2883 cast<Function>(GV)->getAttributes().
2884 hasAttribute(AttributeSet::FunctionIndex,
2885 Attribute::NonLazyBind)) {
2886 // If the function is marked as non-lazy, generate an indirect call
2887 // which loads from the GOT directly. This avoids runtime overhead
2888 // at the cost of eager binding (and one extra byte of encoding).
2889 OpFlags = X86II::MO_GOTPCREL;
2890 WrapperKind = X86ISD::WrapperRIP;
2894 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2895 G->getOffset(), OpFlags);
2897 // Add a wrapper if needed.
2898 if (WrapperKind != ISD::DELETED_NODE)
2899 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2900 // Add extra indirection if needed.
2902 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2903 MachinePointerInfo::getGOT(),
2904 false, false, false, 0);
2906 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2907 unsigned char OpFlags = 0;
2909 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2910 // external symbols should go through the PLT.
2911 if (Subtarget->isTargetELF() &&
2912 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2913 OpFlags = X86II::MO_PLT;
2914 } else if (Subtarget->isPICStyleStubAny() &&
2915 (!Subtarget->getTargetTriple().isMacOSX() ||
2916 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2917 // PC-relative references to external symbols should go through $stub,
2918 // unless we're building with the leopard linker or later, which
2919 // automatically synthesizes these stubs.
2920 OpFlags = X86II::MO_DARWIN_STUB;
2923 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2927 // Returns a chain & a flag for retval copy to use.
2928 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2929 SmallVector<SDValue, 8> Ops;
2931 if (!IsSibcall && isTailCall) {
2932 Chain = DAG.getCALLSEQ_END(Chain,
2933 DAG.getIntPtrConstant(NumBytesToPop, true),
2934 DAG.getIntPtrConstant(0, true), InFlag, dl);
2935 InFlag = Chain.getValue(1);
2938 Ops.push_back(Chain);
2939 Ops.push_back(Callee);
2942 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2944 // Add argument registers to the end of the list so that they are known live
2946 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2947 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2948 RegsToPass[i].second.getValueType()));
2950 // Add a register mask operand representing the call-preserved registers.
2951 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2952 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2953 assert(Mask && "Missing call preserved mask for calling convention");
2954 Ops.push_back(DAG.getRegisterMask(Mask));
2956 if (InFlag.getNode())
2957 Ops.push_back(InFlag);
2961 //// If this is the first return lowered for this function, add the regs
2962 //// to the liveout set for the function.
2963 // This isn't right, although it's probably harmless on x86; liveouts
2964 // should be computed from returns not tail calls. Consider a void
2965 // function making a tail call to a function returning int.
2966 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2969 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2970 InFlag = Chain.getValue(1);
2972 // Create the CALLSEQ_END node.
2973 unsigned NumBytesForCalleeToPop;
2974 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2975 DAG.getTarget().Options.GuaranteedTailCallOpt))
2976 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2977 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2978 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2979 SR == StackStructReturn)
2980 // If this is a call to a struct-return function, the callee
2981 // pops the hidden struct pointer, so we have to push it back.
2982 // This is common for Darwin/X86, Linux & Mingw32 targets.
2983 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2984 NumBytesForCalleeToPop = 4;
2986 NumBytesForCalleeToPop = 0; // Callee pops nothing.
2988 // Returns a flag for retval copy to use.
2990 Chain = DAG.getCALLSEQ_END(Chain,
2991 DAG.getIntPtrConstant(NumBytesToPop, true),
2992 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2995 InFlag = Chain.getValue(1);
2998 // Handle result values, copying them out of physregs into vregs that we
3000 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3001 Ins, dl, DAG, InVals);
3004 //===----------------------------------------------------------------------===//
3005 // Fast Calling Convention (tail call) implementation
3006 //===----------------------------------------------------------------------===//
3008 // Like std call, callee cleans arguments, convention except that ECX is
3009 // reserved for storing the tail called function address. Only 2 registers are
3010 // free for argument passing (inreg). Tail call optimization is performed
3012 // * tailcallopt is enabled
3013 // * caller/callee are fastcc
3014 // On X86_64 architecture with GOT-style position independent code only local
3015 // (within module) calls are supported at the moment.
3016 // To keep the stack aligned according to platform abi the function
3017 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3018 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3019 // If a tail called function callee has more arguments than the caller the
3020 // caller needs to make sure that there is room to move the RETADDR to. This is
3021 // achieved by reserving an area the size of the argument delta right after the
3022 // original REtADDR, but before the saved framepointer or the spilled registers
3023 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3035 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3036 /// for a 16 byte align requirement.
3038 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3039 SelectionDAG& DAG) const {
3040 MachineFunction &MF = DAG.getMachineFunction();
3041 const TargetMachine &TM = MF.getTarget();
3042 const X86RegisterInfo *RegInfo =
3043 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3044 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3045 unsigned StackAlignment = TFI.getStackAlignment();
3046 uint64_t AlignMask = StackAlignment - 1;
3047 int64_t Offset = StackSize;
3048 unsigned SlotSize = RegInfo->getSlotSize();
3049 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3050 // Number smaller than 12 so just add the difference.
3051 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3053 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3054 Offset = ((~AlignMask) & Offset) + StackAlignment +
3055 (StackAlignment-SlotSize);
3060 /// MatchingStackOffset - Return true if the given stack call argument is
3061 /// already available in the same position (relatively) of the caller's
3062 /// incoming argument stack.
3064 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3065 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3066 const X86InstrInfo *TII) {
3067 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3069 if (Arg.getOpcode() == ISD::CopyFromReg) {
3070 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3071 if (!TargetRegisterInfo::isVirtualRegister(VR))
3073 MachineInstr *Def = MRI->getVRegDef(VR);
3076 if (!Flags.isByVal()) {
3077 if (!TII->isLoadFromStackSlot(Def, FI))
3080 unsigned Opcode = Def->getOpcode();
3081 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3082 Def->getOperand(1).isFI()) {
3083 FI = Def->getOperand(1).getIndex();
3084 Bytes = Flags.getByValSize();
3088 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3089 if (Flags.isByVal())
3090 // ByVal argument is passed in as a pointer but it's now being
3091 // dereferenced. e.g.
3092 // define @foo(%struct.X* %A) {
3093 // tail call @bar(%struct.X* byval %A)
3096 SDValue Ptr = Ld->getBasePtr();
3097 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3100 FI = FINode->getIndex();
3101 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3102 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3103 FI = FINode->getIndex();
3104 Bytes = Flags.getByValSize();
3108 assert(FI != INT_MAX);
3109 if (!MFI->isFixedObjectIndex(FI))
3111 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3114 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3115 /// for tail call optimization. Targets which want to do tail call
3116 /// optimization should implement this function.
3118 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3119 CallingConv::ID CalleeCC,
3121 bool isCalleeStructRet,
3122 bool isCallerStructRet,
3124 const SmallVectorImpl<ISD::OutputArg> &Outs,
3125 const SmallVectorImpl<SDValue> &OutVals,
3126 const SmallVectorImpl<ISD::InputArg> &Ins,
3127 SelectionDAG &DAG) const {
3128 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3131 // If -tailcallopt is specified, make fastcc functions tail-callable.
3132 const MachineFunction &MF = DAG.getMachineFunction();
3133 const Function *CallerF = MF.getFunction();
3135 // If the function return type is x86_fp80 and the callee return type is not,
3136 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3137 // perform a tailcall optimization here.
3138 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3141 CallingConv::ID CallerCC = CallerF->getCallingConv();
3142 bool CCMatch = CallerCC == CalleeCC;
3143 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3144 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3146 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3147 if (IsTailCallConvention(CalleeCC) && CCMatch)
3152 // Look for obvious safe cases to perform tail call optimization that do not
3153 // require ABI changes. This is what gcc calls sibcall.
3155 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3156 // emit a special epilogue.
3157 const X86RegisterInfo *RegInfo =
3158 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3159 if (RegInfo->needsStackRealignment(MF))
3162 // Also avoid sibcall optimization if either caller or callee uses struct
3163 // return semantics.
3164 if (isCalleeStructRet || isCallerStructRet)
3167 // An stdcall/thiscall caller is expected to clean up its arguments; the
3168 // callee isn't going to do that.
3169 // FIXME: this is more restrictive than needed. We could produce a tailcall
3170 // when the stack adjustment matches. For example, with a thiscall that takes
3171 // only one argument.
3172 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3173 CallerCC == CallingConv::X86_ThisCall))
3176 // Do not sibcall optimize vararg calls unless all arguments are passed via
3178 if (isVarArg && !Outs.empty()) {
3180 // Optimizing for varargs on Win64 is unlikely to be safe without
3181 // additional testing.
3182 if (IsCalleeWin64 || IsCallerWin64)
3185 SmallVector<CCValAssign, 16> ArgLocs;
3186 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3187 DAG.getTarget(), ArgLocs, *DAG.getContext());
3189 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3190 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3191 if (!ArgLocs[i].isRegLoc())
3195 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3196 // stack. Therefore, if it's not used by the call it is not safe to optimize
3197 // this into a sibcall.
3198 bool Unused = false;
3199 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3206 SmallVector<CCValAssign, 16> RVLocs;
3207 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3208 DAG.getTarget(), RVLocs, *DAG.getContext());
3209 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3210 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3211 CCValAssign &VA = RVLocs[i];
3212 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3217 // If the calling conventions do not match, then we'd better make sure the
3218 // results are returned in the same way as what the caller expects.
3220 SmallVector<CCValAssign, 16> RVLocs1;
3221 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3222 DAG.getTarget(), RVLocs1, *DAG.getContext());
3223 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3225 SmallVector<CCValAssign, 16> RVLocs2;
3226 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3227 DAG.getTarget(), RVLocs2, *DAG.getContext());
3228 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3230 if (RVLocs1.size() != RVLocs2.size())
3232 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3233 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3235 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3237 if (RVLocs1[i].isRegLoc()) {
3238 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3241 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3247 // If the callee takes no arguments then go on to check the results of the
3249 if (!Outs.empty()) {
3250 // Check if stack adjustment is needed. For now, do not do this if any
3251 // argument is passed on the stack.
3252 SmallVector<CCValAssign, 16> ArgLocs;
3253 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3254 DAG.getTarget(), ArgLocs, *DAG.getContext());
3256 // Allocate shadow area for Win64
3258 CCInfo.AllocateStack(32, 8);
3260 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3261 if (CCInfo.getNextStackOffset()) {
3262 MachineFunction &MF = DAG.getMachineFunction();
3263 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3266 // Check if the arguments are already laid out in the right way as
3267 // the caller's fixed stack objects.
3268 MachineFrameInfo *MFI = MF.getFrameInfo();
3269 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3270 const X86InstrInfo *TII =
3271 static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3272 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3273 CCValAssign &VA = ArgLocs[i];
3274 SDValue Arg = OutVals[i];
3275 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3276 if (VA.getLocInfo() == CCValAssign::Indirect)
3278 if (!VA.isRegLoc()) {
3279 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3286 // If the tailcall address may be in a register, then make sure it's
3287 // possible to register allocate for it. In 32-bit, the call address can
3288 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3289 // callee-saved registers are restored. These happen to be the same
3290 // registers used to pass 'inreg' arguments so watch out for those.
3291 if (!Subtarget->is64Bit() &&
3292 ((!isa<GlobalAddressSDNode>(Callee) &&
3293 !isa<ExternalSymbolSDNode>(Callee)) ||
3294 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3295 unsigned NumInRegs = 0;
3296 // In PIC we need an extra register to formulate the address computation
3298 unsigned MaxInRegs =
3299 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3301 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3302 CCValAssign &VA = ArgLocs[i];
3305 unsigned Reg = VA.getLocReg();
3308 case X86::EAX: case X86::EDX: case X86::ECX:
3309 if (++NumInRegs == MaxInRegs)
3321 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3322 const TargetLibraryInfo *libInfo) const {
3323 return X86::createFastISel(funcInfo, libInfo);
3326 //===----------------------------------------------------------------------===//
3327 // Other Lowering Hooks
3328 //===----------------------------------------------------------------------===//
3330 static bool MayFoldLoad(SDValue Op) {
3331 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3334 static bool MayFoldIntoStore(SDValue Op) {
3335 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3338 static bool isTargetShuffle(unsigned Opcode) {
3340 default: return false;
3341 case X86ISD::PSHUFD:
3342 case X86ISD::PSHUFHW:
3343 case X86ISD::PSHUFLW:
3345 case X86ISD::PALIGNR:
3346 case X86ISD::MOVLHPS:
3347 case X86ISD::MOVLHPD:
3348 case X86ISD::MOVHLPS:
3349 case X86ISD::MOVLPS:
3350 case X86ISD::MOVLPD:
3351 case X86ISD::MOVSHDUP:
3352 case X86ISD::MOVSLDUP:
3353 case X86ISD::MOVDDUP:
3356 case X86ISD::UNPCKL:
3357 case X86ISD::UNPCKH:
3358 case X86ISD::VPERMILP:
3359 case X86ISD::VPERM2X128:
3360 case X86ISD::VPERMI:
3365 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3366 SDValue V1, SelectionDAG &DAG) {
3368 default: llvm_unreachable("Unknown x86 shuffle node");
3369 case X86ISD::MOVSHDUP:
3370 case X86ISD::MOVSLDUP:
3371 case X86ISD::MOVDDUP:
3372 return DAG.getNode(Opc, dl, VT, V1);
3376 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3377 SDValue V1, unsigned TargetMask,
3378 SelectionDAG &DAG) {
3380 default: llvm_unreachable("Unknown x86 shuffle node");
3381 case X86ISD::PSHUFD:
3382 case X86ISD::PSHUFHW:
3383 case X86ISD::PSHUFLW:
3384 case X86ISD::VPERMILP:
3385 case X86ISD::VPERMI:
3386 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3390 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3391 SDValue V1, SDValue V2, unsigned TargetMask,
3392 SelectionDAG &DAG) {
3394 default: llvm_unreachable("Unknown x86 shuffle node");
3395 case X86ISD::PALIGNR:
3397 case X86ISD::VPERM2X128:
3398 return DAG.getNode(Opc, dl, VT, V1, V2,
3399 DAG.getConstant(TargetMask, MVT::i8));
3403 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3404 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3406 default: llvm_unreachable("Unknown x86 shuffle node");
3407 case X86ISD::MOVLHPS:
3408 case X86ISD::MOVLHPD:
3409 case X86ISD::MOVHLPS:
3410 case X86ISD::MOVLPS:
3411 case X86ISD::MOVLPD:
3414 case X86ISD::UNPCKL:
3415 case X86ISD::UNPCKH:
3416 return DAG.getNode(Opc, dl, VT, V1, V2);
3420 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3421 MachineFunction &MF = DAG.getMachineFunction();
3422 const X86RegisterInfo *RegInfo =
3423 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3424 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3425 int ReturnAddrIndex = FuncInfo->getRAIndex();
3427 if (ReturnAddrIndex == 0) {
3428 // Set up a frame object for the return address.
3429 unsigned SlotSize = RegInfo->getSlotSize();
3430 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3433 FuncInfo->setRAIndex(ReturnAddrIndex);
3436 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3439 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3440 bool hasSymbolicDisplacement) {
3441 // Offset should fit into 32 bit immediate field.
3442 if (!isInt<32>(Offset))
3445 // If we don't have a symbolic displacement - we don't have any extra
3447 if (!hasSymbolicDisplacement)
3450 // FIXME: Some tweaks might be needed for medium code model.
3451 if (M != CodeModel::Small && M != CodeModel::Kernel)
3454 // For small code model we assume that latest object is 16MB before end of 31
3455 // bits boundary. We may also accept pretty large negative constants knowing
3456 // that all objects are in the positive half of address space.
3457 if (M == CodeModel::Small && Offset < 16*1024*1024)
3460 // For kernel code model we know that all object resist in the negative half
3461 // of 32bits address space. We may not accept negative offsets, since they may
3462 // be just off and we may accept pretty large positive ones.
3463 if (M == CodeModel::Kernel && Offset > 0)
3469 /// isCalleePop - Determines whether the callee is required to pop its
3470 /// own arguments. Callee pop is necessary to support tail calls.
3471 bool X86::isCalleePop(CallingConv::ID CallingConv,
3472 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3476 switch (CallingConv) {
3479 case CallingConv::X86_StdCall:
3481 case CallingConv::X86_FastCall:
3483 case CallingConv::X86_ThisCall:
3485 case CallingConv::Fast:
3487 case CallingConv::GHC:
3489 case CallingConv::HiPE:
3494 /// \brief Return true if the condition is an unsigned comparison operation.
3495 static bool isX86CCUnsigned(unsigned X86CC) {
3497 default: llvm_unreachable("Invalid integer condition!");
3498 case X86::COND_E: return true;
3499 case X86::COND_G: return false;
3500 case X86::COND_GE: return false;
3501 case X86::COND_L: return false;
3502 case X86::COND_LE: return false;
3503 case X86::COND_NE: return true;
3504 case X86::COND_B: return true;
3505 case X86::COND_A: return true;
3506 case X86::COND_BE: return true;
3507 case X86::COND_AE: return true;
3509 llvm_unreachable("covered switch fell through?!");
3512 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3513 /// specific condition code, returning the condition code and the LHS/RHS of the
3514 /// comparison to make.
3515 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3516 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3518 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3519 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3520 // X > -1 -> X == 0, jump !sign.
3521 RHS = DAG.getConstant(0, RHS.getValueType());
3522 return X86::COND_NS;
3524 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3525 // X < 0 -> X == 0, jump on sign.
3528 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3530 RHS = DAG.getConstant(0, RHS.getValueType());
3531 return X86::COND_LE;
3535 switch (SetCCOpcode) {
3536 default: llvm_unreachable("Invalid integer condition!");
3537 case ISD::SETEQ: return X86::COND_E;
3538 case ISD::SETGT: return X86::COND_G;
3539 case ISD::SETGE: return X86::COND_GE;
3540 case ISD::SETLT: return X86::COND_L;
3541 case ISD::SETLE: return X86::COND_LE;
3542 case ISD::SETNE: return X86::COND_NE;
3543 case ISD::SETULT: return X86::COND_B;
3544 case ISD::SETUGT: return X86::COND_A;
3545 case ISD::SETULE: return X86::COND_BE;
3546 case ISD::SETUGE: return X86::COND_AE;
3550 // First determine if it is required or is profitable to flip the operands.
3552 // If LHS is a foldable load, but RHS is not, flip the condition.
3553 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3554 !ISD::isNON_EXTLoad(RHS.getNode())) {
3555 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3556 std::swap(LHS, RHS);
3559 switch (SetCCOpcode) {
3565 std::swap(LHS, RHS);
3569 // On a floating point condition, the flags are set as follows:
3571 // 0 | 0 | 0 | X > Y
3572 // 0 | 0 | 1 | X < Y
3573 // 1 | 0 | 0 | X == Y
3574 // 1 | 1 | 1 | unordered
3575 switch (SetCCOpcode) {
3576 default: llvm_unreachable("Condcode should be pre-legalized away");
3578 case ISD::SETEQ: return X86::COND_E;
3579 case ISD::SETOLT: // flipped
3581 case ISD::SETGT: return X86::COND_A;
3582 case ISD::SETOLE: // flipped
3584 case ISD::SETGE: return X86::COND_AE;
3585 case ISD::SETUGT: // flipped
3587 case ISD::SETLT: return X86::COND_B;
3588 case ISD::SETUGE: // flipped
3590 case ISD::SETLE: return X86::COND_BE;
3592 case ISD::SETNE: return X86::COND_NE;
3593 case ISD::SETUO: return X86::COND_P;
3594 case ISD::SETO: return X86::COND_NP;
3596 case ISD::SETUNE: return X86::COND_INVALID;
3600 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3601 /// code. Current x86 isa includes the following FP cmov instructions:
3602 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3603 static bool hasFPCMov(unsigned X86CC) {
3619 /// isFPImmLegal - Returns true if the target can instruction select the
3620 /// specified FP immediate natively. If false, the legalizer will
3621 /// materialize the FP immediate as a load from a constant pool.
3622 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3623 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3624 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3630 /// \brief Returns true if it is beneficial to convert a load of a constant
3631 /// to just the constant itself.
3632 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3634 assert(Ty->isIntegerTy());
3636 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3637 if (BitSize == 0 || BitSize > 64)
3642 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3643 /// the specified range (L, H].
3644 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3645 return (Val < 0) || (Val >= Low && Val < Hi);
3648 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3649 /// specified value.
3650 static bool isUndefOrEqual(int Val, int CmpVal) {
3651 return (Val < 0 || Val == CmpVal);
3654 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3655 /// from position Pos and ending in Pos+Size, falls within the specified
3656 /// sequential range (L, L+Pos]. or is undef.
3657 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3658 unsigned Pos, unsigned Size, int Low) {
3659 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3660 if (!isUndefOrEqual(Mask[i], Low))
3665 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3666 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3667 /// the second operand.
3668 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3669 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3670 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3671 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3672 return (Mask[0] < 2 && Mask[1] < 2);
3676 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3677 /// is suitable for input to PSHUFHW.
3678 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3679 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3682 // Lower quadword copied in order or undef.
3683 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3686 // Upper quadword shuffled.
3687 for (unsigned i = 4; i != 8; ++i)
3688 if (!isUndefOrInRange(Mask[i], 4, 8))
3691 if (VT == MVT::v16i16) {
3692 // Lower quadword copied in order or undef.
3693 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3696 // Upper quadword shuffled.
3697 for (unsigned i = 12; i != 16; ++i)
3698 if (!isUndefOrInRange(Mask[i], 12, 16))
3705 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3706 /// is suitable for input to PSHUFLW.
3707 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3708 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3711 // Upper quadword copied in order.
3712 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3715 // Lower quadword shuffled.
3716 for (unsigned i = 0; i != 4; ++i)
3717 if (!isUndefOrInRange(Mask[i], 0, 4))
3720 if (VT == MVT::v16i16) {
3721 // Upper quadword copied in order.
3722 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3725 // Lower quadword shuffled.
3726 for (unsigned i = 8; i != 12; ++i)
3727 if (!isUndefOrInRange(Mask[i], 8, 12))
3734 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3735 /// is suitable for input to PALIGNR.
3736 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3737 const X86Subtarget *Subtarget) {
3738 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3739 (VT.is256BitVector() && !Subtarget->hasInt256()))
3742 unsigned NumElts = VT.getVectorNumElements();
3743 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3744 unsigned NumLaneElts = NumElts/NumLanes;
3746 // Do not handle 64-bit element shuffles with palignr.
3747 if (NumLaneElts == 2)
3750 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3752 for (i = 0; i != NumLaneElts; ++i) {
3757 // Lane is all undef, go to next lane
3758 if (i == NumLaneElts)
3761 int Start = Mask[i+l];
3763 // Make sure its in this lane in one of the sources
3764 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3765 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3768 // If not lane 0, then we must match lane 0
3769 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3772 // Correct second source to be contiguous with first source
3773 if (Start >= (int)NumElts)
3774 Start -= NumElts - NumLaneElts;
3776 // Make sure we're shifting in the right direction.
3777 if (Start <= (int)(i+l))
3782 // Check the rest of the elements to see if they are consecutive.
3783 for (++i; i != NumLaneElts; ++i) {
3784 int Idx = Mask[i+l];
3786 // Make sure its in this lane
3787 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3788 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3791 // If not lane 0, then we must match lane 0
3792 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3795 if (Idx >= (int)NumElts)
3796 Idx -= NumElts - NumLaneElts;
3798 if (!isUndefOrEqual(Idx, Start+i))
3807 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3808 /// the two vector operands have swapped position.
3809 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3810 unsigned NumElems) {
3811 for (unsigned i = 0; i != NumElems; ++i) {
3815 else if (idx < (int)NumElems)
3816 Mask[i] = idx + NumElems;
3818 Mask[i] = idx - NumElems;
3822 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3823 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3824 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3825 /// reverse of what x86 shuffles want.
3826 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3828 unsigned NumElems = VT.getVectorNumElements();
3829 unsigned NumLanes = VT.getSizeInBits()/128;
3830 unsigned NumLaneElems = NumElems/NumLanes;
3832 if (NumLaneElems != 2 && NumLaneElems != 4)
3835 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3836 bool symetricMaskRequired =
3837 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3839 // VSHUFPSY divides the resulting vector into 4 chunks.
3840 // The sources are also splitted into 4 chunks, and each destination
3841 // chunk must come from a different source chunk.
3843 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3844 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3846 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3847 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3849 // VSHUFPDY divides the resulting vector into 4 chunks.
3850 // The sources are also splitted into 4 chunks, and each destination
3851 // chunk must come from a different source chunk.
3853 // SRC1 => X3 X2 X1 X0
3854 // SRC2 => Y3 Y2 Y1 Y0
3856 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3858 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3859 unsigned HalfLaneElems = NumLaneElems/2;
3860 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3861 for (unsigned i = 0; i != NumLaneElems; ++i) {
3862 int Idx = Mask[i+l];
3863 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3864 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3866 // For VSHUFPSY, the mask of the second half must be the same as the
3867 // first but with the appropriate offsets. This works in the same way as
3868 // VPERMILPS works with masks.
3869 if (!symetricMaskRequired || Idx < 0)
3871 if (MaskVal[i] < 0) {
3872 MaskVal[i] = Idx - l;
3875 if ((signed)(Idx - l) != MaskVal[i])
3883 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3884 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3885 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3886 if (!VT.is128BitVector())
3889 unsigned NumElems = VT.getVectorNumElements();
3894 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3895 return isUndefOrEqual(Mask[0], 6) &&
3896 isUndefOrEqual(Mask[1], 7) &&
3897 isUndefOrEqual(Mask[2], 2) &&
3898 isUndefOrEqual(Mask[3], 3);
3901 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3902 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3904 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3905 if (!VT.is128BitVector())
3908 unsigned NumElems = VT.getVectorNumElements();
3913 return isUndefOrEqual(Mask[0], 2) &&
3914 isUndefOrEqual(Mask[1], 3) &&
3915 isUndefOrEqual(Mask[2], 2) &&
3916 isUndefOrEqual(Mask[3], 3);
3919 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3920 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3921 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3922 if (!VT.is128BitVector())
3925 unsigned NumElems = VT.getVectorNumElements();
3927 if (NumElems != 2 && NumElems != 4)
3930 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3931 if (!isUndefOrEqual(Mask[i], i + NumElems))
3934 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3935 if (!isUndefOrEqual(Mask[i], i))
3941 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3942 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3943 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3944 if (!VT.is128BitVector())
3947 unsigned NumElems = VT.getVectorNumElements();
3949 if (NumElems != 2 && NumElems != 4)
3952 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3953 if (!isUndefOrEqual(Mask[i], i))
3956 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3957 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3963 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3964 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3965 /// i. e: If all but one element come from the same vector.
3966 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3967 // TODO: Deal with AVX's VINSERTPS
3968 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3971 unsigned CorrectPosV1 = 0;
3972 unsigned CorrectPosV2 = 0;
3973 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3974 if (Mask[i] == -1) {
3982 else if (Mask[i] == i + 4)
3986 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3987 // We have 3 elements (undefs count as elements from any vector) from one
3988 // vector, and one from another.
3995 // Some special combinations that can be optimized.
3998 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3999 SelectionDAG &DAG) {
4000 MVT VT = SVOp->getSimpleValueType(0);
4003 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4006 ArrayRef<int> Mask = SVOp->getMask();
4008 // These are the special masks that may be optimized.
4009 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4010 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4011 bool MatchEvenMask = true;
4012 bool MatchOddMask = true;
4013 for (int i=0; i<8; ++i) {
4014 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4015 MatchEvenMask = false;
4016 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4017 MatchOddMask = false;
4020 if (!MatchEvenMask && !MatchOddMask)
4023 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4025 SDValue Op0 = SVOp->getOperand(0);
4026 SDValue Op1 = SVOp->getOperand(1);
4028 if (MatchEvenMask) {
4029 // Shift the second operand right to 32 bits.
4030 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4031 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4033 // Shift the first operand left to 32 bits.
4034 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4035 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4037 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4038 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4041 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4042 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4043 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4044 bool HasInt256, bool V2IsSplat = false) {
4046 assert(VT.getSizeInBits() >= 128 &&
4047 "Unsupported vector type for unpckl");
4049 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4051 unsigned NumOf256BitLanes;
4052 unsigned NumElts = VT.getVectorNumElements();
4053 if (VT.is256BitVector()) {
4054 if (NumElts != 4 && NumElts != 8 &&
4055 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4058 NumOf256BitLanes = 1;
4059 } else if (VT.is512BitVector()) {
4060 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4061 "Unsupported vector type for unpckh");
4063 NumOf256BitLanes = 2;
4066 NumOf256BitLanes = 1;
4069 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4070 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4072 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4073 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4074 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4075 int BitI = Mask[l256*NumEltsInStride+l+i];
4076 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4077 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4079 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4081 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4089 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4090 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4091 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4092 bool HasInt256, bool V2IsSplat = false) {
4093 assert(VT.getSizeInBits() >= 128 &&
4094 "Unsupported vector type for unpckh");
4096 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4098 unsigned NumOf256BitLanes;
4099 unsigned NumElts = VT.getVectorNumElements();
4100 if (VT.is256BitVector()) {
4101 if (NumElts != 4 && NumElts != 8 &&
4102 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4105 NumOf256BitLanes = 1;
4106 } else if (VT.is512BitVector()) {
4107 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4108 "Unsupported vector type for unpckh");
4110 NumOf256BitLanes = 2;
4113 NumOf256BitLanes = 1;
4116 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4117 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4119 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4120 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4121 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4122 int BitI = Mask[l256*NumEltsInStride+l+i];
4123 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4124 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4126 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4128 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4136 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4137 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4139 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4140 unsigned NumElts = VT.getVectorNumElements();
4141 bool Is256BitVec = VT.is256BitVector();
4143 if (VT.is512BitVector())
4145 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4146 "Unsupported vector type for unpckh");
4148 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4149 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4152 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4153 // FIXME: Need a better way to get rid of this, there's no latency difference
4154 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4155 // the former later. We should also remove the "_undef" special mask.
4156 if (NumElts == 4 && Is256BitVec)
4159 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4160 // independently on 128-bit lanes.
4161 unsigned NumLanes = VT.getSizeInBits()/128;
4162 unsigned NumLaneElts = NumElts/NumLanes;
4164 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4165 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4166 int BitI = Mask[l+i];
4167 int BitI1 = Mask[l+i+1];
4169 if (!isUndefOrEqual(BitI, j))
4171 if (!isUndefOrEqual(BitI1, j))
4179 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4180 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4182 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4183 unsigned NumElts = VT.getVectorNumElements();
4185 if (VT.is512BitVector())
4188 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4189 "Unsupported vector type for unpckh");
4191 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4192 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4195 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4196 // independently on 128-bit lanes.
4197 unsigned NumLanes = VT.getSizeInBits()/128;
4198 unsigned NumLaneElts = NumElts/NumLanes;
4200 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4201 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4202 int BitI = Mask[l+i];
4203 int BitI1 = Mask[l+i+1];
4204 if (!isUndefOrEqual(BitI, j))
4206 if (!isUndefOrEqual(BitI1, j))
4213 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4214 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4215 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4216 if (!VT.is512BitVector())
4219 unsigned NumElts = VT.getVectorNumElements();
4220 unsigned HalfSize = NumElts/2;
4221 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4222 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4227 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4228 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4236 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4237 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4238 /// MOVSD, and MOVD, i.e. setting the lowest element.
4239 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4240 if (VT.getVectorElementType().getSizeInBits() < 32)
4242 if (!VT.is128BitVector())
4245 unsigned NumElts = VT.getVectorNumElements();
4247 if (!isUndefOrEqual(Mask[0], NumElts))
4250 for (unsigned i = 1; i != NumElts; ++i)
4251 if (!isUndefOrEqual(Mask[i], i))
4257 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4258 /// as permutations between 128-bit chunks or halves. As an example: this
4260 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4261 /// The first half comes from the second half of V1 and the second half from the
4262 /// the second half of V2.
4263 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4264 if (!HasFp256 || !VT.is256BitVector())
4267 // The shuffle result is divided into half A and half B. In total the two
4268 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4269 // B must come from C, D, E or F.
4270 unsigned HalfSize = VT.getVectorNumElements()/2;
4271 bool MatchA = false, MatchB = false;
4273 // Check if A comes from one of C, D, E, F.
4274 for (unsigned Half = 0; Half != 4; ++Half) {
4275 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4281 // Check if B comes from one of C, D, E, F.
4282 for (unsigned Half = 0; Half != 4; ++Half) {
4283 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4289 return MatchA && MatchB;
4292 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4293 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4294 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4295 MVT VT = SVOp->getSimpleValueType(0);
4297 unsigned HalfSize = VT.getVectorNumElements()/2;
4299 unsigned FstHalf = 0, SndHalf = 0;
4300 for (unsigned i = 0; i < HalfSize; ++i) {
4301 if (SVOp->getMaskElt(i) > 0) {
4302 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4306 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4307 if (SVOp->getMaskElt(i) > 0) {
4308 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4313 return (FstHalf | (SndHalf << 4));
4316 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4317 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4318 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4322 unsigned NumElts = VT.getVectorNumElements();
4324 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4325 for (unsigned i = 0; i != NumElts; ++i) {
4328 Imm8 |= Mask[i] << (i*2);
4333 unsigned LaneSize = 4;
4334 SmallVector<int, 4> MaskVal(LaneSize, -1);
4336 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4337 for (unsigned i = 0; i != LaneSize; ++i) {
4338 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4342 if (MaskVal[i] < 0) {
4343 MaskVal[i] = Mask[i+l] - l;
4344 Imm8 |= MaskVal[i] << (i*2);
4347 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4354 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4355 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4356 /// Note that VPERMIL mask matching is different depending whether theunderlying
4357 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4358 /// to the same elements of the low, but to the higher half of the source.
4359 /// In VPERMILPD the two lanes could be shuffled independently of each other
4360 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4361 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4362 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4363 if (VT.getSizeInBits() < 256 || EltSize < 32)
4365 bool symetricMaskRequired = (EltSize == 32);
4366 unsigned NumElts = VT.getVectorNumElements();
4368 unsigned NumLanes = VT.getSizeInBits()/128;
4369 unsigned LaneSize = NumElts/NumLanes;
4370 // 2 or 4 elements in one lane
4372 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4373 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4374 for (unsigned i = 0; i != LaneSize; ++i) {
4375 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4377 if (symetricMaskRequired) {
4378 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4379 ExpectedMaskVal[i] = Mask[i+l] - l;
4382 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4390 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4391 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4392 /// element of vector 2 and the other elements to come from vector 1 in order.
4393 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4394 bool V2IsSplat = false, bool V2IsUndef = false) {
4395 if (!VT.is128BitVector())
4398 unsigned NumOps = VT.getVectorNumElements();
4399 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4402 if (!isUndefOrEqual(Mask[0], 0))
4405 for (unsigned i = 1; i != NumOps; ++i)
4406 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4407 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4408 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4414 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4415 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4416 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4417 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4418 const X86Subtarget *Subtarget) {
4419 if (!Subtarget->hasSSE3())
4422 unsigned NumElems = VT.getVectorNumElements();
4424 if ((VT.is128BitVector() && NumElems != 4) ||
4425 (VT.is256BitVector() && NumElems != 8) ||
4426 (VT.is512BitVector() && NumElems != 16))
4429 // "i+1" is the value the indexed mask element must have
4430 for (unsigned i = 0; i != NumElems; i += 2)
4431 if (!isUndefOrEqual(Mask[i], i+1) ||
4432 !isUndefOrEqual(Mask[i+1], i+1))
4438 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4439 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4440 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4441 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4442 const X86Subtarget *Subtarget) {
4443 if (!Subtarget->hasSSE3())
4446 unsigned NumElems = VT.getVectorNumElements();
4448 if ((VT.is128BitVector() && NumElems != 4) ||
4449 (VT.is256BitVector() && NumElems != 8) ||
4450 (VT.is512BitVector() && NumElems != 16))
4453 // "i" is the value the indexed mask element must have
4454 for (unsigned i = 0; i != NumElems; i += 2)
4455 if (!isUndefOrEqual(Mask[i], i) ||
4456 !isUndefOrEqual(Mask[i+1], i))
4462 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4463 /// specifies a shuffle of elements that is suitable for input to 256-bit
4464 /// version of MOVDDUP.
4465 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4466 if (!HasFp256 || !VT.is256BitVector())
4469 unsigned NumElts = VT.getVectorNumElements();
4473 for (unsigned i = 0; i != NumElts/2; ++i)
4474 if (!isUndefOrEqual(Mask[i], 0))
4476 for (unsigned i = NumElts/2; i != NumElts; ++i)
4477 if (!isUndefOrEqual(Mask[i], NumElts/2))
4482 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4483 /// specifies a shuffle of elements that is suitable for input to 128-bit
4484 /// version of MOVDDUP.
4485 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4486 if (!VT.is128BitVector())
4489 unsigned e = VT.getVectorNumElements() / 2;
4490 for (unsigned i = 0; i != e; ++i)
4491 if (!isUndefOrEqual(Mask[i], i))
4493 for (unsigned i = 0; i != e; ++i)
4494 if (!isUndefOrEqual(Mask[e+i], i))
4499 /// isVEXTRACTIndex - Return true if the specified
4500 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4501 /// suitable for instruction that extract 128 or 256 bit vectors
4502 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4503 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4504 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4507 // The index should be aligned on a vecWidth-bit boundary.
4509 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4511 MVT VT = N->getSimpleValueType(0);
4512 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4513 bool Result = (Index * ElSize) % vecWidth == 0;
4518 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4519 /// operand specifies a subvector insert that is suitable for input to
4520 /// insertion of 128 or 256-bit subvectors
4521 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4522 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4523 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4525 // The index should be aligned on a vecWidth-bit boundary.
4527 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4529 MVT VT = N->getSimpleValueType(0);
4530 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4531 bool Result = (Index * ElSize) % vecWidth == 0;
4536 bool X86::isVINSERT128Index(SDNode *N) {
4537 return isVINSERTIndex(N, 128);
4540 bool X86::isVINSERT256Index(SDNode *N) {
4541 return isVINSERTIndex(N, 256);
4544 bool X86::isVEXTRACT128Index(SDNode *N) {
4545 return isVEXTRACTIndex(N, 128);
4548 bool X86::isVEXTRACT256Index(SDNode *N) {
4549 return isVEXTRACTIndex(N, 256);
4552 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4553 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4554 /// Handles 128-bit and 256-bit.
4555 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4556 MVT VT = N->getSimpleValueType(0);
4558 assert((VT.getSizeInBits() >= 128) &&
4559 "Unsupported vector type for PSHUF/SHUFP");
4561 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4562 // independently on 128-bit lanes.
4563 unsigned NumElts = VT.getVectorNumElements();
4564 unsigned NumLanes = VT.getSizeInBits()/128;
4565 unsigned NumLaneElts = NumElts/NumLanes;
4567 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4568 "Only supports 2, 4 or 8 elements per lane");
4570 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4572 for (unsigned i = 0; i != NumElts; ++i) {
4573 int Elt = N->getMaskElt(i);
4574 if (Elt < 0) continue;
4575 Elt &= NumLaneElts - 1;
4576 unsigned ShAmt = (i << Shift) % 8;
4577 Mask |= Elt << ShAmt;
4583 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4584 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4585 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4586 MVT VT = N->getSimpleValueType(0);
4588 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4589 "Unsupported vector type for PSHUFHW");
4591 unsigned NumElts = VT.getVectorNumElements();
4594 for (unsigned l = 0; l != NumElts; l += 8) {
4595 // 8 nodes per lane, but we only care about the last 4.
4596 for (unsigned i = 0; i < 4; ++i) {
4597 int Elt = N->getMaskElt(l+i+4);
4598 if (Elt < 0) continue;
4599 Elt &= 0x3; // only 2-bits.
4600 Mask |= Elt << (i * 2);
4607 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4608 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4609 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4610 MVT VT = N->getSimpleValueType(0);
4612 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4613 "Unsupported vector type for PSHUFHW");
4615 unsigned NumElts = VT.getVectorNumElements();
4618 for (unsigned l = 0; l != NumElts; l += 8) {
4619 // 8 nodes per lane, but we only care about the first 4.
4620 for (unsigned i = 0; i < 4; ++i) {
4621 int Elt = N->getMaskElt(l+i);
4622 if (Elt < 0) continue;
4623 Elt &= 0x3; // only 2-bits
4624 Mask |= Elt << (i * 2);
4631 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4632 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4633 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4634 MVT VT = SVOp->getSimpleValueType(0);
4635 unsigned EltSize = VT.is512BitVector() ? 1 :
4636 VT.getVectorElementType().getSizeInBits() >> 3;
4638 unsigned NumElts = VT.getVectorNumElements();
4639 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4640 unsigned NumLaneElts = NumElts/NumLanes;
4644 for (i = 0; i != NumElts; ++i) {
4645 Val = SVOp->getMaskElt(i);
4649 if (Val >= (int)NumElts)
4650 Val -= NumElts - NumLaneElts;
4652 assert(Val - i > 0 && "PALIGNR imm should be positive");
4653 return (Val - i) * EltSize;
4656 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4657 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4658 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4659 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4662 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4664 MVT VecVT = N->getOperand(0).getSimpleValueType();
4665 MVT ElVT = VecVT.getVectorElementType();
4667 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4668 return Index / NumElemsPerChunk;
4671 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4672 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4673 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4674 llvm_unreachable("Illegal insert subvector for VINSERT");
4677 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4679 MVT VecVT = N->getSimpleValueType(0);
4680 MVT ElVT = VecVT.getVectorElementType();
4682 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4683 return Index / NumElemsPerChunk;
4686 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4687 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4688 /// and VINSERTI128 instructions.
4689 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4690 return getExtractVEXTRACTImmediate(N, 128);
4693 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4694 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4695 /// and VINSERTI64x4 instructions.
4696 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4697 return getExtractVEXTRACTImmediate(N, 256);
4700 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4701 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4702 /// and VINSERTI128 instructions.
4703 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4704 return getInsertVINSERTImmediate(N, 128);
4707 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4708 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4709 /// and VINSERTI64x4 instructions.
4710 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4711 return getInsertVINSERTImmediate(N, 256);
4714 /// isZero - Returns true if Elt is a constant integer zero
4715 static bool isZero(SDValue V) {
4716 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4717 return C && C->isNullValue();
4720 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4722 bool X86::isZeroNode(SDValue Elt) {
4725 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4726 return CFP->getValueAPF().isPosZero();
4730 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4731 /// their permute mask.
4732 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4733 SelectionDAG &DAG) {
4734 MVT VT = SVOp->getSimpleValueType(0);
4735 unsigned NumElems = VT.getVectorNumElements();
4736 SmallVector<int, 8> MaskVec;
4738 for (unsigned i = 0; i != NumElems; ++i) {
4739 int Idx = SVOp->getMaskElt(i);
4741 if (Idx < (int)NumElems)
4746 MaskVec.push_back(Idx);
4748 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4749 SVOp->getOperand(0), &MaskVec[0]);
4752 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4753 /// match movhlps. The lower half elements should come from upper half of
4754 /// V1 (and in order), and the upper half elements should come from the upper
4755 /// half of V2 (and in order).
4756 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4757 if (!VT.is128BitVector())
4759 if (VT.getVectorNumElements() != 4)
4761 for (unsigned i = 0, e = 2; i != e; ++i)
4762 if (!isUndefOrEqual(Mask[i], i+2))
4764 for (unsigned i = 2; i != 4; ++i)
4765 if (!isUndefOrEqual(Mask[i], i+4))
4770 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4771 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4773 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4774 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4776 N = N->getOperand(0).getNode();
4777 if (!ISD::isNON_EXTLoad(N))
4780 *LD = cast<LoadSDNode>(N);
4784 // Test whether the given value is a vector value which will be legalized
4786 static bool WillBeConstantPoolLoad(SDNode *N) {
4787 if (N->getOpcode() != ISD::BUILD_VECTOR)
4790 // Check for any non-constant elements.
4791 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4792 switch (N->getOperand(i).getNode()->getOpcode()) {
4794 case ISD::ConstantFP:
4801 // Vectors of all-zeros and all-ones are materialized with special
4802 // instructions rather than being loaded.
4803 return !ISD::isBuildVectorAllZeros(N) &&
4804 !ISD::isBuildVectorAllOnes(N);
4807 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4808 /// match movlp{s|d}. The lower half elements should come from lower half of
4809 /// V1 (and in order), and the upper half elements should come from the upper
4810 /// half of V2 (and in order). And since V1 will become the source of the
4811 /// MOVLP, it must be either a vector load or a scalar load to vector.
4812 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4813 ArrayRef<int> Mask, MVT VT) {
4814 if (!VT.is128BitVector())
4817 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4819 // Is V2 is a vector load, don't do this transformation. We will try to use
4820 // load folding shufps op.
4821 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4824 unsigned NumElems = VT.getVectorNumElements();
4826 if (NumElems != 2 && NumElems != 4)
4828 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4829 if (!isUndefOrEqual(Mask[i], i))
4831 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4832 if (!isUndefOrEqual(Mask[i], i+NumElems))
4837 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4839 static bool isSplatVector(SDNode *N) {
4840 if (N->getOpcode() != ISD::BUILD_VECTOR)
4843 SDValue SplatValue = N->getOperand(0);
4844 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4845 if (N->getOperand(i) != SplatValue)
4850 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4851 /// to an zero vector.
4852 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4853 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4854 SDValue V1 = N->getOperand(0);
4855 SDValue V2 = N->getOperand(1);
4856 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4857 for (unsigned i = 0; i != NumElems; ++i) {
4858 int Idx = N->getMaskElt(i);
4859 if (Idx >= (int)NumElems) {
4860 unsigned Opc = V2.getOpcode();
4861 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4863 if (Opc != ISD::BUILD_VECTOR ||
4864 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4866 } else if (Idx >= 0) {
4867 unsigned Opc = V1.getOpcode();
4868 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4870 if (Opc != ISD::BUILD_VECTOR ||
4871 !X86::isZeroNode(V1.getOperand(Idx)))
4878 /// getZeroVector - Returns a vector of specified type with all zero elements.
4880 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4881 SelectionDAG &DAG, SDLoc dl) {
4882 assert(VT.isVector() && "Expected a vector type");
4884 // Always build SSE zero vectors as <4 x i32> bitcasted
4885 // to their dest type. This ensures they get CSE'd.
4887 if (VT.is128BitVector()) { // SSE
4888 if (Subtarget->hasSSE2()) { // SSE2
4889 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4890 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4892 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4893 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4895 } else if (VT.is256BitVector()) { // AVX
4896 if (Subtarget->hasInt256()) { // AVX2
4897 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4898 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4899 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4901 // 256-bit logic and arithmetic instructions in AVX are all
4902 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4903 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4904 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4905 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4907 } else if (VT.is512BitVector()) { // AVX-512
4908 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4909 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4910 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4911 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4912 } else if (VT.getScalarType() == MVT::i1) {
4913 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4914 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4915 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4916 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4918 llvm_unreachable("Unexpected vector type");
4920 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4923 /// getOnesVector - Returns a vector of specified type with all bits set.
4924 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4925 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4926 /// Then bitcast to their original type, ensuring they get CSE'd.
4927 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4929 assert(VT.isVector() && "Expected a vector type");
4931 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4933 if (VT.is256BitVector()) {
4934 if (HasInt256) { // AVX2
4935 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4936 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4938 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4939 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4941 } else if (VT.is128BitVector()) {
4942 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4944 llvm_unreachable("Unexpected vector type");
4946 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4949 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4950 /// that point to V2 points to its first element.
4951 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4952 for (unsigned i = 0; i != NumElems; ++i) {
4953 if (Mask[i] > (int)NumElems) {
4959 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4960 /// operation of specified width.
4961 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4963 unsigned NumElems = VT.getVectorNumElements();
4964 SmallVector<int, 8> Mask;
4965 Mask.push_back(NumElems);
4966 for (unsigned i = 1; i != NumElems; ++i)
4968 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4971 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4972 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4974 unsigned NumElems = VT.getVectorNumElements();
4975 SmallVector<int, 8> Mask;
4976 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4978 Mask.push_back(i + NumElems);
4980 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4983 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4984 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4986 unsigned NumElems = VT.getVectorNumElements();
4987 SmallVector<int, 8> Mask;
4988 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4989 Mask.push_back(i + Half);
4990 Mask.push_back(i + NumElems + Half);
4992 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4995 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4996 // a generic shuffle instruction because the target has no such instructions.
4997 // Generate shuffles which repeat i16 and i8 several times until they can be
4998 // represented by v4f32 and then be manipulated by target suported shuffles.
4999 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5000 MVT VT = V.getSimpleValueType();
5001 int NumElems = VT.getVectorNumElements();
5004 while (NumElems > 4) {
5005 if (EltNo < NumElems/2) {
5006 V = getUnpackl(DAG, dl, VT, V, V);
5008 V = getUnpackh(DAG, dl, VT, V, V);
5009 EltNo -= NumElems/2;
5016 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5017 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5018 MVT VT = V.getSimpleValueType();
5021 if (VT.is128BitVector()) {
5022 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5023 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5024 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5026 } else if (VT.is256BitVector()) {
5027 // To use VPERMILPS to splat scalars, the second half of indicies must
5028 // refer to the higher part, which is a duplication of the lower one,
5029 // because VPERMILPS can only handle in-lane permutations.
5030 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5031 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5033 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5034 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5037 llvm_unreachable("Vector size not supported");
5039 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5042 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5043 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5044 MVT SrcVT = SV->getSimpleValueType(0);
5045 SDValue V1 = SV->getOperand(0);
5048 int EltNo = SV->getSplatIndex();
5049 int NumElems = SrcVT.getVectorNumElements();
5050 bool Is256BitVec = SrcVT.is256BitVector();
5052 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5053 "Unknown how to promote splat for type");
5055 // Extract the 128-bit part containing the splat element and update
5056 // the splat element index when it refers to the higher register.
5058 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5059 if (EltNo >= NumElems/2)
5060 EltNo -= NumElems/2;
5063 // All i16 and i8 vector types can't be used directly by a generic shuffle
5064 // instruction because the target has no such instruction. Generate shuffles
5065 // which repeat i16 and i8 several times until they fit in i32, and then can
5066 // be manipulated by target suported shuffles.
5067 MVT EltVT = SrcVT.getVectorElementType();
5068 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5069 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5071 // Recreate the 256-bit vector and place the same 128-bit vector
5072 // into the low and high part. This is necessary because we want
5073 // to use VPERM* to shuffle the vectors
5075 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5078 return getLegalSplat(DAG, V1, EltNo);
5081 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5082 /// vector of zero or undef vector. This produces a shuffle where the low
5083 /// element of V2 is swizzled into the zero/undef vector, landing at element
5084 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5085 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5087 const X86Subtarget *Subtarget,
5088 SelectionDAG &DAG) {
5089 MVT VT = V2.getSimpleValueType();
5091 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5092 unsigned NumElems = VT.getVectorNumElements();
5093 SmallVector<int, 16> MaskVec;
5094 for (unsigned i = 0; i != NumElems; ++i)
5095 // If this is the insertion idx, put the low elt of V2 here.
5096 MaskVec.push_back(i == Idx ? NumElems : i);
5097 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5100 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5101 /// target specific opcode. Returns true if the Mask could be calculated.
5102 /// Sets IsUnary to true if only uses one source.
5103 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5104 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5105 unsigned NumElems = VT.getVectorNumElements();
5109 switch(N->getOpcode()) {
5111 ImmN = N->getOperand(N->getNumOperands()-1);
5112 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5114 case X86ISD::UNPCKH:
5115 DecodeUNPCKHMask(VT, Mask);
5117 case X86ISD::UNPCKL:
5118 DecodeUNPCKLMask(VT, Mask);
5120 case X86ISD::MOVHLPS:
5121 DecodeMOVHLPSMask(NumElems, Mask);
5123 case X86ISD::MOVLHPS:
5124 DecodeMOVLHPSMask(NumElems, Mask);
5126 case X86ISD::PALIGNR:
5127 ImmN = N->getOperand(N->getNumOperands()-1);
5128 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5130 case X86ISD::PSHUFD:
5131 case X86ISD::VPERMILP:
5132 ImmN = N->getOperand(N->getNumOperands()-1);
5133 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5136 case X86ISD::PSHUFHW:
5137 ImmN = N->getOperand(N->getNumOperands()-1);
5138 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5141 case X86ISD::PSHUFLW:
5142 ImmN = N->getOperand(N->getNumOperands()-1);
5143 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5146 case X86ISD::VPERMI:
5147 ImmN = N->getOperand(N->getNumOperands()-1);
5148 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5152 case X86ISD::MOVSD: {
5153 // The index 0 always comes from the first element of the second source,
5154 // this is why MOVSS and MOVSD are used in the first place. The other
5155 // elements come from the other positions of the first source vector
5156 Mask.push_back(NumElems);
5157 for (unsigned i = 1; i != NumElems; ++i) {
5162 case X86ISD::VPERM2X128:
5163 ImmN = N->getOperand(N->getNumOperands()-1);
5164 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5165 if (Mask.empty()) return false;
5167 case X86ISD::MOVDDUP:
5168 case X86ISD::MOVLHPD:
5169 case X86ISD::MOVLPD:
5170 case X86ISD::MOVLPS:
5171 case X86ISD::MOVSHDUP:
5172 case X86ISD::MOVSLDUP:
5173 // Not yet implemented
5175 default: llvm_unreachable("unknown target shuffle node");
5181 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5182 /// element of the result of the vector shuffle.
5183 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5186 return SDValue(); // Limit search depth.
5188 SDValue V = SDValue(N, 0);
5189 EVT VT = V.getValueType();
5190 unsigned Opcode = V.getOpcode();
5192 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5193 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5194 int Elt = SV->getMaskElt(Index);
5197 return DAG.getUNDEF(VT.getVectorElementType());
5199 unsigned NumElems = VT.getVectorNumElements();
5200 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5201 : SV->getOperand(1);
5202 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5205 // Recurse into target specific vector shuffles to find scalars.
5206 if (isTargetShuffle(Opcode)) {
5207 MVT ShufVT = V.getSimpleValueType();
5208 unsigned NumElems = ShufVT.getVectorNumElements();
5209 SmallVector<int, 16> ShuffleMask;
5212 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5215 int Elt = ShuffleMask[Index];
5217 return DAG.getUNDEF(ShufVT.getVectorElementType());
5219 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5221 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5225 // Actual nodes that may contain scalar elements
5226 if (Opcode == ISD::BITCAST) {
5227 V = V.getOperand(0);
5228 EVT SrcVT = V.getValueType();
5229 unsigned NumElems = VT.getVectorNumElements();
5231 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5235 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5236 return (Index == 0) ? V.getOperand(0)
5237 : DAG.getUNDEF(VT.getVectorElementType());
5239 if (V.getOpcode() == ISD::BUILD_VECTOR)
5240 return V.getOperand(Index);
5245 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5246 /// shuffle operation which come from a consecutively from a zero. The
5247 /// search can start in two different directions, from left or right.
5248 /// We count undefs as zeros until PreferredNum is reached.
5249 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5250 unsigned NumElems, bool ZerosFromLeft,
5252 unsigned PreferredNum = -1U) {
5253 unsigned NumZeros = 0;
5254 for (unsigned i = 0; i != NumElems; ++i) {
5255 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5256 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5260 if (X86::isZeroNode(Elt))
5262 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5263 NumZeros = std::min(NumZeros + 1, PreferredNum);
5271 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5272 /// correspond consecutively to elements from one of the vector operands,
5273 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5275 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5276 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5277 unsigned NumElems, unsigned &OpNum) {
5278 bool SeenV1 = false;
5279 bool SeenV2 = false;
5281 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5282 int Idx = SVOp->getMaskElt(i);
5283 // Ignore undef indicies
5287 if (Idx < (int)NumElems)
5292 // Only accept consecutive elements from the same vector
5293 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5297 OpNum = SeenV1 ? 0 : 1;
5301 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5302 /// logical left shift of a vector.
5303 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5304 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5306 SVOp->getSimpleValueType(0).getVectorNumElements();
5307 unsigned NumZeros = getNumOfConsecutiveZeros(
5308 SVOp, NumElems, false /* check zeros from right */, DAG,
5309 SVOp->getMaskElt(0));
5315 // Considering the elements in the mask that are not consecutive zeros,
5316 // check if they consecutively come from only one of the source vectors.
5318 // V1 = {X, A, B, C} 0
5320 // vector_shuffle V1, V2 <1, 2, 3, X>
5322 if (!isShuffleMaskConsecutive(SVOp,
5323 0, // Mask Start Index
5324 NumElems-NumZeros, // Mask End Index(exclusive)
5325 NumZeros, // Where to start looking in the src vector
5326 NumElems, // Number of elements in vector
5327 OpSrc)) // Which source operand ?
5332 ShVal = SVOp->getOperand(OpSrc);
5336 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5337 /// logical left shift of a vector.
5338 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5339 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5341 SVOp->getSimpleValueType(0).getVectorNumElements();
5342 unsigned NumZeros = getNumOfConsecutiveZeros(
5343 SVOp, NumElems, true /* check zeros from left */, DAG,
5344 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5350 // Considering the elements in the mask that are not consecutive zeros,
5351 // check if they consecutively come from only one of the source vectors.
5353 // 0 { A, B, X, X } = V2
5355 // vector_shuffle V1, V2 <X, X, 4, 5>
5357 if (!isShuffleMaskConsecutive(SVOp,
5358 NumZeros, // Mask Start Index
5359 NumElems, // Mask End Index(exclusive)
5360 0, // Where to start looking in the src vector
5361 NumElems, // Number of elements in vector
5362 OpSrc)) // Which source operand ?
5367 ShVal = SVOp->getOperand(OpSrc);
5371 /// isVectorShift - Returns true if the shuffle can be implemented as a
5372 /// logical left or right shift of a vector.
5373 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5374 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5375 // Although the logic below support any bitwidth size, there are no
5376 // shift instructions which handle more than 128-bit vectors.
5377 if (!SVOp->getSimpleValueType(0).is128BitVector())
5380 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5381 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5387 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5389 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5390 unsigned NumNonZero, unsigned NumZero,
5392 const X86Subtarget* Subtarget,
5393 const TargetLowering &TLI) {
5400 for (unsigned i = 0; i < 16; ++i) {
5401 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5402 if (ThisIsNonZero && First) {
5404 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5406 V = DAG.getUNDEF(MVT::v8i16);
5411 SDValue ThisElt, LastElt;
5412 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5413 if (LastIsNonZero) {
5414 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5415 MVT::i16, Op.getOperand(i-1));
5417 if (ThisIsNonZero) {
5418 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5419 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5420 ThisElt, DAG.getConstant(8, MVT::i8));
5422 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5426 if (ThisElt.getNode())
5427 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5428 DAG.getIntPtrConstant(i/2));
5432 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5435 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5437 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5438 unsigned NumNonZero, unsigned NumZero,
5440 const X86Subtarget* Subtarget,
5441 const TargetLowering &TLI) {
5448 for (unsigned i = 0; i < 8; ++i) {
5449 bool isNonZero = (NonZeros & (1 << i)) != 0;
5453 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5455 V = DAG.getUNDEF(MVT::v8i16);
5458 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5459 MVT::v8i16, V, Op.getOperand(i),
5460 DAG.getIntPtrConstant(i));
5467 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5468 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5469 unsigned NonZeros, unsigned NumNonZero,
5470 unsigned NumZero, SelectionDAG &DAG,
5471 const X86Subtarget *Subtarget,
5472 const TargetLowering &TLI) {
5473 // We know there's at least one non-zero element
5474 unsigned FirstNonZeroIdx = 0;
5475 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5476 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5477 X86::isZeroNode(FirstNonZero)) {
5479 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5482 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5483 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5486 SDValue V = FirstNonZero.getOperand(0);
5487 MVT VVT = V.getSimpleValueType();
5488 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5491 unsigned FirstNonZeroDst =
5492 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5493 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5494 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5495 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5497 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5498 SDValue Elem = Op.getOperand(Idx);
5499 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5502 // TODO: What else can be here? Deal with it.
5503 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5506 // TODO: Some optimizations are still possible here
5507 // ex: Getting one element from a vector, and the rest from another.
5508 if (Elem.getOperand(0) != V)
5511 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5514 else if (IncorrectIdx == -1U) {
5518 // There was already one element with an incorrect index.
5519 // We can't optimize this case to an insertps.
5523 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5525 EVT VT = Op.getSimpleValueType();
5526 unsigned ElementMoveMask = 0;
5527 if (IncorrectIdx == -1U)
5528 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5530 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5532 SDValue InsertpsMask =
5533 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5534 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5540 /// getVShift - Return a vector logical shift node.
5542 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5543 unsigned NumBits, SelectionDAG &DAG,
5544 const TargetLowering &TLI, SDLoc dl) {
5545 assert(VT.is128BitVector() && "Unknown type for VShift");
5546 EVT ShVT = MVT::v2i64;
5547 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5548 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5549 return DAG.getNode(ISD::BITCAST, dl, VT,
5550 DAG.getNode(Opc, dl, ShVT, SrcOp,
5551 DAG.getConstant(NumBits,
5552 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5556 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5558 // Check if the scalar load can be widened into a vector load. And if
5559 // the address is "base + cst" see if the cst can be "absorbed" into
5560 // the shuffle mask.
5561 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5562 SDValue Ptr = LD->getBasePtr();
5563 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5565 EVT PVT = LD->getValueType(0);
5566 if (PVT != MVT::i32 && PVT != MVT::f32)
5571 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5572 FI = FINode->getIndex();
5574 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5575 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5576 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5577 Offset = Ptr.getConstantOperandVal(1);
5578 Ptr = Ptr.getOperand(0);
5583 // FIXME: 256-bit vector instructions don't require a strict alignment,
5584 // improve this code to support it better.
5585 unsigned RequiredAlign = VT.getSizeInBits()/8;
5586 SDValue Chain = LD->getChain();
5587 // Make sure the stack object alignment is at least 16 or 32.
5588 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5589 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5590 if (MFI->isFixedObjectIndex(FI)) {
5591 // Can't change the alignment. FIXME: It's possible to compute
5592 // the exact stack offset and reference FI + adjust offset instead.
5593 // If someone *really* cares about this. That's the way to implement it.
5596 MFI->setObjectAlignment(FI, RequiredAlign);
5600 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5601 // Ptr + (Offset & ~15).
5604 if ((Offset % RequiredAlign) & 3)
5606 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5608 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5609 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5611 int EltNo = (Offset - StartOffset) >> 2;
5612 unsigned NumElems = VT.getVectorNumElements();
5614 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5615 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5616 LD->getPointerInfo().getWithOffset(StartOffset),
5617 false, false, false, 0);
5619 SmallVector<int, 8> Mask;
5620 for (unsigned i = 0; i != NumElems; ++i)
5621 Mask.push_back(EltNo);
5623 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5629 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5630 /// vector of type 'VT', see if the elements can be replaced by a single large
5631 /// load which has the same value as a build_vector whose operands are 'elts'.
5633 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5635 /// FIXME: we'd also like to handle the case where the last elements are zero
5636 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5637 /// There's even a handy isZeroNode for that purpose.
5638 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5639 SDLoc &DL, SelectionDAG &DAG,
5640 bool isAfterLegalize) {
5641 EVT EltVT = VT.getVectorElementType();
5642 unsigned NumElems = Elts.size();
5644 LoadSDNode *LDBase = nullptr;
5645 unsigned LastLoadedElt = -1U;
5647 // For each element in the initializer, see if we've found a load or an undef.
5648 // If we don't find an initial load element, or later load elements are
5649 // non-consecutive, bail out.
5650 for (unsigned i = 0; i < NumElems; ++i) {
5651 SDValue Elt = Elts[i];
5653 if (!Elt.getNode() ||
5654 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5657 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5659 LDBase = cast<LoadSDNode>(Elt.getNode());
5663 if (Elt.getOpcode() == ISD::UNDEF)
5666 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5667 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5672 // If we have found an entire vector of loads and undefs, then return a large
5673 // load of the entire vector width starting at the base pointer. If we found
5674 // consecutive loads for the low half, generate a vzext_load node.
5675 if (LastLoadedElt == NumElems - 1) {
5677 if (isAfterLegalize &&
5678 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5681 SDValue NewLd = SDValue();
5683 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5684 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5685 LDBase->getPointerInfo(),
5686 LDBase->isVolatile(), LDBase->isNonTemporal(),
5687 LDBase->isInvariant(), 0);
5688 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5689 LDBase->getPointerInfo(),
5690 LDBase->isVolatile(), LDBase->isNonTemporal(),
5691 LDBase->isInvariant(), LDBase->getAlignment());
5693 if (LDBase->hasAnyUseOfValue(1)) {
5694 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5696 SDValue(NewLd.getNode(), 1));
5697 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5698 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5699 SDValue(NewLd.getNode(), 1));
5704 if (NumElems == 4 && LastLoadedElt == 1 &&
5705 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5706 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5707 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5709 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5710 LDBase->getPointerInfo(),
5711 LDBase->getAlignment(),
5712 false/*isVolatile*/, true/*ReadMem*/,
5715 // Make sure the newly-created LOAD is in the same position as LDBase in
5716 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5717 // update uses of LDBase's output chain to use the TokenFactor.
5718 if (LDBase->hasAnyUseOfValue(1)) {
5719 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5720 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5721 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5722 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5723 SDValue(ResNode.getNode(), 1));
5726 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5731 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5732 /// to generate a splat value for the following cases:
5733 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5734 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5735 /// a scalar load, or a constant.
5736 /// The VBROADCAST node is returned when a pattern is found,
5737 /// or SDValue() otherwise.
5738 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5739 SelectionDAG &DAG) {
5740 if (!Subtarget->hasFp256())
5743 MVT VT = Op.getSimpleValueType();
5746 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5747 "Unsupported vector type for broadcast.");
5752 switch (Op.getOpcode()) {
5754 // Unknown pattern found.
5757 case ISD::BUILD_VECTOR: {
5758 // The BUILD_VECTOR node must be a splat.
5759 if (!isSplatVector(Op.getNode()))
5762 Ld = Op.getOperand(0);
5763 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5764 Ld.getOpcode() == ISD::ConstantFP);
5766 // The suspected load node has several users. Make sure that all
5767 // of its users are from the BUILD_VECTOR node.
5768 // Constants may have multiple users.
5769 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5774 case ISD::VECTOR_SHUFFLE: {
5775 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5777 // Shuffles must have a splat mask where the first element is
5779 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5782 SDValue Sc = Op.getOperand(0);
5783 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5784 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5786 if (!Subtarget->hasInt256())
5789 // Use the register form of the broadcast instruction available on AVX2.
5790 if (VT.getSizeInBits() >= 256)
5791 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5792 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5795 Ld = Sc.getOperand(0);
5796 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5797 Ld.getOpcode() == ISD::ConstantFP);
5799 // The scalar_to_vector node and the suspected
5800 // load node must have exactly one user.
5801 // Constants may have multiple users.
5803 // AVX-512 has register version of the broadcast
5804 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5805 Ld.getValueType().getSizeInBits() >= 32;
5806 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5813 bool IsGE256 = (VT.getSizeInBits() >= 256);
5815 // Handle the broadcasting a single constant scalar from the constant pool
5816 // into a vector. On Sandybridge it is still better to load a constant vector
5817 // from the constant pool and not to broadcast it from a scalar.
5818 if (ConstSplatVal && Subtarget->hasInt256()) {
5819 EVT CVT = Ld.getValueType();
5820 assert(!CVT.isVector() && "Must not broadcast a vector type");
5821 unsigned ScalarSize = CVT.getSizeInBits();
5823 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5824 const Constant *C = nullptr;
5825 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5826 C = CI->getConstantIntValue();
5827 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5828 C = CF->getConstantFPValue();
5830 assert(C && "Invalid constant type");
5832 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5833 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5834 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5835 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5836 MachinePointerInfo::getConstantPool(),
5837 false, false, false, Alignment);
5839 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5843 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5844 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5846 // Handle AVX2 in-register broadcasts.
5847 if (!IsLoad && Subtarget->hasInt256() &&
5848 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5849 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5851 // The scalar source must be a normal load.
5855 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5856 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5858 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5859 // double since there is no vbroadcastsd xmm
5860 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5861 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5862 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5865 // Unsupported broadcast.
5869 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5870 /// underlying vector and index.
5872 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5874 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5876 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5877 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5880 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5882 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5884 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5885 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5888 // In this case the vector is the extract_subvector expression and the index
5889 // is 2, as specified by the shuffle.
5890 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5891 SDValue ShuffleVec = SVOp->getOperand(0);
5892 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5893 assert(ShuffleVecVT.getVectorElementType() ==
5894 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5896 int ShuffleIdx = SVOp->getMaskElt(Idx);
5897 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5898 ExtractedFromVec = ShuffleVec;
5904 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5905 MVT VT = Op.getSimpleValueType();
5907 // Skip if insert_vec_elt is not supported.
5908 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5909 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5913 unsigned NumElems = Op.getNumOperands();
5917 SmallVector<unsigned, 4> InsertIndices;
5918 SmallVector<int, 8> Mask(NumElems, -1);
5920 for (unsigned i = 0; i != NumElems; ++i) {
5921 unsigned Opc = Op.getOperand(i).getOpcode();
5923 if (Opc == ISD::UNDEF)
5926 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5927 // Quit if more than 1 elements need inserting.
5928 if (InsertIndices.size() > 1)
5931 InsertIndices.push_back(i);
5935 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5936 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5937 // Quit if non-constant index.
5938 if (!isa<ConstantSDNode>(ExtIdx))
5940 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5942 // Quit if extracted from vector of different type.
5943 if (ExtractedFromVec.getValueType() != VT)
5946 if (!VecIn1.getNode())
5947 VecIn1 = ExtractedFromVec;
5948 else if (VecIn1 != ExtractedFromVec) {
5949 if (!VecIn2.getNode())
5950 VecIn2 = ExtractedFromVec;
5951 else if (VecIn2 != ExtractedFromVec)
5952 // Quit if more than 2 vectors to shuffle
5956 if (ExtractedFromVec == VecIn1)
5958 else if (ExtractedFromVec == VecIn2)
5959 Mask[i] = Idx + NumElems;
5962 if (!VecIn1.getNode())
5965 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5966 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5967 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5968 unsigned Idx = InsertIndices[i];
5969 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5970 DAG.getIntPtrConstant(Idx));
5976 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5978 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5980 MVT VT = Op.getSimpleValueType();
5981 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5982 "Unexpected type in LowerBUILD_VECTORvXi1!");
5985 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5986 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5987 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5988 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5991 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5992 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5993 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5994 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5997 bool AllContants = true;
5998 uint64_t Immediate = 0;
5999 int NonConstIdx = -1;
6000 bool IsSplat = true;
6001 unsigned NumNonConsts = 0;
6002 unsigned NumConsts = 0;
6003 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6004 SDValue In = Op.getOperand(idx);
6005 if (In.getOpcode() == ISD::UNDEF)
6007 if (!isa<ConstantSDNode>(In)) {
6008 AllContants = false;
6014 if (cast<ConstantSDNode>(In)->getZExtValue())
6015 Immediate |= (1ULL << idx);
6017 if (In != Op.getOperand(0))
6022 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6023 DAG.getConstant(Immediate, MVT::i16));
6024 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6025 DAG.getIntPtrConstant(0));
6028 if (NumNonConsts == 1 && NonConstIdx != 0) {
6031 SDValue VecAsImm = DAG.getConstant(Immediate,
6032 MVT::getIntegerVT(VT.getSizeInBits()));
6033 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6036 DstVec = DAG.getUNDEF(VT);
6037 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6038 Op.getOperand(NonConstIdx),
6039 DAG.getIntPtrConstant(NonConstIdx));
6041 if (!IsSplat && (NonConstIdx != 0))
6042 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6043 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6046 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6047 DAG.getConstant(-1, SelectVT),
6048 DAG.getConstant(0, SelectVT));
6050 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6051 DAG.getConstant((Immediate | 1), SelectVT),
6052 DAG.getConstant(Immediate, SelectVT));
6053 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6056 /// \brief Return true if \p N implements a horizontal binop and return the
6057 /// operands for the horizontal binop into V0 and V1.
6059 /// This is a helper function of PerformBUILD_VECTORCombine.
6060 /// This function checks that the build_vector \p N in input implements a
6061 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6062 /// operation to match.
6063 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6064 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6065 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6068 /// This function only analyzes elements of \p N whose indices are
6069 /// in range [BaseIdx, LastIdx).
6070 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6072 unsigned BaseIdx, unsigned LastIdx,
6073 SDValue &V0, SDValue &V1) {
6074 EVT VT = N->getValueType(0);
6076 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6077 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6078 "Invalid Vector in input!");
6080 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6081 bool CanFold = true;
6082 unsigned ExpectedVExtractIdx = BaseIdx;
6083 unsigned NumElts = LastIdx - BaseIdx;
6084 V0 = DAG.getUNDEF(VT);
6085 V1 = DAG.getUNDEF(VT);
6087 // Check if N implements a horizontal binop.
6088 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6089 SDValue Op = N->getOperand(i + BaseIdx);
6092 if (Op->getOpcode() == ISD::UNDEF) {
6093 // Update the expected vector extract index.
6094 if (i * 2 == NumElts)
6095 ExpectedVExtractIdx = BaseIdx;
6096 ExpectedVExtractIdx += 2;
6100 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6105 SDValue Op0 = Op.getOperand(0);
6106 SDValue Op1 = Op.getOperand(1);
6108 // Try to match the following pattern:
6109 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6110 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6111 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6112 Op0.getOperand(0) == Op1.getOperand(0) &&
6113 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6114 isa<ConstantSDNode>(Op1.getOperand(1)));
6118 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6119 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6121 if (i * 2 < NumElts) {
6122 if (V0.getOpcode() == ISD::UNDEF)
6123 V0 = Op0.getOperand(0);
6125 if (V1.getOpcode() == ISD::UNDEF)
6126 V1 = Op0.getOperand(0);
6127 if (i * 2 == NumElts)
6128 ExpectedVExtractIdx = BaseIdx;
6131 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6132 if (I0 == ExpectedVExtractIdx)
6133 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6134 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6135 // Try to match the following dag sequence:
6136 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6137 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6141 ExpectedVExtractIdx += 2;
6147 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6148 /// a concat_vector.
6150 /// This is a helper function of PerformBUILD_VECTORCombine.
6151 /// This function expects two 256-bit vectors called V0 and V1.
6152 /// At first, each vector is split into two separate 128-bit vectors.
6153 /// Then, the resulting 128-bit vectors are used to implement two
6154 /// horizontal binary operations.
6156 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6158 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6159 /// the two new horizontal binop.
6160 /// When Mode is set, the first horizontal binop dag node would take as input
6161 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6162 /// horizontal binop dag node would take as input the lower 128-bit of V1
6163 /// and the upper 128-bit of V1.
6165 /// HADD V0_LO, V0_HI
6166 /// HADD V1_LO, V1_HI
6168 /// Otherwise, the first horizontal binop dag node takes as input the lower
6169 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6170 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6172 /// HADD V0_LO, V1_LO
6173 /// HADD V0_HI, V1_HI
6175 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6176 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6177 /// the upper 128-bits of the result.
6178 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6179 SDLoc DL, SelectionDAG &DAG,
6180 unsigned X86Opcode, bool Mode,
6181 bool isUndefLO, bool isUndefHI) {
6182 EVT VT = V0.getValueType();
6183 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6184 "Invalid nodes in input!");
6186 unsigned NumElts = VT.getVectorNumElements();
6187 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6188 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6189 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6190 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6191 EVT NewVT = V0_LO.getValueType();
6193 SDValue LO = DAG.getUNDEF(NewVT);
6194 SDValue HI = DAG.getUNDEF(NewVT);
6197 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6198 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6199 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6200 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6201 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6203 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6204 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6205 V1_LO->getOpcode() != ISD::UNDEF))
6206 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6208 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6209 V1_HI->getOpcode() != ISD::UNDEF))
6210 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6213 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6216 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6217 /// sequence of 'vadd + vsub + blendi'.
6218 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6219 const X86Subtarget *Subtarget) {
6221 EVT VT = BV->getValueType(0);
6222 unsigned NumElts = VT.getVectorNumElements();
6223 SDValue InVec0 = DAG.getUNDEF(VT);
6224 SDValue InVec1 = DAG.getUNDEF(VT);
6226 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6227 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6229 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6230 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6231 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6234 // Odd-numbered elements in the input build vector are obtained from
6235 // adding two integer/float elements.
6236 // Even-numbered elements in the input build vector are obtained from
6237 // subtracting two integer/float elements.
6238 unsigned ExpectedOpcode = ISD::FSUB;
6239 unsigned NextExpectedOpcode = ISD::FADD;
6240 bool AddFound = false;
6241 bool SubFound = false;
6243 for (unsigned i = 0, e = NumElts; i != e; i++) {
6244 SDValue Op = BV->getOperand(i);
6246 // Skip 'undef' values.
6247 unsigned Opcode = Op.getOpcode();
6248 if (Opcode == ISD::UNDEF) {
6249 std::swap(ExpectedOpcode, NextExpectedOpcode);
6253 // Early exit if we found an unexpected opcode.
6254 if (Opcode != ExpectedOpcode)
6257 SDValue Op0 = Op.getOperand(0);
6258 SDValue Op1 = Op.getOperand(1);
6260 // Try to match the following pattern:
6261 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6262 // Early exit if we cannot match that sequence.
6263 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6264 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6265 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6266 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6267 Op0.getOperand(1) != Op1.getOperand(1))
6270 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6274 // We found a valid add/sub node. Update the information accordingly.
6280 // Update InVec0 and InVec1.
6281 if (InVec0.getOpcode() == ISD::UNDEF)
6282 InVec0 = Op0.getOperand(0);
6283 if (InVec1.getOpcode() == ISD::UNDEF)
6284 InVec1 = Op1.getOperand(0);
6286 // Make sure that operands in input to each add/sub node always
6287 // come from a same pair of vectors.
6288 if (InVec0 != Op0.getOperand(0)) {
6289 if (ExpectedOpcode == ISD::FSUB)
6292 // FADD is commutable. Try to commute the operands
6293 // and then test again.
6294 std::swap(Op0, Op1);
6295 if (InVec0 != Op0.getOperand(0))
6299 if (InVec1 != Op1.getOperand(0))
6302 // Update the pair of expected opcodes.
6303 std::swap(ExpectedOpcode, NextExpectedOpcode);
6306 // Don't try to fold this build_vector into a VSELECT if it has
6307 // too many UNDEF operands.
6308 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6309 InVec1.getOpcode() != ISD::UNDEF) {
6310 // Emit a sequence of vector add and sub followed by a VSELECT.
6311 // The new VSELECT will be lowered into a BLENDI.
6312 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6313 // and emit a single ADDSUB instruction.
6314 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6315 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6317 // Construct the VSELECT mask.
6318 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6319 EVT SVT = MaskVT.getVectorElementType();
6320 unsigned SVTBits = SVT.getSizeInBits();
6321 SmallVector<SDValue, 8> Ops;
6323 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6324 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6325 APInt::getAllOnesValue(SVTBits);
6326 SDValue Constant = DAG.getConstant(Value, SVT);
6327 Ops.push_back(Constant);
6330 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6331 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6337 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6338 const X86Subtarget *Subtarget) {
6340 EVT VT = N->getValueType(0);
6341 unsigned NumElts = VT.getVectorNumElements();
6342 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6343 SDValue InVec0, InVec1;
6345 // Try to match an ADDSUB.
6346 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6347 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6348 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6349 if (Value.getNode())
6353 // Try to match horizontal ADD/SUB.
6354 unsigned NumUndefsLO = 0;
6355 unsigned NumUndefsHI = 0;
6356 unsigned Half = NumElts/2;
6358 // Count the number of UNDEF operands in the build_vector in input.
6359 for (unsigned i = 0, e = Half; i != e; ++i)
6360 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6363 for (unsigned i = Half, e = NumElts; i != e; ++i)
6364 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6367 // Early exit if this is either a build_vector of all UNDEFs or all the
6368 // operands but one are UNDEF.
6369 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6372 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6373 // Try to match an SSE3 float HADD/HSUB.
6374 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6375 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6377 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6378 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6379 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6380 // Try to match an SSSE3 integer HADD/HSUB.
6381 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6382 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6384 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6385 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6388 if (!Subtarget->hasAVX())
6391 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6392 // Try to match an AVX horizontal add/sub of packed single/double
6393 // precision floating point values from 256-bit vectors.
6394 SDValue InVec2, InVec3;
6395 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6396 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6397 ((InVec0.getOpcode() == ISD::UNDEF ||
6398 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6399 ((InVec1.getOpcode() == ISD::UNDEF ||
6400 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6401 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6403 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6404 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6405 ((InVec0.getOpcode() == ISD::UNDEF ||
6406 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6407 ((InVec1.getOpcode() == ISD::UNDEF ||
6408 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6409 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6410 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6411 // Try to match an AVX2 horizontal add/sub of signed integers.
6412 SDValue InVec2, InVec3;
6414 bool CanFold = true;
6416 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6417 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6418 ((InVec0.getOpcode() == ISD::UNDEF ||
6419 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6420 ((InVec1.getOpcode() == ISD::UNDEF ||
6421 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6422 X86Opcode = X86ISD::HADD;
6423 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6424 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6425 ((InVec0.getOpcode() == ISD::UNDEF ||
6426 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6427 ((InVec1.getOpcode() == ISD::UNDEF ||
6428 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6429 X86Opcode = X86ISD::HSUB;
6434 // Fold this build_vector into a single horizontal add/sub.
6435 // Do this only if the target has AVX2.
6436 if (Subtarget->hasAVX2())
6437 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6439 // Do not try to expand this build_vector into a pair of horizontal
6440 // add/sub if we can emit a pair of scalar add/sub.
6441 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6444 // Convert this build_vector into a pair of horizontal binop followed by
6446 bool isUndefLO = NumUndefsLO == Half;
6447 bool isUndefHI = NumUndefsHI == Half;
6448 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6449 isUndefLO, isUndefHI);
6453 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6454 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6456 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6457 X86Opcode = X86ISD::HADD;
6458 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6459 X86Opcode = X86ISD::HSUB;
6460 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6461 X86Opcode = X86ISD::FHADD;
6462 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6463 X86Opcode = X86ISD::FHSUB;
6467 // Don't try to expand this build_vector into a pair of horizontal add/sub
6468 // if we can simply emit a pair of scalar add/sub.
6469 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6472 // Convert this build_vector into two horizontal add/sub followed by
6474 bool isUndefLO = NumUndefsLO == Half;
6475 bool isUndefHI = NumUndefsHI == Half;
6476 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6477 isUndefLO, isUndefHI);
6484 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6487 MVT VT = Op.getSimpleValueType();
6488 MVT ExtVT = VT.getVectorElementType();
6489 unsigned NumElems = Op.getNumOperands();
6491 // Generate vectors for predicate vectors.
6492 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6493 return LowerBUILD_VECTORvXi1(Op, DAG);
6495 // Vectors containing all zeros can be matched by pxor and xorps later
6496 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6497 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6498 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6499 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6502 return getZeroVector(VT, Subtarget, DAG, dl);
6505 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6506 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6507 // vpcmpeqd on 256-bit vectors.
6508 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6509 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6512 if (!VT.is512BitVector())
6513 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6516 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6517 if (Broadcast.getNode())
6520 unsigned EVTBits = ExtVT.getSizeInBits();
6522 unsigned NumZero = 0;
6523 unsigned NumNonZero = 0;
6524 unsigned NonZeros = 0;
6525 bool IsAllConstants = true;
6526 SmallSet<SDValue, 8> Values;
6527 for (unsigned i = 0; i < NumElems; ++i) {
6528 SDValue Elt = Op.getOperand(i);
6529 if (Elt.getOpcode() == ISD::UNDEF)
6532 if (Elt.getOpcode() != ISD::Constant &&
6533 Elt.getOpcode() != ISD::ConstantFP)
6534 IsAllConstants = false;
6535 if (X86::isZeroNode(Elt))
6538 NonZeros |= (1 << i);
6543 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6544 if (NumNonZero == 0)
6545 return DAG.getUNDEF(VT);
6547 // Special case for single non-zero, non-undef, element.
6548 if (NumNonZero == 1) {
6549 unsigned Idx = countTrailingZeros(NonZeros);
6550 SDValue Item = Op.getOperand(Idx);
6552 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6553 // the value are obviously zero, truncate the value to i32 and do the
6554 // insertion that way. Only do this if the value is non-constant or if the
6555 // value is a constant being inserted into element 0. It is cheaper to do
6556 // a constant pool load than it is to do a movd + shuffle.
6557 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6558 (!IsAllConstants || Idx == 0)) {
6559 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6561 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6562 EVT VecVT = MVT::v4i32;
6563 unsigned VecElts = 4;
6565 // Truncate the value (which may itself be a constant) to i32, and
6566 // convert it to a vector with movd (S2V+shuffle to zero extend).
6567 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6568 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6569 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6571 // Now we have our 32-bit value zero extended in the low element of
6572 // a vector. If Idx != 0, swizzle it into place.
6574 SmallVector<int, 4> Mask;
6575 Mask.push_back(Idx);
6576 for (unsigned i = 1; i != VecElts; ++i)
6578 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6581 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6585 // If we have a constant or non-constant insertion into the low element of
6586 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6587 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6588 // depending on what the source datatype is.
6591 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6593 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6594 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6595 if (VT.is256BitVector() || VT.is512BitVector()) {
6596 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6597 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6598 Item, DAG.getIntPtrConstant(0));
6600 assert(VT.is128BitVector() && "Expected an SSE value type!");
6601 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6602 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6603 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6606 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6607 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6608 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6609 if (VT.is256BitVector()) {
6610 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6611 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6613 assert(VT.is128BitVector() && "Expected an SSE value type!");
6614 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6616 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6620 // Is it a vector logical left shift?
6621 if (NumElems == 2 && Idx == 1 &&
6622 X86::isZeroNode(Op.getOperand(0)) &&
6623 !X86::isZeroNode(Op.getOperand(1))) {
6624 unsigned NumBits = VT.getSizeInBits();
6625 return getVShift(true, VT,
6626 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6627 VT, Op.getOperand(1)),
6628 NumBits/2, DAG, *this, dl);
6631 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6634 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6635 // is a non-constant being inserted into an element other than the low one,
6636 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6637 // movd/movss) to move this into the low element, then shuffle it into
6639 if (EVTBits == 32) {
6640 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6642 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6643 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6644 SmallVector<int, 8> MaskVec;
6645 for (unsigned i = 0; i != NumElems; ++i)
6646 MaskVec.push_back(i == Idx ? 0 : 1);
6647 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6651 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6652 if (Values.size() == 1) {
6653 if (EVTBits == 32) {
6654 // Instead of a shuffle like this:
6655 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6656 // Check if it's possible to issue this instead.
6657 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6658 unsigned Idx = countTrailingZeros(NonZeros);
6659 SDValue Item = Op.getOperand(Idx);
6660 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6661 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6666 // A vector full of immediates; various special cases are already
6667 // handled, so this is best done with a single constant-pool load.
6671 // For AVX-length vectors, build the individual 128-bit pieces and use
6672 // shuffles to put them in place.
6673 if (VT.is256BitVector() || VT.is512BitVector()) {
6674 SmallVector<SDValue, 64> V;
6675 for (unsigned i = 0; i != NumElems; ++i)
6676 V.push_back(Op.getOperand(i));
6678 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6680 // Build both the lower and upper subvector.
6681 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6682 makeArrayRef(&V[0], NumElems/2));
6683 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6684 makeArrayRef(&V[NumElems / 2], NumElems/2));
6686 // Recreate the wider vector with the lower and upper part.
6687 if (VT.is256BitVector())
6688 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6689 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6692 // Let legalizer expand 2-wide build_vectors.
6693 if (EVTBits == 64) {
6694 if (NumNonZero == 1) {
6695 // One half is zero or undef.
6696 unsigned Idx = countTrailingZeros(NonZeros);
6697 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6698 Op.getOperand(Idx));
6699 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6704 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6705 if (EVTBits == 8 && NumElems == 16) {
6706 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6708 if (V.getNode()) return V;
6711 if (EVTBits == 16 && NumElems == 8) {
6712 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6714 if (V.getNode()) return V;
6717 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6718 if (EVTBits == 32 && NumElems == 4) {
6719 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6720 NumZero, DAG, Subtarget, *this);
6725 // If element VT is == 32 bits, turn it into a number of shuffles.
6726 SmallVector<SDValue, 8> V(NumElems);
6727 if (NumElems == 4 && NumZero > 0) {
6728 for (unsigned i = 0; i < 4; ++i) {
6729 bool isZero = !(NonZeros & (1 << i));
6731 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6733 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6736 for (unsigned i = 0; i < 2; ++i) {
6737 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6740 V[i] = V[i*2]; // Must be a zero vector.
6743 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6746 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6749 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6754 bool Reverse1 = (NonZeros & 0x3) == 2;
6755 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6759 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6760 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6762 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6765 if (Values.size() > 1 && VT.is128BitVector()) {
6766 // Check for a build vector of consecutive loads.
6767 for (unsigned i = 0; i < NumElems; ++i)
6768 V[i] = Op.getOperand(i);
6770 // Check for elements which are consecutive loads.
6771 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6775 // Check for a build vector from mostly shuffle plus few inserting.
6776 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6780 // For SSE 4.1, use insertps to put the high elements into the low element.
6781 if (getSubtarget()->hasSSE41()) {
6783 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6784 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6786 Result = DAG.getUNDEF(VT);
6788 for (unsigned i = 1; i < NumElems; ++i) {
6789 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6790 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6791 Op.getOperand(i), DAG.getIntPtrConstant(i));
6796 // Otherwise, expand into a number of unpckl*, start by extending each of
6797 // our (non-undef) elements to the full vector width with the element in the
6798 // bottom slot of the vector (which generates no code for SSE).
6799 for (unsigned i = 0; i < NumElems; ++i) {
6800 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6801 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6803 V[i] = DAG.getUNDEF(VT);
6806 // Next, we iteratively mix elements, e.g. for v4f32:
6807 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6808 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6809 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6810 unsigned EltStride = NumElems >> 1;
6811 while (EltStride != 0) {
6812 for (unsigned i = 0; i < EltStride; ++i) {
6813 // If V[i+EltStride] is undef and this is the first round of mixing,
6814 // then it is safe to just drop this shuffle: V[i] is already in the
6815 // right place, the one element (since it's the first round) being
6816 // inserted as undef can be dropped. This isn't safe for successive
6817 // rounds because they will permute elements within both vectors.
6818 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6819 EltStride == NumElems/2)
6822 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6831 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6832 // to create 256-bit vectors from two other 128-bit ones.
6833 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6835 MVT ResVT = Op.getSimpleValueType();
6837 assert((ResVT.is256BitVector() ||
6838 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6840 SDValue V1 = Op.getOperand(0);
6841 SDValue V2 = Op.getOperand(1);
6842 unsigned NumElems = ResVT.getVectorNumElements();
6843 if(ResVT.is256BitVector())
6844 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6846 if (Op.getNumOperands() == 4) {
6847 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6848 ResVT.getVectorNumElements()/2);
6849 SDValue V3 = Op.getOperand(2);
6850 SDValue V4 = Op.getOperand(3);
6851 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6852 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6854 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6857 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6858 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6859 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6860 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6861 Op.getNumOperands() == 4)));
6863 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6864 // from two other 128-bit ones.
6866 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6867 return LowerAVXCONCAT_VECTORS(Op, DAG);
6871 //===----------------------------------------------------------------------===//
6872 // Vector shuffle lowering
6874 // This is an experimental code path for lowering vector shuffles on x86. It is
6875 // designed to handle arbitrary vector shuffles and blends, gracefully
6876 // degrading performance as necessary. It works hard to recognize idiomatic
6877 // shuffles and lower them to optimal instruction patterns without leaving
6878 // a framework that allows reasonably efficient handling of all vector shuffle
6880 //===----------------------------------------------------------------------===//
6882 /// \brief Tiny helper function to identify a no-op mask.
6884 /// This is a somewhat boring predicate function. It checks whether the mask
6885 /// array input, which is assumed to be a single-input shuffle mask of the kind
6886 /// used by the X86 shuffle instructions (not a fully general
6887 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6888 /// in-place shuffle are 'no-op's.
6889 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6890 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6891 if (Mask[i] != -1 && Mask[i] != i)
6896 /// \brief Helper function to classify a mask as a single-input mask.
6898 /// This isn't a generic single-input test because in the vector shuffle
6899 /// lowering we canonicalize single inputs to be the first input operand. This
6900 /// means we can more quickly test for a single input by only checking whether
6901 /// an input from the second operand exists. We also assume that the size of
6902 /// mask corresponds to the size of the input vectors which isn't true in the
6903 /// fully general case.
6904 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6906 if (M >= (int)Mask.size())
6911 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6913 /// This helper function produces an 8-bit shuffle immediate corresponding to
6914 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6915 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6918 /// NB: We rely heavily on "undef" masks preserving the input lane.
6919 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6920 SelectionDAG &DAG) {
6921 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6922 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6923 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6924 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6925 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6928 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6929 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6930 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6931 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6932 return DAG.getConstant(Imm, MVT::i8);
6935 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6937 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6938 /// support for floating point shuffles but not integer shuffles. These
6939 /// instructions will incur a domain crossing penalty on some chips though so
6940 /// it is better to avoid lowering through this for integer vectors where
6942 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6943 const X86Subtarget *Subtarget,
6944 SelectionDAG &DAG) {
6946 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6947 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6948 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6949 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6950 ArrayRef<int> Mask = SVOp->getMask();
6951 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6953 if (isSingleInputShuffleMask(Mask)) {
6954 // Straight shuffle of a single input vector. Simulate this by using the
6955 // single input as both of the "inputs" to this instruction..
6956 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6957 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6958 DAG.getConstant(SHUFPDMask, MVT::i8));
6960 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6961 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6963 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6964 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6965 DAG.getConstant(SHUFPDMask, MVT::i8));
6968 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
6970 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
6971 /// the integer unit to minimize domain crossing penalties. However, for blends
6972 /// it falls back to the floating point shuffle operation with appropriate bit
6974 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6975 const X86Subtarget *Subtarget,
6976 SelectionDAG &DAG) {
6978 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
6979 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6980 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6981 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6982 ArrayRef<int> Mask = SVOp->getMask();
6983 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6985 if (isSingleInputShuffleMask(Mask)) {
6986 // Straight shuffle of a single input vector. For everything from SSE2
6987 // onward this has a single fast instruction with no scary immediates.
6988 // We have to map the mask as it is actually a v4i32 shuffle instruction.
6989 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
6990 int WidenedMask[4] = {
6991 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
6992 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
6994 ISD::BITCAST, DL, MVT::v2i64,
6995 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
6996 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
6999 // We implement this with SHUFPD which is pretty lame because it will likely
7000 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7001 // However, all the alternatives are still more cycles and newer chips don't
7002 // have this problem. It would be really nice if x86 had better shuffles here.
7003 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7004 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7005 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7006 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7009 /// \brief Lower 4-lane 32-bit floating point shuffles.
7011 /// Uses instructions exclusively from the floating point unit to minimize
7012 /// domain crossing penalties, as these are sufficient to implement all v4f32
7014 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7015 const X86Subtarget *Subtarget,
7016 SelectionDAG &DAG) {
7018 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7019 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7020 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7021 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7022 ArrayRef<int> Mask = SVOp->getMask();
7023 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7025 SDValue LowV = V1, HighV = V2;
7026 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7029 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7031 if (NumV2Elements == 0)
7032 // Straight shuffle of a single input vector. We pass the input vector to
7033 // both operands to simulate this with a SHUFPS.
7034 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7035 getV4X86ShuffleImm8ForMask(Mask, DAG));
7037 if (NumV2Elements == 1) {
7039 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7041 // Compute the index adjacent to V2Index and in the same half by toggling
7043 int V2AdjIndex = V2Index ^ 1;
7045 if (Mask[V2AdjIndex] == -1) {
7046 // Handles all the cases where we have a single V2 element and an undef.
7047 // This will only ever happen in the high lanes because we commute the
7048 // vector otherwise.
7050 std::swap(LowV, HighV);
7051 NewMask[V2Index] -= 4;
7053 // Handle the case where the V2 element ends up adjacent to a V1 element.
7054 // To make this work, blend them together as the first step.
7055 int V1Index = V2AdjIndex;
7056 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7057 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7058 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7060 // Now proceed to reconstruct the final blend as we have the necessary
7061 // high or low half formed.
7068 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7069 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7071 } else if (NumV2Elements == 2) {
7072 if (Mask[0] < 4 && Mask[1] < 4) {
7073 // Handle the easy case where we have V1 in the low lanes and V2 in the
7074 // high lanes. We never see this reversed because we sort the shuffle.
7078 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7079 // trying to place elements directly, just blend them and set up the final
7080 // shuffle to place them.
7082 // The first two blend mask elements are for V1, the second two are for
7084 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7085 Mask[2] < 4 ? Mask[2] : Mask[3],
7086 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7087 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7088 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7089 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7091 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7094 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7095 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7096 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7097 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7100 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7101 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7104 /// \brief Lower 4-lane i32 vector shuffles.
7106 /// We try to handle these with integer-domain shuffles where we can, but for
7107 /// blends we use the floating point domain blend instructions.
7108 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7109 const X86Subtarget *Subtarget,
7110 SelectionDAG &DAG) {
7112 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7113 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7114 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7115 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7116 ArrayRef<int> Mask = SVOp->getMask();
7117 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7119 if (isSingleInputShuffleMask(Mask))
7120 // Straight shuffle of a single input vector. For everything from SSE2
7121 // onward this has a single fast instruction with no scary immediates.
7122 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7123 getV4X86ShuffleImm8ForMask(Mask, DAG));
7125 // We implement this with SHUFPS because it can blend from two vectors.
7126 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7127 // up the inputs, bypassing domain shift penalties that we would encur if we
7128 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7130 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7131 DAG.getVectorShuffle(
7133 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7134 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7137 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7138 /// shuffle lowering, and the most complex part.
7140 /// The lowering strategy is to try to form pairs of input lanes which are
7141 /// targeted at the same half of the final vector, and then use a dword shuffle
7142 /// to place them onto the right half, and finally unpack the paired lanes into
7143 /// their final position.
7145 /// The exact breakdown of how to form these dword pairs and align them on the
7146 /// correct sides is really tricky. See the comments within the function for
7147 /// more of the details.
7148 static SDValue lowerV8I16SingleInputVectorShuffle(
7149 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7150 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7151 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7152 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7153 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7155 SmallVector<int, 4> LoInputs;
7156 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7157 [](int M) { return M >= 0; });
7158 std::sort(LoInputs.begin(), LoInputs.end());
7159 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7160 SmallVector<int, 4> HiInputs;
7161 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7162 [](int M) { return M >= 0; });
7163 std::sort(HiInputs.begin(), HiInputs.end());
7164 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7166 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7167 int NumHToL = LoInputs.size() - NumLToL;
7169 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7170 int NumHToH = HiInputs.size() - NumLToH;
7171 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7172 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7173 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7174 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7176 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7177 // such inputs we can swap two of the dwords across the half mark and end up
7178 // with <=2 inputs to each half in each half. Once there, we can fall through
7179 // to the generic code below. For example:
7181 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7182 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7184 // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7186 auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7187 int ThreeInputHalfSum, int OneInputHalfOffset) {
7188 // Compute the index of dword with only one word among the three inputs in
7189 // a half by taking the sum of the half with three inputs and subtracting
7190 // the sum of the actual three inputs. The difference is the remaining
7192 int DWordA = (ThreeInputHalfSum -
7193 std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7195 int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7197 int PSHUFDMask[] = {0, 1, 2, 3};
7198 PSHUFDMask[DWordA] = DWordB;
7199 PSHUFDMask[DWordB] = DWordA;
7200 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7201 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7202 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7203 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7205 // Adjust the mask to match the new locations of A and B.
7207 if (M != -1 && M/2 == DWordA)
7208 M = 2 * DWordB + M % 2;
7209 else if (M != -1 && M/2 == DWordB)
7210 M = 2 * DWordA + M % 2;
7212 // Recurse back into this routine to re-compute state now that this isn't
7213 // a 3 and 1 problem.
7214 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7217 if (NumLToL == 3 && NumHToL == 1)
7218 return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7219 else if (NumLToL == 1 && NumHToL == 3)
7220 return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7221 else if (NumLToH == 1 && NumHToH == 3)
7222 return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7223 else if (NumLToH == 3 && NumHToH == 1)
7224 return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7226 // At this point there are at most two inputs to the low and high halves from
7227 // each half. That means the inputs can always be grouped into dwords and
7228 // those dwords can then be moved to the correct half with a dword shuffle.
7229 // We use at most one low and one high word shuffle to collect these paired
7230 // inputs into dwords, and finally a dword shuffle to place them.
7231 int PSHUFLMask[4] = {-1, -1, -1, -1};
7232 int PSHUFHMask[4] = {-1, -1, -1, -1};
7233 int PSHUFDMask[4] = {-1, -1, -1, -1};
7235 // First fix the masks for all the inputs that are staying in their
7236 // original halves. This will then dictate the targets of the cross-half
7238 auto fixInPlaceInputs = [&PSHUFDMask](
7239 ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7240 MutableArrayRef<int> HalfMask, int HalfOffset) {
7241 if (InPlaceInputs.empty())
7243 if (InPlaceInputs.size() == 1) {
7244 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7245 InPlaceInputs[0] - HalfOffset;
7246 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7250 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7251 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7252 InPlaceInputs[0] - HalfOffset;
7253 // Put the second input next to the first so that they are packed into
7254 // a dword. We find the adjacent index by toggling the low bit.
7255 int AdjIndex = InPlaceInputs[0] ^ 1;
7256 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7257 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7258 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7260 if (!HToLInputs.empty())
7261 fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7262 if (!LToHInputs.empty())
7263 fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7265 // Now gather the cross-half inputs and place them into a free dword of
7266 // their target half.
7267 // FIXME: This operation could almost certainly be simplified dramatically to
7268 // look more like the 3-1 fixing operation.
7269 auto moveInputsToRightHalf = [&PSHUFDMask](
7270 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7271 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7272 int SourceOffset, int DestOffset) {
7273 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7274 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7276 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7278 int LowWord = Word & ~1;
7279 int HighWord = Word | 1;
7280 return isWordClobbered(SourceHalfMask, LowWord) ||
7281 isWordClobbered(SourceHalfMask, HighWord);
7284 if (IncomingInputs.empty())
7287 if (ExistingInputs.empty()) {
7288 // Map any dwords with inputs from them into the right half.
7289 for (int Input : IncomingInputs) {
7290 // If the source half mask maps over the inputs, turn those into
7291 // swaps and use the swapped lane.
7292 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7293 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7294 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7295 Input - SourceOffset;
7296 // We have to swap the uses in our half mask in one sweep.
7297 for (int &M : HalfMask)
7298 if (M == SourceHalfMask[Input - SourceOffset])
7300 else if (M == Input)
7301 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7303 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7304 Input - SourceOffset &&
7305 "Previous placement doesn't match!");
7307 // Note that this correctly re-maps both when we do a swap and when
7308 // we observe the other side of the swap above. We rely on that to
7309 // avoid swapping the members of the input list directly.
7310 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7313 // Map the input's dword into the correct half.
7314 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7315 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7317 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7319 "Previous placement doesn't match!");
7322 // And just directly shift any other-half mask elements to be same-half
7323 // as we will have mirrored the dword containing the element into the
7324 // same position within that half.
7325 for (int &M : HalfMask)
7326 if (M >= SourceOffset && M < SourceOffset + 4) {
7327 M = M - SourceOffset + DestOffset;
7328 assert(M >= 0 && "This should never wrap below zero!");
7333 // Ensure we have the input in a viable dword of its current half. This
7334 // is particularly tricky because the original position may be clobbered
7335 // by inputs being moved and *staying* in that half.
7336 if (IncomingInputs.size() == 1) {
7337 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7338 int InputFixed = std::find(std::begin(SourceHalfMask),
7339 std::end(SourceHalfMask), -1) -
7340 std::begin(SourceHalfMask) + SourceOffset;
7341 SourceHalfMask[InputFixed - SourceOffset] =
7342 IncomingInputs[0] - SourceOffset;
7343 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7345 IncomingInputs[0] = InputFixed;
7347 } else if (IncomingInputs.size() == 2) {
7348 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7349 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7350 int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7351 assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7352 "Not all dwords can be clobbered!");
7353 SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7354 SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7355 for (int &M : HalfMask)
7356 if (M == IncomingInputs[0])
7357 M = SourceDWordBase + SourceOffset;
7358 else if (M == IncomingInputs[1])
7359 M = SourceDWordBase + 1 + SourceOffset;
7360 IncomingInputs[0] = SourceDWordBase + SourceOffset;
7361 IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7364 llvm_unreachable("Unhandled input size!");
7367 // Now hoist the DWord down to the right half.
7368 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7369 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7370 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7371 for (int Input : IncomingInputs)
7372 std::replace(HalfMask.begin(), HalfMask.end(), Input,
7373 FreeDWord * 2 + Input % 2);
7375 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7376 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7377 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7378 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7380 // Now enact all the shuffles we've computed to move the inputs into their
7382 if (!isNoopShuffleMask(PSHUFLMask))
7383 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7384 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7385 if (!isNoopShuffleMask(PSHUFHMask))
7386 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7387 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7388 if (!isNoopShuffleMask(PSHUFDMask))
7389 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7390 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7391 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7392 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7394 // At this point, each half should contain all its inputs, and we can then
7395 // just shuffle them into their final position.
7396 assert(std::count_if(LoMask.begin(), LoMask.end(),
7397 [](int M) { return M >= 4; }) == 0 &&
7398 "Failed to lift all the high half inputs to the low mask!");
7399 assert(std::count_if(HiMask.begin(), HiMask.end(),
7400 [](int M) { return M >= 0 && M < 4; }) == 0 &&
7401 "Failed to lift all the low half inputs to the high mask!");
7403 // Do a half shuffle for the low mask.
7404 if (!isNoopShuffleMask(LoMask))
7405 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7406 getV4X86ShuffleImm8ForMask(LoMask, DAG));
7408 // Do a half shuffle with the high mask after shifting its values down.
7409 for (int &M : HiMask)
7412 if (!isNoopShuffleMask(HiMask))
7413 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7414 getV4X86ShuffleImm8ForMask(HiMask, DAG));
7419 /// \brief Detect whether the mask pattern should be lowered through
7422 /// This essentially tests whether viewing the mask as an interleaving of two
7423 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7424 /// lowering it through interleaving is a significantly better strategy.
7425 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7426 int NumEvenInputs[2] = {0, 0};
7427 int NumOddInputs[2] = {0, 0};
7428 int NumLoInputs[2] = {0, 0};
7429 int NumHiInputs[2] = {0, 0};
7430 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7434 int InputIdx = Mask[i] >= Size;
7437 ++NumLoInputs[InputIdx];
7439 ++NumHiInputs[InputIdx];
7442 ++NumEvenInputs[InputIdx];
7444 ++NumOddInputs[InputIdx];
7447 // The minimum number of cross-input results for both the interleaved and
7448 // split cases. If interleaving results in fewer cross-input results, return
7450 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7451 NumEvenInputs[0] + NumOddInputs[1]);
7452 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7453 NumLoInputs[0] + NumHiInputs[1]);
7454 return InterleavedCrosses < SplitCrosses;
7457 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7459 /// This strategy only works when the inputs from each vector fit into a single
7460 /// half of that vector, and generally there are not so many inputs as to leave
7461 /// the in-place shuffles required highly constrained (and thus expensive). It
7462 /// shifts all the inputs into a single side of both input vectors and then
7463 /// uses an unpack to interleave these inputs in a single vector. At that
7464 /// point, we will fall back on the generic single input shuffle lowering.
7465 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7467 MutableArrayRef<int> Mask,
7468 const X86Subtarget *Subtarget,
7469 SelectionDAG &DAG) {
7470 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7471 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7472 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7473 for (int i = 0; i < 8; ++i)
7474 if (Mask[i] >= 0 && Mask[i] < 4)
7475 LoV1Inputs.push_back(i);
7476 else if (Mask[i] >= 4 && Mask[i] < 8)
7477 HiV1Inputs.push_back(i);
7478 else if (Mask[i] >= 8 && Mask[i] < 12)
7479 LoV2Inputs.push_back(i);
7480 else if (Mask[i] >= 12)
7481 HiV2Inputs.push_back(i);
7483 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7484 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7487 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7488 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7489 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7491 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7492 HiV1Inputs.size() + HiV2Inputs.size();
7494 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7495 ArrayRef<int> HiInputs, bool MoveToLo,
7497 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7498 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7499 if (BadInputs.empty())
7502 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7503 int MoveOffset = MoveToLo ? 0 : 4;
7505 if (GoodInputs.empty()) {
7506 for (int BadInput : BadInputs) {
7507 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7508 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7511 if (GoodInputs.size() == 2) {
7512 // If the low inputs are spread across two dwords, pack them into
7514 MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7515 Mask[GoodInputs[0]] - MaskOffset;
7516 MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7517 Mask[GoodInputs[1]] - MaskOffset;
7518 Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7519 Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7521 // Otherwise pin the low inputs.
7522 for (int GoodInput : GoodInputs)
7523 MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7527 std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7528 std::begin(MoveMask);
7529 assert(MoveMaskIdx >= MoveOffset && "Established above");
7531 if (BadInputs.size() == 2) {
7532 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7533 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7534 MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7535 Mask[BadInputs[0]] - MaskOffset;
7536 MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7537 Mask[BadInputs[1]] - MaskOffset;
7538 Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7539 Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7541 assert(BadInputs.size() == 1 && "All sizes handled");
7542 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7543 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7547 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7550 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7552 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7555 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7556 // cross-half traffic in the final shuffle.
7558 // Munge the mask to be a single-input mask after the unpack merges the
7562 M = 2 * (M % 4) + (M / 8);
7564 return DAG.getVectorShuffle(
7565 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7566 DL, MVT::v8i16, V1, V2),
7567 DAG.getUNDEF(MVT::v8i16), Mask);
7570 /// \brief Generic lowering of 8-lane i16 shuffles.
7572 /// This handles both single-input shuffles and combined shuffle/blends with
7573 /// two inputs. The single input shuffles are immediately delegated to
7574 /// a dedicated lowering routine.
7576 /// The blends are lowered in one of three fundamental ways. If there are few
7577 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7578 /// of the input is significantly cheaper when lowered as an interleaving of
7579 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7580 /// halves of the inputs separately (making them have relatively few inputs)
7581 /// and then concatenate them.
7582 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7583 const X86Subtarget *Subtarget,
7584 SelectionDAG &DAG) {
7586 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7587 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7588 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7589 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7590 ArrayRef<int> OrigMask = SVOp->getMask();
7591 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7592 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7593 MutableArrayRef<int> Mask(MaskStorage);
7595 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7597 auto isV1 = [](int M) { return M >= 0 && M < 8; };
7598 auto isV2 = [](int M) { return M >= 8; };
7600 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7601 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7603 if (NumV2Inputs == 0)
7604 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7606 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7607 "to be V1-input shuffles.");
7609 if (NumV1Inputs + NumV2Inputs <= 4)
7610 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7612 // Check whether an interleaving lowering is likely to be more efficient.
7613 // This isn't perfect but it is a strong heuristic that tends to work well on
7614 // the kinds of shuffles that show up in practice.
7616 // FIXME: Handle 1x, 2x, and 4x interleaving.
7617 if (shouldLowerAsInterleaving(Mask)) {
7618 // FIXME: Figure out whether we should pack these into the low or high
7621 int EMask[8], OMask[8];
7622 for (int i = 0; i < 4; ++i) {
7623 EMask[i] = Mask[2*i];
7624 OMask[i] = Mask[2*i + 1];
7629 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7630 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7632 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7635 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7636 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7638 for (int i = 0; i < 4; ++i) {
7639 LoBlendMask[i] = Mask[i];
7640 HiBlendMask[i] = Mask[i + 4];
7643 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7644 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7645 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7646 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7648 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7649 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7652 /// \brief Generic lowering of v16i8 shuffles.
7654 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7655 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7656 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7657 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7659 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7660 const X86Subtarget *Subtarget,
7661 SelectionDAG &DAG) {
7663 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7664 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7665 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7666 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7667 ArrayRef<int> OrigMask = SVOp->getMask();
7668 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7669 int MaskStorage[16] = {
7670 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7671 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
7672 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
7673 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7674 MutableArrayRef<int> Mask(MaskStorage);
7675 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7676 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7678 // For single-input shuffles, there are some nicer lowering tricks we can use.
7679 if (isSingleInputShuffleMask(Mask)) {
7680 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7681 // Notably, this handles splat and partial-splat shuffles more efficiently.
7683 // FIXME: We should check for other patterns which can be widened into an
7684 // i16 shuffle as well.
7685 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7686 for (int i = 0; i < 16; i += 2) {
7687 if (Mask[i] != Mask[i + 1])
7692 if (canWidenViaDuplication(Mask)) {
7693 SmallVector<int, 4> LoInputs;
7694 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7695 [](int M) { return M >= 0 && M < 8; });
7696 std::sort(LoInputs.begin(), LoInputs.end());
7697 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7699 SmallVector<int, 4> HiInputs;
7700 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7701 [](int M) { return M >= 8; });
7702 std::sort(HiInputs.begin(), HiInputs.end());
7703 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7706 bool TargetLo = LoInputs.size() >= HiInputs.size();
7707 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7708 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7711 SmallDenseMap<int, int, 8> LaneMap;
7712 for (int i = 0; i < 16; ++i)
7714 for (int I : InPlaceInputs) {
7718 int FreeByteIdx = 0;
7719 int TargetOffset = TargetLo ? 0 : 8;
7720 for (int I : MovingInputs) {
7721 // Walk the free index into the byte mask until we find an unoccupied
7722 // spot. We bound this to 8 steps to catch bugs, the pigeonhole
7723 // principle indicates that there *must* be a spot as we can only have
7724 // 8 duplicated inputs. We have to walk the index using modular
7725 // arithmetic to wrap around as necessary.
7726 // FIXME: We could do a much better job of picking an inexpensive slot
7727 // so this doesn't go through the worst case for the byte shuffle.
7728 for (int j = 0; j < 8 && ByteMask[FreeByteIdx + TargetOffset] != -1;
7729 ++j, FreeByteIdx = (FreeByteIdx + 1) % 8)
7731 assert(ByteMask[FreeByteIdx + TargetOffset] == -1 &&
7732 "Failed to find a free byte!");
7733 ByteMask[FreeByteIdx + TargetOffset] = I;
7734 LaneMap[I] = FreeByteIdx + TargetOffset;
7736 V1 = DAG.getVectorShuffle(MVT::v16i8, DL, V1, DAG.getUNDEF(MVT::v16i8),
7742 // Unpack the bytes to form the i16s that will be shuffled into place.
7743 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7744 MVT::v16i8, V1, V1);
7746 int I16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7747 for (int i = 0; i < 16; i += 2) {
7749 I16Shuffle[i / 2] = Mask[i] - (TargetLo ? 0 : 8);
7750 assert(I16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7752 return DAG.getVectorShuffle(MVT::v8i16, DL,
7753 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7754 DAG.getUNDEF(MVT::v8i16), I16Shuffle);
7758 // Check whether an interleaving lowering is likely to be more efficient.
7759 // This isn't perfect but it is a strong heuristic that tends to work well on
7760 // the kinds of shuffles that show up in practice.
7762 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7763 if (shouldLowerAsInterleaving(Mask)) {
7764 // FIXME: Figure out whether we should pack these into the low or high
7767 int EMask[16], OMask[16];
7768 for (int i = 0; i < 8; ++i) {
7769 EMask[i] = Mask[2*i];
7770 OMask[i] = Mask[2*i + 1];
7775 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7776 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7778 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7780 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7782 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7783 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, Zero));
7785 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7786 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, Zero));
7788 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7789 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V2, Zero));
7791 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7792 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V2, Zero));
7794 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7795 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7796 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7797 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7799 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7800 MutableArrayRef<int> V1HalfBlendMask,
7801 MutableArrayRef<int> V2HalfBlendMask) {
7802 for (int i = 0; i < 8; ++i)
7803 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7804 V1HalfBlendMask[i] = HalfMask[i];
7806 } else if (HalfMask[i] >= 16) {
7807 V2HalfBlendMask[i] = HalfMask[i] - 16;
7808 HalfMask[i] = i + 8;
7811 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7812 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7814 SDValue V1Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1LoBlendMask);
7815 SDValue V2Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2LoBlendMask);
7816 SDValue V1Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1HiBlendMask);
7817 SDValue V2Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2HiBlendMask);
7819 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7820 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7822 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7825 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7827 /// This routine breaks down the specific type of 128-bit shuffle and
7828 /// dispatches to the lowering routines accordingly.
7829 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7830 MVT VT, const X86Subtarget *Subtarget,
7831 SelectionDAG &DAG) {
7832 switch (VT.SimpleTy) {
7834 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7836 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7838 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7840 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7842 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7844 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7847 llvm_unreachable("Unimplemented!");
7851 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7852 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7853 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7854 if (Mask[i] + 1 != Mask[i+1])
7860 /// \brief Top-level lowering for x86 vector shuffles.
7862 /// This handles decomposition, canonicalization, and lowering of all x86
7863 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7864 /// above in helper routines. The canonicalization attempts to widen shuffles
7865 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7866 /// s.t. only one of the two inputs needs to be tested, etc.
7867 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7868 SelectionDAG &DAG) {
7869 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7870 ArrayRef<int> Mask = SVOp->getMask();
7871 SDValue V1 = Op.getOperand(0);
7872 SDValue V2 = Op.getOperand(1);
7873 MVT VT = Op.getSimpleValueType();
7874 int NumElements = VT.getVectorNumElements();
7877 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7879 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7880 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7881 if (V1IsUndef && V2IsUndef)
7882 return DAG.getUNDEF(VT);
7884 // When we create a shuffle node we put the UNDEF node to second operand,
7885 // but in some cases the first operand may be transformed to UNDEF.
7886 // In this case we should just commute the node.
7888 return CommuteVectorShuffle(SVOp, DAG);
7890 // Check for non-undef masks pointing at an undef vector and make the masks
7891 // undef as well. This makes it easier to match the shuffle based solely on
7895 if (M >= NumElements) {
7896 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7897 for (int &M : NewMask)
7898 if (M >= NumElements)
7900 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7903 // For integer vector shuffles, try to collapse them into a shuffle of fewer
7904 // lanes but wider integers. We cap this to not form integers larger than i64
7905 // but it might be interesting to form i128 integers to handle flipping the
7906 // low and high halves of AVX 256-bit vectors.
7907 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7908 areAdjacentMasksSequential(Mask)) {
7909 SmallVector<int, 8> NewMask;
7910 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7911 NewMask.push_back(Mask[i] / 2);
7913 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7914 VT.getVectorNumElements() / 2);
7915 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7916 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7917 return DAG.getNode(ISD::BITCAST, dl, VT,
7918 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7921 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7922 for (int M : SVOp->getMask())
7925 else if (M < NumElements)
7930 // Commute the shuffle as needed such that more elements come from V1 than
7931 // V2. This allows us to match the shuffle pattern strictly on how many
7932 // elements come from V1 without handling the symmetric cases.
7933 if (NumV2Elements > NumV1Elements)
7934 return CommuteVectorShuffle(SVOp, DAG);
7936 // When the number of V1 and V2 elements are the same, try to minimize the
7937 // number of uses of V2 in the low half of the vector.
7938 if (NumV1Elements == NumV2Elements) {
7939 int LowV1Elements = 0, LowV2Elements = 0;
7940 for (int M : SVOp->getMask().slice(0, NumElements / 2))
7941 if (M >= NumElements)
7945 if (LowV2Elements > LowV1Elements)
7946 return CommuteVectorShuffle(SVOp, DAG);
7949 // For each vector width, delegate to a specialized lowering routine.
7950 if (VT.getSizeInBits() == 128)
7951 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
7953 llvm_unreachable("Unimplemented!");
7957 //===----------------------------------------------------------------------===//
7958 // Legacy vector shuffle lowering
7960 // This code is the legacy code handling vector shuffles until the above
7961 // replaces its functionality and performance.
7962 //===----------------------------------------------------------------------===//
7964 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
7965 bool hasInt256, unsigned *MaskOut = nullptr) {
7966 MVT EltVT = VT.getVectorElementType();
7968 // There is no blend with immediate in AVX-512.
7969 if (VT.is512BitVector())
7972 if (!hasSSE41 || EltVT == MVT::i8)
7974 if (!hasInt256 && VT == MVT::v16i16)
7977 unsigned MaskValue = 0;
7978 unsigned NumElems = VT.getVectorNumElements();
7979 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
7980 unsigned NumLanes = (NumElems - 1) / 8 + 1;
7981 unsigned NumElemsInLane = NumElems / NumLanes;
7983 // Blend for v16i16 should be symetric for the both lanes.
7984 for (unsigned i = 0; i < NumElemsInLane; ++i) {
7986 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
7987 int EltIdx = MaskVals[i];
7989 if ((EltIdx < 0 || EltIdx == (int)i) &&
7990 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
7993 if (((unsigned)EltIdx == (i + NumElems)) &&
7994 (SndLaneEltIdx < 0 ||
7995 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
7996 MaskValue |= (1 << i);
8002 *MaskOut = MaskValue;
8006 // Try to lower a shuffle node into a simple blend instruction.
8007 // This function assumes isBlendMask returns true for this
8008 // SuffleVectorSDNode
8009 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8011 const X86Subtarget *Subtarget,
8012 SelectionDAG &DAG) {
8013 MVT VT = SVOp->getSimpleValueType(0);
8014 MVT EltVT = VT.getVectorElementType();
8015 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8016 Subtarget->hasInt256() && "Trying to lower a "
8017 "VECTOR_SHUFFLE to a Blend but "
8018 "with the wrong mask"));
8019 SDValue V1 = SVOp->getOperand(0);
8020 SDValue V2 = SVOp->getOperand(1);
8022 unsigned NumElems = VT.getVectorNumElements();
8024 // Convert i32 vectors to floating point if it is not AVX2.
8025 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8027 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8028 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8030 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8031 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8034 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8035 DAG.getConstant(MaskValue, MVT::i32));
8036 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8039 /// In vector type \p VT, return true if the element at index \p InputIdx
8040 /// falls on a different 128-bit lane than \p OutputIdx.
8041 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8042 unsigned OutputIdx) {
8043 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8044 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8047 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
8048 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
8049 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
8050 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8052 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8053 SelectionDAG &DAG) {
8054 MVT VT = V1.getSimpleValueType();
8055 assert(VT.is128BitVector() || VT.is256BitVector());
8057 MVT EltVT = VT.getVectorElementType();
8058 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8059 unsigned NumElts = VT.getVectorNumElements();
8061 SmallVector<SDValue, 32> PshufbMask;
8062 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8063 int InputIdx = MaskVals[OutputIdx];
8064 unsigned InputByteIdx;
8066 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8067 InputByteIdx = 0x80;
8069 // Cross lane is not allowed.
8070 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8072 InputByteIdx = InputIdx * EltSizeInBytes;
8073 // Index is an byte offset within the 128-bit lane.
8074 InputByteIdx &= 0xf;
8077 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8078 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8079 if (InputByteIdx != 0x80)
8084 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8086 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8087 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8088 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8091 // v8i16 shuffles - Prefer shuffles in the following order:
8092 // 1. [all] pshuflw, pshufhw, optional move
8093 // 2. [ssse3] 1 x pshufb
8094 // 3. [ssse3] 2 x pshufb + 1 x por
8095 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8097 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8098 SelectionDAG &DAG) {
8099 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8100 SDValue V1 = SVOp->getOperand(0);
8101 SDValue V2 = SVOp->getOperand(1);
8103 SmallVector<int, 8> MaskVals;
8105 // Determine if more than 1 of the words in each of the low and high quadwords
8106 // of the result come from the same quadword of one of the two inputs. Undef
8107 // mask values count as coming from any quadword, for better codegen.
8109 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8110 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8111 unsigned LoQuad[] = { 0, 0, 0, 0 };
8112 unsigned HiQuad[] = { 0, 0, 0, 0 };
8113 // Indices of quads used.
8114 std::bitset<4> InputQuads;
8115 for (unsigned i = 0; i < 8; ++i) {
8116 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8117 int EltIdx = SVOp->getMaskElt(i);
8118 MaskVals.push_back(EltIdx);
8127 InputQuads.set(EltIdx / 4);
8130 int BestLoQuad = -1;
8131 unsigned MaxQuad = 1;
8132 for (unsigned i = 0; i < 4; ++i) {
8133 if (LoQuad[i] > MaxQuad) {
8135 MaxQuad = LoQuad[i];
8139 int BestHiQuad = -1;
8141 for (unsigned i = 0; i < 4; ++i) {
8142 if (HiQuad[i] > MaxQuad) {
8144 MaxQuad = HiQuad[i];
8148 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8149 // of the two input vectors, shuffle them into one input vector so only a
8150 // single pshufb instruction is necessary. If there are more than 2 input
8151 // quads, disable the next transformation since it does not help SSSE3.
8152 bool V1Used = InputQuads[0] || InputQuads[1];
8153 bool V2Used = InputQuads[2] || InputQuads[3];
8154 if (Subtarget->hasSSSE3()) {
8155 if (InputQuads.count() == 2 && V1Used && V2Used) {
8156 BestLoQuad = InputQuads[0] ? 0 : 1;
8157 BestHiQuad = InputQuads[2] ? 2 : 3;
8159 if (InputQuads.count() > 2) {
8165 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8166 // the shuffle mask. If a quad is scored as -1, that means that it contains
8167 // words from all 4 input quadwords.
8169 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8171 BestLoQuad < 0 ? 0 : BestLoQuad,
8172 BestHiQuad < 0 ? 1 : BestHiQuad
8174 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8175 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8176 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8177 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8179 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8180 // source words for the shuffle, to aid later transformations.
8181 bool AllWordsInNewV = true;
8182 bool InOrder[2] = { true, true };
8183 for (unsigned i = 0; i != 8; ++i) {
8184 int idx = MaskVals[i];
8186 InOrder[i/4] = false;
8187 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8189 AllWordsInNewV = false;
8193 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8194 if (AllWordsInNewV) {
8195 for (int i = 0; i != 8; ++i) {
8196 int idx = MaskVals[i];
8199 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8200 if ((idx != i) && idx < 4)
8202 if ((idx != i) && idx > 3)
8211 // If we've eliminated the use of V2, and the new mask is a pshuflw or
8212 // pshufhw, that's as cheap as it gets. Return the new shuffle.
8213 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8214 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8215 unsigned TargetMask = 0;
8216 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8217 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8218 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8219 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8220 getShufflePSHUFLWImmediate(SVOp);
8221 V1 = NewV.getOperand(0);
8222 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8226 // Promote splats to a larger type which usually leads to more efficient code.
8227 // FIXME: Is this true if pshufb is available?
8228 if (SVOp->isSplat())
8229 return PromoteSplat(SVOp, DAG);
8231 // If we have SSSE3, and all words of the result are from 1 input vector,
8232 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
8233 // is present, fall back to case 4.
8234 if (Subtarget->hasSSSE3()) {
8235 SmallVector<SDValue,16> pshufbMask;
8237 // If we have elements from both input vectors, set the high bit of the
8238 // shuffle mask element to zero out elements that come from V2 in the V1
8239 // mask, and elements that come from V1 in the V2 mask, so that the two
8240 // results can be OR'd together.
8241 bool TwoInputs = V1Used && V2Used;
8242 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8244 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8246 // Calculate the shuffle mask for the second input, shuffle it, and
8247 // OR it with the first shuffled input.
8248 CommuteVectorShuffleMask(MaskVals, 8);
8249 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8250 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8251 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8254 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8255 // and update MaskVals with new element order.
8256 std::bitset<8> InOrder;
8257 if (BestLoQuad >= 0) {
8258 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8259 for (int i = 0; i != 4; ++i) {
8260 int idx = MaskVals[i];
8263 } else if ((idx / 4) == BestLoQuad) {
8268 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8271 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8272 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8273 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8275 getShufflePSHUFLWImmediate(SVOp), DAG);
8279 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8280 // and update MaskVals with the new element order.
8281 if (BestHiQuad >= 0) {
8282 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8283 for (unsigned i = 4; i != 8; ++i) {
8284 int idx = MaskVals[i];
8287 } else if ((idx / 4) == BestHiQuad) {
8288 MaskV[i] = (idx & 3) + 4;
8292 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8295 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8296 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8297 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8299 getShufflePSHUFHWImmediate(SVOp), DAG);
8303 // In case BestHi & BestLo were both -1, which means each quadword has a word
8304 // from each of the four input quadwords, calculate the InOrder bitvector now
8305 // before falling through to the insert/extract cleanup.
8306 if (BestLoQuad == -1 && BestHiQuad == -1) {
8308 for (int i = 0; i != 8; ++i)
8309 if (MaskVals[i] < 0 || MaskVals[i] == i)
8313 // The other elements are put in the right place using pextrw and pinsrw.
8314 for (unsigned i = 0; i != 8; ++i) {
8317 int EltIdx = MaskVals[i];
8320 SDValue ExtOp = (EltIdx < 8) ?
8321 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8322 DAG.getIntPtrConstant(EltIdx)) :
8323 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8324 DAG.getIntPtrConstant(EltIdx - 8));
8325 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8326 DAG.getIntPtrConstant(i));
8331 /// \brief v16i16 shuffles
8333 /// FIXME: We only support generation of a single pshufb currently. We can
8334 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8335 /// well (e.g 2 x pshufb + 1 x por).
8337 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8338 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8339 SDValue V1 = SVOp->getOperand(0);
8340 SDValue V2 = SVOp->getOperand(1);
8343 if (V2.getOpcode() != ISD::UNDEF)
8346 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8347 return getPSHUFB(MaskVals, V1, dl, DAG);
8350 // v16i8 shuffles - Prefer shuffles in the following order:
8351 // 1. [ssse3] 1 x pshufb
8352 // 2. [ssse3] 2 x pshufb + 1 x por
8353 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
8354 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8355 const X86Subtarget* Subtarget,
8356 SelectionDAG &DAG) {
8357 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8358 SDValue V1 = SVOp->getOperand(0);
8359 SDValue V2 = SVOp->getOperand(1);
8361 ArrayRef<int> MaskVals = SVOp->getMask();
8363 // Promote splats to a larger type which usually leads to more efficient code.
8364 // FIXME: Is this true if pshufb is available?
8365 if (SVOp->isSplat())
8366 return PromoteSplat(SVOp, DAG);
8368 // If we have SSSE3, case 1 is generated when all result bytes come from
8369 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
8370 // present, fall back to case 3.
8372 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8373 if (Subtarget->hasSSSE3()) {
8374 SmallVector<SDValue,16> pshufbMask;
8376 // If all result elements are from one input vector, then only translate
8377 // undef mask values to 0x80 (zero out result) in the pshufb mask.
8379 // Otherwise, we have elements from both input vectors, and must zero out
8380 // elements that come from V2 in the first mask, and V1 in the second mask
8381 // so that we can OR them together.
8382 for (unsigned i = 0; i != 16; ++i) {
8383 int EltIdx = MaskVals[i];
8384 if (EltIdx < 0 || EltIdx >= 16)
8386 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8388 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8389 DAG.getNode(ISD::BUILD_VECTOR, dl,
8390 MVT::v16i8, pshufbMask));
8392 // As PSHUFB will zero elements with negative indices, it's safe to ignore
8393 // the 2nd operand if it's undefined or zero.
8394 if (V2.getOpcode() == ISD::UNDEF ||
8395 ISD::isBuildVectorAllZeros(V2.getNode()))
8398 // Calculate the shuffle mask for the second input, shuffle it, and
8399 // OR it with the first shuffled input.
8401 for (unsigned i = 0; i != 16; ++i) {
8402 int EltIdx = MaskVals[i];
8403 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8404 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8406 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8407 DAG.getNode(ISD::BUILD_VECTOR, dl,
8408 MVT::v16i8, pshufbMask));
8409 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8412 // No SSSE3 - Calculate in place words and then fix all out of place words
8413 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
8414 // the 16 different words that comprise the two doublequadword input vectors.
8415 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8416 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8418 for (int i = 0; i != 8; ++i) {
8419 int Elt0 = MaskVals[i*2];
8420 int Elt1 = MaskVals[i*2+1];
8422 // This word of the result is all undef, skip it.
8423 if (Elt0 < 0 && Elt1 < 0)
8426 // This word of the result is already in the correct place, skip it.
8427 if ((Elt0 == i*2) && (Elt1 == i*2+1))
8430 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8431 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8434 // If Elt0 and Elt1 are defined, are consecutive, and can be load
8435 // using a single extract together, load it and store it.
8436 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8437 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8438 DAG.getIntPtrConstant(Elt1 / 2));
8439 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8440 DAG.getIntPtrConstant(i));
8444 // If Elt1 is defined, extract it from the appropriate source. If the
8445 // source byte is not also odd, shift the extracted word left 8 bits
8446 // otherwise clear the bottom 8 bits if we need to do an or.
8448 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8449 DAG.getIntPtrConstant(Elt1 / 2));
8450 if ((Elt1 & 1) == 0)
8451 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8453 TLI.getShiftAmountTy(InsElt.getValueType())));
8455 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8456 DAG.getConstant(0xFF00, MVT::i16));
8458 // If Elt0 is defined, extract it from the appropriate source. If the
8459 // source byte is not also even, shift the extracted word right 8 bits. If
8460 // Elt1 was also defined, OR the extracted values together before
8461 // inserting them in the result.
8463 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8464 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8465 if ((Elt0 & 1) != 0)
8466 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8468 TLI.getShiftAmountTy(InsElt0.getValueType())));
8470 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8471 DAG.getConstant(0x00FF, MVT::i16));
8472 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8475 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8476 DAG.getIntPtrConstant(i));
8478 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8481 // v32i8 shuffles - Translate to VPSHUFB if possible.
8483 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8484 const X86Subtarget *Subtarget,
8485 SelectionDAG &DAG) {
8486 MVT VT = SVOp->getSimpleValueType(0);
8487 SDValue V1 = SVOp->getOperand(0);
8488 SDValue V2 = SVOp->getOperand(1);
8490 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8492 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8493 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8494 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8496 // VPSHUFB may be generated if
8497 // (1) one of input vector is undefined or zeroinitializer.
8498 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8499 // And (2) the mask indexes don't cross the 128-bit lane.
8500 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8501 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8504 if (V1IsAllZero && !V2IsAllZero) {
8505 CommuteVectorShuffleMask(MaskVals, 32);
8508 return getPSHUFB(MaskVals, V1, dl, DAG);
8511 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8512 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8513 /// done when every pair / quad of shuffle mask elements point to elements in
8514 /// the right sequence. e.g.
8515 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8517 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8518 SelectionDAG &DAG) {
8519 MVT VT = SVOp->getSimpleValueType(0);
8521 unsigned NumElems = VT.getVectorNumElements();
8524 switch (VT.SimpleTy) {
8525 default: llvm_unreachable("Unexpected!");
8528 return SDValue(SVOp, 0);
8529 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
8530 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
8531 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
8532 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
8533 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8534 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
8537 SmallVector<int, 8> MaskVec;
8538 for (unsigned i = 0; i != NumElems; i += Scale) {
8540 for (unsigned j = 0; j != Scale; ++j) {
8541 int EltIdx = SVOp->getMaskElt(i+j);
8545 StartIdx = (EltIdx / Scale);
8546 if (EltIdx != (int)(StartIdx*Scale + j))
8549 MaskVec.push_back(StartIdx);
8552 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8553 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8554 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8557 /// getVZextMovL - Return a zero-extending vector move low node.
8559 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8560 SDValue SrcOp, SelectionDAG &DAG,
8561 const X86Subtarget *Subtarget, SDLoc dl) {
8562 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8563 LoadSDNode *LD = nullptr;
8564 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8565 LD = dyn_cast<LoadSDNode>(SrcOp);
8567 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8569 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8570 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8571 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8572 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8573 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8575 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8576 return DAG.getNode(ISD::BITCAST, dl, VT,
8577 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8578 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8586 return DAG.getNode(ISD::BITCAST, dl, VT,
8587 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8588 DAG.getNode(ISD::BITCAST, dl,
8592 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8593 /// which could not be matched by any known target speficic shuffle
8595 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8597 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8598 if (NewOp.getNode())
8601 MVT VT = SVOp->getSimpleValueType(0);
8603 unsigned NumElems = VT.getVectorNumElements();
8604 unsigned NumLaneElems = NumElems / 2;
8607 MVT EltVT = VT.getVectorElementType();
8608 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8611 SmallVector<int, 16> Mask;
8612 for (unsigned l = 0; l < 2; ++l) {
8613 // Build a shuffle mask for the output, discovering on the fly which
8614 // input vectors to use as shuffle operands (recorded in InputUsed).
8615 // If building a suitable shuffle vector proves too hard, then bail
8616 // out with UseBuildVector set.
8617 bool UseBuildVector = false;
8618 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8619 unsigned LaneStart = l * NumLaneElems;
8620 for (unsigned i = 0; i != NumLaneElems; ++i) {
8621 // The mask element. This indexes into the input.
8622 int Idx = SVOp->getMaskElt(i+LaneStart);
8624 // the mask element does not index into any input vector.
8629 // The input vector this mask element indexes into.
8630 int Input = Idx / NumLaneElems;
8632 // Turn the index into an offset from the start of the input vector.
8633 Idx -= Input * NumLaneElems;
8635 // Find or create a shuffle vector operand to hold this input.
8637 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8638 if (InputUsed[OpNo] == Input)
8639 // This input vector is already an operand.
8641 if (InputUsed[OpNo] < 0) {
8642 // Create a new operand for this input vector.
8643 InputUsed[OpNo] = Input;
8648 if (OpNo >= array_lengthof(InputUsed)) {
8649 // More than two input vectors used! Give up on trying to create a
8650 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
8651 UseBuildVector = true;
8655 // Add the mask index for the new shuffle vector.
8656 Mask.push_back(Idx + OpNo * NumLaneElems);
8659 if (UseBuildVector) {
8660 SmallVector<SDValue, 16> SVOps;
8661 for (unsigned i = 0; i != NumLaneElems; ++i) {
8662 // The mask element. This indexes into the input.
8663 int Idx = SVOp->getMaskElt(i+LaneStart);
8665 SVOps.push_back(DAG.getUNDEF(EltVT));
8669 // The input vector this mask element indexes into.
8670 int Input = Idx / NumElems;
8672 // Turn the index into an offset from the start of the input vector.
8673 Idx -= Input * NumElems;
8675 // Extract the vector element by hand.
8676 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8677 SVOp->getOperand(Input),
8678 DAG.getIntPtrConstant(Idx)));
8681 // Construct the output using a BUILD_VECTOR.
8682 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8683 } else if (InputUsed[0] < 0) {
8684 // No input vectors were used! The result is undefined.
8685 Output[l] = DAG.getUNDEF(NVT);
8687 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8688 (InputUsed[0] % 2) * NumLaneElems,
8690 // If only one input was used, use an undefined vector for the other.
8691 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8692 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8693 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8694 // At least one input vector was used. Create a new shuffle vector.
8695 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8701 // Concatenate the result back
8702 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8705 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8706 /// 4 elements, and match them with several different shuffle types.
8708 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8709 SDValue V1 = SVOp->getOperand(0);
8710 SDValue V2 = SVOp->getOperand(1);
8712 MVT VT = SVOp->getSimpleValueType(0);
8714 assert(VT.is128BitVector() && "Unsupported vector size");
8716 std::pair<int, int> Locs[4];
8717 int Mask1[] = { -1, -1, -1, -1 };
8718 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8722 for (unsigned i = 0; i != 4; ++i) {
8723 int Idx = PermMask[i];
8725 Locs[i] = std::make_pair(-1, -1);
8727 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8729 Locs[i] = std::make_pair(0, NumLo);
8733 Locs[i] = std::make_pair(1, NumHi);
8735 Mask1[2+NumHi] = Idx;
8741 if (NumLo <= 2 && NumHi <= 2) {
8742 // If no more than two elements come from either vector. This can be
8743 // implemented with two shuffles. First shuffle gather the elements.
8744 // The second shuffle, which takes the first shuffle as both of its
8745 // vector operands, put the elements into the right order.
8746 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8748 int Mask2[] = { -1, -1, -1, -1 };
8750 for (unsigned i = 0; i != 4; ++i)
8751 if (Locs[i].first != -1) {
8752 unsigned Idx = (i < 2) ? 0 : 4;
8753 Idx += Locs[i].first * 2 + Locs[i].second;
8757 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8760 if (NumLo == 3 || NumHi == 3) {
8761 // Otherwise, we must have three elements from one vector, call it X, and
8762 // one element from the other, call it Y. First, use a shufps to build an
8763 // intermediate vector with the one element from Y and the element from X
8764 // that will be in the same half in the final destination (the indexes don't
8765 // matter). Then, use a shufps to build the final vector, taking the half
8766 // containing the element from Y from the intermediate, and the other half
8769 // Normalize it so the 3 elements come from V1.
8770 CommuteVectorShuffleMask(PermMask, 4);
8774 // Find the element from V2.
8776 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8777 int Val = PermMask[HiIndex];
8784 Mask1[0] = PermMask[HiIndex];
8786 Mask1[2] = PermMask[HiIndex^1];
8788 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8791 Mask1[0] = PermMask[0];
8792 Mask1[1] = PermMask[1];
8793 Mask1[2] = HiIndex & 1 ? 6 : 4;
8794 Mask1[3] = HiIndex & 1 ? 4 : 6;
8795 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8798 Mask1[0] = HiIndex & 1 ? 2 : 0;
8799 Mask1[1] = HiIndex & 1 ? 0 : 2;
8800 Mask1[2] = PermMask[2];
8801 Mask1[3] = PermMask[3];
8806 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8809 // Break it into (shuffle shuffle_hi, shuffle_lo).
8810 int LoMask[] = { -1, -1, -1, -1 };
8811 int HiMask[] = { -1, -1, -1, -1 };
8813 int *MaskPtr = LoMask;
8814 unsigned MaskIdx = 0;
8817 for (unsigned i = 0; i != 4; ++i) {
8824 int Idx = PermMask[i];
8826 Locs[i] = std::make_pair(-1, -1);
8827 } else if (Idx < 4) {
8828 Locs[i] = std::make_pair(MaskIdx, LoIdx);
8829 MaskPtr[LoIdx] = Idx;
8832 Locs[i] = std::make_pair(MaskIdx, HiIdx);
8833 MaskPtr[HiIdx] = Idx;
8838 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8839 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8840 int MaskOps[] = { -1, -1, -1, -1 };
8841 for (unsigned i = 0; i != 4; ++i)
8842 if (Locs[i].first != -1)
8843 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8844 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8847 static bool MayFoldVectorLoad(SDValue V) {
8848 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8849 V = V.getOperand(0);
8851 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8852 V = V.getOperand(0);
8853 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8854 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8855 // BUILD_VECTOR (load), undef
8856 V = V.getOperand(0);
8858 return MayFoldLoad(V);
8862 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8863 MVT VT = Op.getSimpleValueType();
8865 // Canonizalize to v2f64.
8866 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8867 return DAG.getNode(ISD::BITCAST, dl, VT,
8868 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8873 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8875 SDValue V1 = Op.getOperand(0);
8876 SDValue V2 = Op.getOperand(1);
8877 MVT VT = Op.getSimpleValueType();
8879 assert(VT != MVT::v2i64 && "unsupported shuffle type");
8881 if (HasSSE2 && VT == MVT::v2f64)
8882 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8884 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8885 return DAG.getNode(ISD::BITCAST, dl, VT,
8886 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8887 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8888 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8892 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8893 SDValue V1 = Op.getOperand(0);
8894 SDValue V2 = Op.getOperand(1);
8895 MVT VT = Op.getSimpleValueType();
8897 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8898 "unsupported shuffle type");
8900 if (V2.getOpcode() == ISD::UNDEF)
8904 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8908 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8909 SDValue V1 = Op.getOperand(0);
8910 SDValue V2 = Op.getOperand(1);
8911 MVT VT = Op.getSimpleValueType();
8912 unsigned NumElems = VT.getVectorNumElements();
8914 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8915 // operand of these instructions is only memory, so check if there's a
8916 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8918 bool CanFoldLoad = false;
8920 // Trivial case, when V2 comes from a load.
8921 if (MayFoldVectorLoad(V2))
8924 // When V1 is a load, it can be folded later into a store in isel, example:
8925 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8927 // (MOVLPSmr addr:$src1, VR128:$src2)
8928 // So, recognize this potential and also use MOVLPS or MOVLPD
8929 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8932 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8934 if (HasSSE2 && NumElems == 2)
8935 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
8938 // If we don't care about the second element, proceed to use movss.
8939 if (SVOp->getMaskElt(1) != -1)
8940 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
8943 // movl and movlp will both match v2i64, but v2i64 is never matched by
8944 // movl earlier because we make it strict to avoid messing with the movlp load
8945 // folding logic (see the code above getMOVLP call). Match it here then,
8946 // this is horrible, but will stay like this until we move all shuffle
8947 // matching to x86 specific nodes. Note that for the 1st condition all
8948 // types are matched with movsd.
8950 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
8951 // as to remove this logic from here, as much as possible
8952 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
8953 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8954 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8957 assert(VT != MVT::v4i32 && "unsupported shuffle type");
8959 // Invert the operand order and use SHUFPS to match it.
8960 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
8961 getShuffleSHUFImmediate(SVOp), DAG);
8964 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
8965 SelectionDAG &DAG) {
8967 MVT VT = Load->getSimpleValueType(0);
8968 MVT EVT = VT.getVectorElementType();
8969 SDValue Addr = Load->getOperand(1);
8970 SDValue NewAddr = DAG.getNode(
8971 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
8972 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
8975 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
8976 DAG.getMachineFunction().getMachineMemOperand(
8977 Load->getMemOperand(), 0, EVT.getStoreSize()));
8981 // It is only safe to call this function if isINSERTPSMask is true for
8982 // this shufflevector mask.
8983 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
8984 SelectionDAG &DAG) {
8985 // Generate an insertps instruction when inserting an f32 from memory onto a
8986 // v4f32 or when copying a member from one v4f32 to another.
8987 // We also use it for transferring i32 from one register to another,
8988 // since it simply copies the same bits.
8989 // If we're transferring an i32 from memory to a specific element in a
8990 // register, we output a generic DAG that will match the PINSRD
8992 MVT VT = SVOp->getSimpleValueType(0);
8993 MVT EVT = VT.getVectorElementType();
8994 SDValue V1 = SVOp->getOperand(0);
8995 SDValue V2 = SVOp->getOperand(1);
8996 auto Mask = SVOp->getMask();
8997 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
8998 "unsupported vector type for insertps/pinsrd");
9000 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9001 auto FromV2Predicate = [](const int &i) { return i >= 4; };
9002 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9010 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9013 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9014 "More than one element from V1 and from V2, or no elements from one "
9015 "of the vectors. This case should not have returned true from "
9020 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9023 unsigned SrcIndex = Mask[DestIndex] % 4;
9024 if (MayFoldLoad(From)) {
9025 // Trivial case, when From comes from a load and is only used by the
9026 // shuffle. Make it use insertps from the vector that we need from that
9029 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9030 if (!NewLoad.getNode())
9033 if (EVT == MVT::f32) {
9034 // Create this as a scalar to vector to match the instruction pattern.
9035 SDValue LoadScalarToVector =
9036 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9037 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9038 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9040 } else { // EVT == MVT::i32
9041 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9042 // instruction, to match the PINSRD instruction, which loads an i32 to a
9043 // certain vector element.
9044 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9045 DAG.getConstant(DestIndex, MVT::i32));
9049 // Vector-element-to-vector
9050 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9051 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9054 // Reduce a vector shuffle to zext.
9055 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9056 SelectionDAG &DAG) {
9057 // PMOVZX is only available from SSE41.
9058 if (!Subtarget->hasSSE41())
9061 MVT VT = Op.getSimpleValueType();
9063 // Only AVX2 support 256-bit vector integer extending.
9064 if (!Subtarget->hasInt256() && VT.is256BitVector())
9067 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9069 SDValue V1 = Op.getOperand(0);
9070 SDValue V2 = Op.getOperand(1);
9071 unsigned NumElems = VT.getVectorNumElements();
9073 // Extending is an unary operation and the element type of the source vector
9074 // won't be equal to or larger than i64.
9075 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9076 VT.getVectorElementType() == MVT::i64)
9079 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9080 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9081 while ((1U << Shift) < NumElems) {
9082 if (SVOp->getMaskElt(1U << Shift) == 1)
9085 // The maximal ratio is 8, i.e. from i8 to i64.
9090 // Check the shuffle mask.
9091 unsigned Mask = (1U << Shift) - 1;
9092 for (unsigned i = 0; i != NumElems; ++i) {
9093 int EltIdx = SVOp->getMaskElt(i);
9094 if ((i & Mask) != 0 && EltIdx != -1)
9096 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9100 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9101 MVT NeVT = MVT::getIntegerVT(NBits);
9102 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9104 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9107 // Simplify the operand as it's prepared to be fed into shuffle.
9108 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9109 if (V1.getOpcode() == ISD::BITCAST &&
9110 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9111 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9112 V1.getOperand(0).getOperand(0)
9113 .getSimpleValueType().getSizeInBits() == SignificantBits) {
9114 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9115 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9116 ConstantSDNode *CIdx =
9117 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9118 // If it's foldable, i.e. normal load with single use, we will let code
9119 // selection to fold it. Otherwise, we will short the conversion sequence.
9120 if (CIdx && CIdx->getZExtValue() == 0 &&
9121 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9122 MVT FullVT = V.getSimpleValueType();
9123 MVT V1VT = V1.getSimpleValueType();
9124 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9125 // The "ext_vec_elt" node is wider than the result node.
9126 // In this case we should extract subvector from V.
9127 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9128 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9129 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9130 FullVT.getVectorNumElements()/Ratio);
9131 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9132 DAG.getIntPtrConstant(0));
9134 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9138 return DAG.getNode(ISD::BITCAST, DL, VT,
9139 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9142 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9143 SelectionDAG &DAG) {
9144 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9145 MVT VT = Op.getSimpleValueType();
9147 SDValue V1 = Op.getOperand(0);
9148 SDValue V2 = Op.getOperand(1);
9150 if (isZeroShuffle(SVOp))
9151 return getZeroVector(VT, Subtarget, DAG, dl);
9153 // Handle splat operations
9154 if (SVOp->isSplat()) {
9155 // Use vbroadcast whenever the splat comes from a foldable load
9156 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9157 if (Broadcast.getNode())
9161 // Check integer expanding shuffles.
9162 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9163 if (NewOp.getNode())
9166 // If the shuffle can be profitably rewritten as a narrower shuffle, then
9168 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9170 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9171 if (NewOp.getNode())
9172 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9173 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9174 // FIXME: Figure out a cleaner way to do this.
9175 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9176 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9177 if (NewOp.getNode()) {
9178 MVT NewVT = NewOp.getSimpleValueType();
9179 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9180 NewVT, true, false))
9181 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9184 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9185 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9186 if (NewOp.getNode()) {
9187 MVT NewVT = NewOp.getSimpleValueType();
9188 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9189 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9198 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9199 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9200 SDValue V1 = Op.getOperand(0);
9201 SDValue V2 = Op.getOperand(1);
9202 MVT VT = Op.getSimpleValueType();
9204 unsigned NumElems = VT.getVectorNumElements();
9205 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9206 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9207 bool V1IsSplat = false;
9208 bool V2IsSplat = false;
9209 bool HasSSE2 = Subtarget->hasSSE2();
9210 bool HasFp256 = Subtarget->hasFp256();
9211 bool HasInt256 = Subtarget->hasInt256();
9212 MachineFunction &MF = DAG.getMachineFunction();
9213 bool OptForSize = MF.getFunction()->getAttributes().
9214 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9216 // Check if we should use the experimental vector shuffle lowering. If so,
9217 // delegate completely to that code path.
9218 if (ExperimentalVectorShuffleLowering)
9219 return lowerVectorShuffle(Op, Subtarget, DAG);
9221 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9223 if (V1IsUndef && V2IsUndef)
9224 return DAG.getUNDEF(VT);
9226 // When we create a shuffle node we put the UNDEF node to second operand,
9227 // but in some cases the first operand may be transformed to UNDEF.
9228 // In this case we should just commute the node.
9230 return CommuteVectorShuffle(SVOp, DAG);
9232 // Vector shuffle lowering takes 3 steps:
9234 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9235 // narrowing and commutation of operands should be handled.
9236 // 2) Matching of shuffles with known shuffle masks to x86 target specific
9238 // 3) Rewriting of unmatched masks into new generic shuffle operations,
9239 // so the shuffle can be broken into other shuffles and the legalizer can
9240 // try the lowering again.
9242 // The general idea is that no vector_shuffle operation should be left to
9243 // be matched during isel, all of them must be converted to a target specific
9246 // Normalize the input vectors. Here splats, zeroed vectors, profitable
9247 // narrowing and commutation of operands should be handled. The actual code
9248 // doesn't include all of those, work in progress...
9249 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9250 if (NewOp.getNode())
9253 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9255 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9256 // unpckh_undef). Only use pshufd if speed is more important than size.
9257 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9258 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9259 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9260 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9262 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9263 V2IsUndef && MayFoldVectorLoad(V1))
9264 return getMOVDDup(Op, dl, V1, DAG);
9266 if (isMOVHLPS_v_undef_Mask(M, VT))
9267 return getMOVHighToLow(Op, dl, DAG);
9269 // Use to match splats
9270 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9271 (VT == MVT::v2f64 || VT == MVT::v2i64))
9272 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9274 if (isPSHUFDMask(M, VT)) {
9275 // The actual implementation will match the mask in the if above and then
9276 // during isel it can match several different instructions, not only pshufd
9277 // as its name says, sad but true, emulate the behavior for now...
9278 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9279 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9281 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9283 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9284 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9286 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9287 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9290 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9294 if (isPALIGNRMask(M, VT, Subtarget))
9295 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9296 getShufflePALIGNRImmediate(SVOp),
9299 // Check if this can be converted into a logical shift.
9300 bool isLeft = false;
9303 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9304 if (isShift && ShVal.hasOneUse()) {
9305 // If the shifted value has multiple uses, it may be cheaper to use
9306 // v_set0 + movlhps or movhlps, etc.
9307 MVT EltVT = VT.getVectorElementType();
9308 ShAmt *= EltVT.getSizeInBits();
9309 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9312 if (isMOVLMask(M, VT)) {
9313 if (ISD::isBuildVectorAllZeros(V1.getNode()))
9314 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9315 if (!isMOVLPMask(M, VT)) {
9316 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9317 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9319 if (VT == MVT::v4i32 || VT == MVT::v4f32)
9320 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9324 // FIXME: fold these into legal mask.
9325 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9326 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9328 if (isMOVHLPSMask(M, VT))
9329 return getMOVHighToLow(Op, dl, DAG);
9331 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9332 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9334 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9335 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9337 if (isMOVLPMask(M, VT))
9338 return getMOVLP(Op, dl, DAG, HasSSE2);
9340 if (ShouldXformToMOVHLPS(M, VT) ||
9341 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9342 return CommuteVectorShuffle(SVOp, DAG);
9345 // No better options. Use a vshldq / vsrldq.
9346 MVT EltVT = VT.getVectorElementType();
9347 ShAmt *= EltVT.getSizeInBits();
9348 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9351 bool Commuted = false;
9352 // FIXME: This should also accept a bitcast of a splat? Be careful, not
9353 // 1,1,1,1 -> v8i16 though.
9354 V1IsSplat = isSplatVector(V1.getNode());
9355 V2IsSplat = isSplatVector(V2.getNode());
9357 // Canonicalize the splat or undef, if present, to be on the RHS.
9358 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9359 CommuteVectorShuffleMask(M, NumElems);
9361 std::swap(V1IsSplat, V2IsSplat);
9365 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9366 // Shuffling low element of v1 into undef, just return v1.
9369 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9370 // the instruction selector will not match, so get a canonical MOVL with
9371 // swapped operands to undo the commute.
9372 return getMOVL(DAG, dl, VT, V2, V1);
9375 if (isUNPCKLMask(M, VT, HasInt256))
9376 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9378 if (isUNPCKHMask(M, VT, HasInt256))
9379 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9382 // Normalize mask so all entries that point to V2 points to its first
9383 // element then try to match unpck{h|l} again. If match, return a
9384 // new vector_shuffle with the corrected mask.p
9385 SmallVector<int, 8> NewMask(M.begin(), M.end());
9386 NormalizeMask(NewMask, NumElems);
9387 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9388 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9389 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9390 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9394 // Commute is back and try unpck* again.
9395 // FIXME: this seems wrong.
9396 CommuteVectorShuffleMask(M, NumElems);
9398 std::swap(V1IsSplat, V2IsSplat);
9400 if (isUNPCKLMask(M, VT, HasInt256))
9401 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9403 if (isUNPCKHMask(M, VT, HasInt256))
9404 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9407 // Normalize the node to match x86 shuffle ops if needed
9408 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9409 return CommuteVectorShuffle(SVOp, DAG);
9411 // The checks below are all present in isShuffleMaskLegal, but they are
9412 // inlined here right now to enable us to directly emit target specific
9413 // nodes, and remove one by one until they don't return Op anymore.
9415 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9416 SVOp->getSplatIndex() == 0 && V2IsUndef) {
9417 if (VT == MVT::v2f64 || VT == MVT::v2i64)
9418 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9421 if (isPSHUFHWMask(M, VT, HasInt256))
9422 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9423 getShufflePSHUFHWImmediate(SVOp),
9426 if (isPSHUFLWMask(M, VT, HasInt256))
9427 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9428 getShufflePSHUFLWImmediate(SVOp),
9432 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9434 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9436 if (isSHUFPMask(M, VT))
9437 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9438 getShuffleSHUFImmediate(SVOp), DAG);
9440 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9441 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9442 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9443 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9445 //===--------------------------------------------------------------------===//
9446 // Generate target specific nodes for 128 or 256-bit shuffles only
9447 // supported in the AVX instruction set.
9450 // Handle VMOVDDUPY permutations
9451 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9452 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9454 // Handle VPERMILPS/D* permutations
9455 if (isVPERMILPMask(M, VT)) {
9456 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9457 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9458 getShuffleSHUFImmediate(SVOp), DAG);
9459 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9460 getShuffleSHUFImmediate(SVOp), DAG);
9464 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9465 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9466 Idx*(NumElems/2), DAG, dl);
9468 // Handle VPERM2F128/VPERM2I128 permutations
9469 if (isVPERM2X128Mask(M, VT, HasFp256))
9470 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9471 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9473 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9474 return getINSERTPS(SVOp, dl, DAG);
9477 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9478 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9480 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9481 VT.is512BitVector()) {
9482 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9483 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9484 SmallVector<SDValue, 16> permclMask;
9485 for (unsigned i = 0; i != NumElems; ++i) {
9486 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9489 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9491 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9492 return DAG.getNode(X86ISD::VPERMV, dl, VT,
9493 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9494 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9495 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9498 //===--------------------------------------------------------------------===//
9499 // Since no target specific shuffle was selected for this generic one,
9500 // lower it into other known shuffles. FIXME: this isn't true yet, but
9501 // this is the plan.
9504 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9505 if (VT == MVT::v8i16) {
9506 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9507 if (NewOp.getNode())
9511 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9512 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9513 if (NewOp.getNode())
9517 if (VT == MVT::v16i8) {
9518 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9519 if (NewOp.getNode())
9523 if (VT == MVT::v32i8) {
9524 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9525 if (NewOp.getNode())
9529 // Handle all 128-bit wide vectors with 4 elements, and match them with
9530 // several different shuffle types.
9531 if (NumElems == 4 && VT.is128BitVector())
9532 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9534 // Handle general 256-bit shuffles
9535 if (VT.is256BitVector())
9536 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9541 // This function assumes its argument is a BUILD_VECTOR of constants or
9542 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9544 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9545 unsigned &MaskValue) {
9547 unsigned NumElems = BuildVector->getNumOperands();
9548 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9549 unsigned NumLanes = (NumElems - 1) / 8 + 1;
9550 unsigned NumElemsInLane = NumElems / NumLanes;
9552 // Blend for v16i16 should be symetric for the both lanes.
9553 for (unsigned i = 0; i < NumElemsInLane; ++i) {
9554 SDValue EltCond = BuildVector->getOperand(i);
9555 SDValue SndLaneEltCond =
9556 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9558 int Lane1Cond = -1, Lane2Cond = -1;
9559 if (isa<ConstantSDNode>(EltCond))
9560 Lane1Cond = !isZero(EltCond);
9561 if (isa<ConstantSDNode>(SndLaneEltCond))
9562 Lane2Cond = !isZero(SndLaneEltCond);
9564 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9565 // Lane1Cond != 0, means we want the first argument.
9566 // Lane1Cond == 0, means we want the second argument.
9567 // The encoding of this argument is 0 for the first argument, 1
9568 // for the second. Therefore, invert the condition.
9569 MaskValue |= !Lane1Cond << i;
9570 else if (Lane1Cond < 0)
9571 MaskValue |= !Lane2Cond << i;
9578 // Try to lower a vselect node into a simple blend instruction.
9579 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9580 SelectionDAG &DAG) {
9581 SDValue Cond = Op.getOperand(0);
9582 SDValue LHS = Op.getOperand(1);
9583 SDValue RHS = Op.getOperand(2);
9585 MVT VT = Op.getSimpleValueType();
9586 MVT EltVT = VT.getVectorElementType();
9587 unsigned NumElems = VT.getVectorNumElements();
9589 // There is no blend with immediate in AVX-512.
9590 if (VT.is512BitVector())
9593 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9595 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9598 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9601 // Check the mask for BLEND and build the value.
9602 unsigned MaskValue = 0;
9603 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9606 // Convert i32 vectors to floating point if it is not AVX2.
9607 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9609 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9610 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9612 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9613 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9616 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9617 DAG.getConstant(MaskValue, MVT::i32));
9618 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9621 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9622 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9623 if (BlendOp.getNode())
9626 // Some types for vselect were previously set to Expand, not Legal or
9627 // Custom. Return an empty SDValue so we fall-through to Expand, after
9628 // the Custom lowering phase.
9629 MVT VT = Op.getSimpleValueType();
9630 switch (VT.SimpleTy) {
9638 // We couldn't create a "Blend with immediate" node.
9639 // This node should still be legal, but we'll have to emit a blendv*
9644 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9645 MVT VT = Op.getSimpleValueType();
9648 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9651 if (VT.getSizeInBits() == 8) {
9652 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9653 Op.getOperand(0), Op.getOperand(1));
9654 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9655 DAG.getValueType(VT));
9656 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9659 if (VT.getSizeInBits() == 16) {
9660 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9661 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9663 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9664 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9665 DAG.getNode(ISD::BITCAST, dl,
9669 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9670 Op.getOperand(0), Op.getOperand(1));
9671 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9672 DAG.getValueType(VT));
9673 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9676 if (VT == MVT::f32) {
9677 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9678 // the result back to FR32 register. It's only worth matching if the
9679 // result has a single use which is a store or a bitcast to i32. And in
9680 // the case of a store, it's not worth it if the index is a constant 0,
9681 // because a MOVSSmr can be used instead, which is smaller and faster.
9682 if (!Op.hasOneUse())
9684 SDNode *User = *Op.getNode()->use_begin();
9685 if ((User->getOpcode() != ISD::STORE ||
9686 (isa<ConstantSDNode>(Op.getOperand(1)) &&
9687 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9688 (User->getOpcode() != ISD::BITCAST ||
9689 User->getValueType(0) != MVT::i32))
9691 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9692 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9695 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9698 if (VT == MVT::i32 || VT == MVT::i64) {
9699 // ExtractPS/pextrq works with constant index.
9700 if (isa<ConstantSDNode>(Op.getOperand(1)))
9706 /// Extract one bit from mask vector, like v16i1 or v8i1.
9707 /// AVX-512 feature.
9709 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9710 SDValue Vec = Op.getOperand(0);
9712 MVT VecVT = Vec.getSimpleValueType();
9713 SDValue Idx = Op.getOperand(1);
9714 MVT EltVT = Op.getSimpleValueType();
9716 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9718 // variable index can't be handled in mask registers,
9719 // extend vector to VR512
9720 if (!isa<ConstantSDNode>(Idx)) {
9721 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9722 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9723 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9724 ExtVT.getVectorElementType(), Ext, Idx);
9725 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9728 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9729 const TargetRegisterClass* rc = getRegClassFor(VecVT);
9730 unsigned MaxSift = rc->getSize()*8 - 1;
9731 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9732 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9733 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9734 DAG.getConstant(MaxSift, MVT::i8));
9735 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9736 DAG.getIntPtrConstant(0));
9740 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9741 SelectionDAG &DAG) const {
9743 SDValue Vec = Op.getOperand(0);
9744 MVT VecVT = Vec.getSimpleValueType();
9745 SDValue Idx = Op.getOperand(1);
9747 if (Op.getSimpleValueType() == MVT::i1)
9748 return ExtractBitFromMaskVector(Op, DAG);
9750 if (!isa<ConstantSDNode>(Idx)) {
9751 if (VecVT.is512BitVector() ||
9752 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9753 VecVT.getVectorElementType().getSizeInBits() == 32)) {
9756 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9757 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9758 MaskEltVT.getSizeInBits());
9760 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9761 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9762 getZeroVector(MaskVT, Subtarget, DAG, dl),
9763 Idx, DAG.getConstant(0, getPointerTy()));
9764 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9765 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9766 Perm, DAG.getConstant(0, getPointerTy()));
9771 // If this is a 256-bit vector result, first extract the 128-bit vector and
9772 // then extract the element from the 128-bit vector.
9773 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9775 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9776 // Get the 128-bit vector.
9777 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9778 MVT EltVT = VecVT.getVectorElementType();
9780 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9782 //if (IdxVal >= NumElems/2)
9783 // IdxVal -= NumElems/2;
9784 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9785 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9786 DAG.getConstant(IdxVal, MVT::i32));
9789 assert(VecVT.is128BitVector() && "Unexpected vector length");
9791 if (Subtarget->hasSSE41()) {
9792 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9797 MVT VT = Op.getSimpleValueType();
9798 // TODO: handle v16i8.
9799 if (VT.getSizeInBits() == 16) {
9800 SDValue Vec = Op.getOperand(0);
9801 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9803 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9804 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9805 DAG.getNode(ISD::BITCAST, dl,
9808 // Transform it so it match pextrw which produces a 32-bit result.
9809 MVT EltVT = MVT::i32;
9810 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9811 Op.getOperand(0), Op.getOperand(1));
9812 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9813 DAG.getValueType(VT));
9814 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9817 if (VT.getSizeInBits() == 32) {
9818 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9822 // SHUFPS the element to the lowest double word, then movss.
9823 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9824 MVT VVT = Op.getOperand(0).getSimpleValueType();
9825 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9826 DAG.getUNDEF(VVT), Mask);
9827 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9828 DAG.getIntPtrConstant(0));
9831 if (VT.getSizeInBits() == 64) {
9832 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9833 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9834 // to match extract_elt for f64.
9835 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9839 // UNPCKHPD the element to the lowest double word, then movsd.
9840 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9841 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9842 int Mask[2] = { 1, -1 };
9843 MVT VVT = Op.getOperand(0).getSimpleValueType();
9844 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9845 DAG.getUNDEF(VVT), Mask);
9846 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9847 DAG.getIntPtrConstant(0));
9853 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9854 MVT VT = Op.getSimpleValueType();
9855 MVT EltVT = VT.getVectorElementType();
9858 SDValue N0 = Op.getOperand(0);
9859 SDValue N1 = Op.getOperand(1);
9860 SDValue N2 = Op.getOperand(2);
9862 if (!VT.is128BitVector())
9865 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9866 isa<ConstantSDNode>(N2)) {
9868 if (VT == MVT::v8i16)
9869 Opc = X86ISD::PINSRW;
9870 else if (VT == MVT::v16i8)
9871 Opc = X86ISD::PINSRB;
9873 Opc = X86ISD::PINSRB;
9875 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9877 if (N1.getValueType() != MVT::i32)
9878 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9879 if (N2.getValueType() != MVT::i32)
9880 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9881 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9884 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9885 // Bits [7:6] of the constant are the source select. This will always be
9886 // zero here. The DAG Combiner may combine an extract_elt index into these
9887 // bits. For example (insert (extract, 3), 2) could be matched by putting
9888 // the '3' into bits [7:6] of X86ISD::INSERTPS.
9889 // Bits [5:4] of the constant are the destination select. This is the
9890 // value of the incoming immediate.
9891 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
9892 // combine either bitwise AND or insert of float 0.0 to set these bits.
9893 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9894 // Create this as a scalar to vector..
9895 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9896 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9899 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9900 // PINSR* works with constant index.
9906 /// Insert one bit to mask vector, like v16i1 or v8i1.
9907 /// AVX-512 feature.
9909 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9911 SDValue Vec = Op.getOperand(0);
9912 SDValue Elt = Op.getOperand(1);
9913 SDValue Idx = Op.getOperand(2);
9914 MVT VecVT = Vec.getSimpleValueType();
9916 if (!isa<ConstantSDNode>(Idx)) {
9917 // Non constant index. Extend source and destination,
9918 // insert element and then truncate the result.
9919 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9920 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
9921 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
9922 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9923 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9924 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
9927 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9928 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
9929 if (Vec.getOpcode() == ISD::UNDEF)
9930 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9931 DAG.getConstant(IdxVal, MVT::i8));
9932 const TargetRegisterClass* rc = getRegClassFor(VecVT);
9933 unsigned MaxSift = rc->getSize()*8 - 1;
9934 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9935 DAG.getConstant(MaxSift, MVT::i8));
9936 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
9937 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9938 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
9941 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
9942 MVT VT = Op.getSimpleValueType();
9943 MVT EltVT = VT.getVectorElementType();
9945 if (EltVT == MVT::i1)
9946 return InsertBitToMaskVector(Op, DAG);
9949 SDValue N0 = Op.getOperand(0);
9950 SDValue N1 = Op.getOperand(1);
9951 SDValue N2 = Op.getOperand(2);
9953 // If this is a 256-bit vector result, first extract the 128-bit vector,
9954 // insert the element into the extracted half and then place it back.
9955 if (VT.is256BitVector() || VT.is512BitVector()) {
9956 if (!isa<ConstantSDNode>(N2))
9959 // Get the desired 128-bit vector half.
9960 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
9961 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
9963 // Insert the element into the desired half.
9964 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
9965 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
9967 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
9968 DAG.getConstant(IdxIn128, MVT::i32));
9970 // Insert the changed part back to the 256-bit vector
9971 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
9974 if (Subtarget->hasSSE41())
9975 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
9977 if (EltVT == MVT::i8)
9980 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
9981 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
9982 // as its second argument.
9983 if (N1.getValueType() != MVT::i32)
9984 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9985 if (N2.getValueType() != MVT::i32)
9986 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9987 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
9992 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
9994 MVT OpVT = Op.getSimpleValueType();
9996 // If this is a 256-bit vector result, first insert into a 128-bit
9997 // vector and then insert into the 256-bit vector.
9998 if (!OpVT.is128BitVector()) {
9999 // Insert into a 128-bit vector.
10000 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10001 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10002 OpVT.getVectorNumElements() / SizeFactor);
10004 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10006 // Insert the 128-bit vector.
10007 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10010 if (OpVT == MVT::v1i64 &&
10011 Op.getOperand(0).getValueType() == MVT::i64)
10012 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10014 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10015 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10016 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10017 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10020 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10021 // a simple subregister reference or explicit instructions to grab
10022 // upper bits of a vector.
10023 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10024 SelectionDAG &DAG) {
10026 SDValue In = Op.getOperand(0);
10027 SDValue Idx = Op.getOperand(1);
10028 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10029 MVT ResVT = Op.getSimpleValueType();
10030 MVT InVT = In.getSimpleValueType();
10032 if (Subtarget->hasFp256()) {
10033 if (ResVT.is128BitVector() &&
10034 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10035 isa<ConstantSDNode>(Idx)) {
10036 return Extract128BitVector(In, IdxVal, DAG, dl);
10038 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10039 isa<ConstantSDNode>(Idx)) {
10040 return Extract256BitVector(In, IdxVal, DAG, dl);
10046 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10047 // simple superregister reference or explicit instructions to insert
10048 // the upper bits of a vector.
10049 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10050 SelectionDAG &DAG) {
10051 if (Subtarget->hasFp256()) {
10052 SDLoc dl(Op.getNode());
10053 SDValue Vec = Op.getNode()->getOperand(0);
10054 SDValue SubVec = Op.getNode()->getOperand(1);
10055 SDValue Idx = Op.getNode()->getOperand(2);
10057 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10058 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10059 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10060 isa<ConstantSDNode>(Idx)) {
10061 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10062 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10065 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10066 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10067 isa<ConstantSDNode>(Idx)) {
10068 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10069 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10075 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10076 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10077 // one of the above mentioned nodes. It has to be wrapped because otherwise
10078 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10079 // be used to form addressing mode. These wrapped nodes will be selected
10082 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10083 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10085 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10086 // global base reg.
10087 unsigned char OpFlag = 0;
10088 unsigned WrapperKind = X86ISD::Wrapper;
10089 CodeModel::Model M = DAG.getTarget().getCodeModel();
10091 if (Subtarget->isPICStyleRIPRel() &&
10092 (M == CodeModel::Small || M == CodeModel::Kernel))
10093 WrapperKind = X86ISD::WrapperRIP;
10094 else if (Subtarget->isPICStyleGOT())
10095 OpFlag = X86II::MO_GOTOFF;
10096 else if (Subtarget->isPICStyleStubPIC())
10097 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10099 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10100 CP->getAlignment(),
10101 CP->getOffset(), OpFlag);
10103 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10104 // With PIC, the address is actually $g + Offset.
10106 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10107 DAG.getNode(X86ISD::GlobalBaseReg,
10108 SDLoc(), getPointerTy()),
10115 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10116 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10118 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10119 // global base reg.
10120 unsigned char OpFlag = 0;
10121 unsigned WrapperKind = X86ISD::Wrapper;
10122 CodeModel::Model M = DAG.getTarget().getCodeModel();
10124 if (Subtarget->isPICStyleRIPRel() &&
10125 (M == CodeModel::Small || M == CodeModel::Kernel))
10126 WrapperKind = X86ISD::WrapperRIP;
10127 else if (Subtarget->isPICStyleGOT())
10128 OpFlag = X86II::MO_GOTOFF;
10129 else if (Subtarget->isPICStyleStubPIC())
10130 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10132 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10135 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10137 // With PIC, the address is actually $g + Offset.
10139 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10140 DAG.getNode(X86ISD::GlobalBaseReg,
10141 SDLoc(), getPointerTy()),
10148 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10149 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10151 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10152 // global base reg.
10153 unsigned char OpFlag = 0;
10154 unsigned WrapperKind = X86ISD::Wrapper;
10155 CodeModel::Model M = DAG.getTarget().getCodeModel();
10157 if (Subtarget->isPICStyleRIPRel() &&
10158 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10159 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10160 OpFlag = X86II::MO_GOTPCREL;
10161 WrapperKind = X86ISD::WrapperRIP;
10162 } else if (Subtarget->isPICStyleGOT()) {
10163 OpFlag = X86II::MO_GOT;
10164 } else if (Subtarget->isPICStyleStubPIC()) {
10165 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10166 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10167 OpFlag = X86II::MO_DARWIN_NONLAZY;
10170 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10173 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10175 // With PIC, the address is actually $g + Offset.
10176 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10177 !Subtarget->is64Bit()) {
10178 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10179 DAG.getNode(X86ISD::GlobalBaseReg,
10180 SDLoc(), getPointerTy()),
10184 // For symbols that require a load from a stub to get the address, emit the
10186 if (isGlobalStubReference(OpFlag))
10187 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10188 MachinePointerInfo::getGOT(), false, false, false, 0);
10194 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10195 // Create the TargetBlockAddressAddress node.
10196 unsigned char OpFlags =
10197 Subtarget->ClassifyBlockAddressReference();
10198 CodeModel::Model M = DAG.getTarget().getCodeModel();
10199 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10200 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10202 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10205 if (Subtarget->isPICStyleRIPRel() &&
10206 (M == CodeModel::Small || M == CodeModel::Kernel))
10207 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10209 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10211 // With PIC, the address is actually $g + Offset.
10212 if (isGlobalRelativeToPICBase(OpFlags)) {
10213 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10214 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10222 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10223 int64_t Offset, SelectionDAG &DAG) const {
10224 // Create the TargetGlobalAddress node, folding in the constant
10225 // offset if it is legal.
10226 unsigned char OpFlags =
10227 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10228 CodeModel::Model M = DAG.getTarget().getCodeModel();
10230 if (OpFlags == X86II::MO_NO_FLAG &&
10231 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10232 // A direct static reference to a global.
10233 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10236 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10239 if (Subtarget->isPICStyleRIPRel() &&
10240 (M == CodeModel::Small || M == CodeModel::Kernel))
10241 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10243 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10245 // With PIC, the address is actually $g + Offset.
10246 if (isGlobalRelativeToPICBase(OpFlags)) {
10247 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10248 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10252 // For globals that require a load from a stub to get the address, emit the
10254 if (isGlobalStubReference(OpFlags))
10255 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10256 MachinePointerInfo::getGOT(), false, false, false, 0);
10258 // If there was a non-zero offset that we didn't fold, create an explicit
10259 // addition for it.
10261 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10262 DAG.getConstant(Offset, getPointerTy()));
10268 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10269 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10270 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10271 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10275 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10276 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10277 unsigned char OperandFlags, bool LocalDynamic = false) {
10278 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10279 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10281 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10282 GA->getValueType(0),
10286 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10290 SDValue Ops[] = { Chain, TGA, *InFlag };
10291 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10293 SDValue Ops[] = { Chain, TGA };
10294 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10297 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10298 MFI->setAdjustsStack(true);
10300 SDValue Flag = Chain.getValue(1);
10301 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10304 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10306 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10309 SDLoc dl(GA); // ? function entry point might be better
10310 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10311 DAG.getNode(X86ISD::GlobalBaseReg,
10312 SDLoc(), PtrVT), InFlag);
10313 InFlag = Chain.getValue(1);
10315 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10318 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10320 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10322 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10323 X86::RAX, X86II::MO_TLSGD);
10326 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10332 // Get the start address of the TLS block for this module.
10333 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10334 .getInfo<X86MachineFunctionInfo>();
10335 MFI->incNumLocalDynamicTLSAccesses();
10339 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10340 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10343 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10344 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10345 InFlag = Chain.getValue(1);
10346 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10347 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10350 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10354 unsigned char OperandFlags = X86II::MO_DTPOFF;
10355 unsigned WrapperKind = X86ISD::Wrapper;
10356 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10357 GA->getValueType(0),
10358 GA->getOffset(), OperandFlags);
10359 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10361 // Add x@dtpoff with the base.
10362 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10365 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10366 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10367 const EVT PtrVT, TLSModel::Model model,
10368 bool is64Bit, bool isPIC) {
10371 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10372 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10373 is64Bit ? 257 : 256));
10375 SDValue ThreadPointer =
10376 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10377 MachinePointerInfo(Ptr), false, false, false, 0);
10379 unsigned char OperandFlags = 0;
10380 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10382 unsigned WrapperKind = X86ISD::Wrapper;
10383 if (model == TLSModel::LocalExec) {
10384 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10385 } else if (model == TLSModel::InitialExec) {
10387 OperandFlags = X86II::MO_GOTTPOFF;
10388 WrapperKind = X86ISD::WrapperRIP;
10390 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10393 llvm_unreachable("Unexpected model");
10396 // emit "addl x@ntpoff,%eax" (local exec)
10397 // or "addl x@indntpoff,%eax" (initial exec)
10398 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10400 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10401 GA->getOffset(), OperandFlags);
10402 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10404 if (model == TLSModel::InitialExec) {
10405 if (isPIC && !is64Bit) {
10406 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10407 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10411 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10412 MachinePointerInfo::getGOT(), false, false, false, 0);
10415 // The address of the thread local variable is the add of the thread
10416 // pointer with the offset of the variable.
10417 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10421 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10423 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10424 const GlobalValue *GV = GA->getGlobal();
10426 if (Subtarget->isTargetELF()) {
10427 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10430 case TLSModel::GeneralDynamic:
10431 if (Subtarget->is64Bit())
10432 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10433 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10434 case TLSModel::LocalDynamic:
10435 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10436 Subtarget->is64Bit());
10437 case TLSModel::InitialExec:
10438 case TLSModel::LocalExec:
10439 return LowerToTLSExecModel(
10440 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10441 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10443 llvm_unreachable("Unknown TLS model.");
10446 if (Subtarget->isTargetDarwin()) {
10447 // Darwin only has one model of TLS. Lower to that.
10448 unsigned char OpFlag = 0;
10449 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10450 X86ISD::WrapperRIP : X86ISD::Wrapper;
10452 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10453 // global base reg.
10454 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10455 !Subtarget->is64Bit();
10457 OpFlag = X86II::MO_TLVP_PIC_BASE;
10459 OpFlag = X86II::MO_TLVP;
10461 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10462 GA->getValueType(0),
10463 GA->getOffset(), OpFlag);
10464 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10466 // With PIC32, the address is actually $g + Offset.
10468 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10469 DAG.getNode(X86ISD::GlobalBaseReg,
10470 SDLoc(), getPointerTy()),
10473 // Lowering the machine isd will make sure everything is in the right
10475 SDValue Chain = DAG.getEntryNode();
10476 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10477 SDValue Args[] = { Chain, Offset };
10478 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10480 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10481 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10482 MFI->setAdjustsStack(true);
10484 // And our return value (tls address) is in the standard call return value
10486 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10487 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10488 Chain.getValue(1));
10491 if (Subtarget->isTargetKnownWindowsMSVC() ||
10492 Subtarget->isTargetWindowsGNU()) {
10493 // Just use the implicit TLS architecture
10494 // Need to generate someting similar to:
10495 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10497 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
10498 // mov rcx, qword [rdx+rcx*8]
10499 // mov eax, .tls$:tlsvar
10500 // [rax+rcx] contains the address
10501 // Windows 64bit: gs:0x58
10502 // Windows 32bit: fs:__tls_array
10505 SDValue Chain = DAG.getEntryNode();
10507 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10508 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10509 // use its literal value of 0x2C.
10510 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10511 ? Type::getInt8PtrTy(*DAG.getContext(),
10513 : Type::getInt32PtrTy(*DAG.getContext(),
10517 Subtarget->is64Bit()
10518 ? DAG.getIntPtrConstant(0x58)
10519 : (Subtarget->isTargetWindowsGNU()
10520 ? DAG.getIntPtrConstant(0x2C)
10521 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10523 SDValue ThreadPointer =
10524 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10525 MachinePointerInfo(Ptr), false, false, false, 0);
10527 // Load the _tls_index variable
10528 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10529 if (Subtarget->is64Bit())
10530 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10531 IDX, MachinePointerInfo(), MVT::i32,
10534 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10535 false, false, false, 0);
10537 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10539 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10541 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10542 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10543 false, false, false, 0);
10545 // Get the offset of start of .tls section
10546 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10547 GA->getValueType(0),
10548 GA->getOffset(), X86II::MO_SECREL);
10549 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10551 // The address of the thread local variable is the add of the thread
10552 // pointer with the offset of the variable.
10553 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10556 llvm_unreachable("TLS not implemented for this target.");
10559 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10560 /// and take a 2 x i32 value to shift plus a shift amount.
10561 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10562 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10563 MVT VT = Op.getSimpleValueType();
10564 unsigned VTBits = VT.getSizeInBits();
10566 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10567 SDValue ShOpLo = Op.getOperand(0);
10568 SDValue ShOpHi = Op.getOperand(1);
10569 SDValue ShAmt = Op.getOperand(2);
10570 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10571 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10573 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10574 DAG.getConstant(VTBits - 1, MVT::i8));
10575 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10576 DAG.getConstant(VTBits - 1, MVT::i8))
10577 : DAG.getConstant(0, VT);
10579 SDValue Tmp2, Tmp3;
10580 if (Op.getOpcode() == ISD::SHL_PARTS) {
10581 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10582 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10584 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10585 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10588 // If the shift amount is larger or equal than the width of a part we can't
10589 // rely on the results of shld/shrd. Insert a test and select the appropriate
10590 // values for large shift amounts.
10591 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10592 DAG.getConstant(VTBits, MVT::i8));
10593 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10594 AndNode, DAG.getConstant(0, MVT::i8));
10597 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10598 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10599 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10601 if (Op.getOpcode() == ISD::SHL_PARTS) {
10602 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10603 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10605 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10606 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10609 SDValue Ops[2] = { Lo, Hi };
10610 return DAG.getMergeValues(Ops, dl);
10613 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10614 SelectionDAG &DAG) const {
10615 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10617 if (SrcVT.isVector())
10620 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10621 "Unknown SINT_TO_FP to lower!");
10623 // These are really Legal; return the operand so the caller accepts it as
10625 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10627 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10628 Subtarget->is64Bit()) {
10633 unsigned Size = SrcVT.getSizeInBits()/8;
10634 MachineFunction &MF = DAG.getMachineFunction();
10635 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10636 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10637 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10639 MachinePointerInfo::getFixedStack(SSFI),
10641 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10644 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10646 SelectionDAG &DAG) const {
10650 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10652 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10654 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10656 unsigned ByteSize = SrcVT.getSizeInBits()/8;
10658 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10659 MachineMemOperand *MMO;
10661 int SSFI = FI->getIndex();
10663 DAG.getMachineFunction()
10664 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10665 MachineMemOperand::MOLoad, ByteSize, ByteSize);
10667 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10668 StackSlot = StackSlot.getOperand(1);
10670 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10671 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10673 Tys, Ops, SrcVT, MMO);
10676 Chain = Result.getValue(1);
10677 SDValue InFlag = Result.getValue(2);
10679 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10680 // shouldn't be necessary except that RFP cannot be live across
10681 // multiple blocks. When stackifier is fixed, they can be uncoupled.
10682 MachineFunction &MF = DAG.getMachineFunction();
10683 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10684 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10685 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10686 Tys = DAG.getVTList(MVT::Other);
10688 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10690 MachineMemOperand *MMO =
10691 DAG.getMachineFunction()
10692 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10693 MachineMemOperand::MOStore, SSFISize, SSFISize);
10695 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10696 Ops, Op.getValueType(), MMO);
10697 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10698 MachinePointerInfo::getFixedStack(SSFI),
10699 false, false, false, 0);
10705 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10706 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10707 SelectionDAG &DAG) const {
10708 // This algorithm is not obvious. Here it is what we're trying to output:
10711 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10712 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10714 haddpd %xmm0, %xmm0
10716 pshufd $0x4e, %xmm0, %xmm1
10722 LLVMContext *Context = DAG.getContext();
10724 // Build some magic constants.
10725 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10726 Constant *C0 = ConstantDataVector::get(*Context, CV0);
10727 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10729 SmallVector<Constant*,2> CV1;
10731 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10732 APInt(64, 0x4330000000000000ULL))));
10734 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10735 APInt(64, 0x4530000000000000ULL))));
10736 Constant *C1 = ConstantVector::get(CV1);
10737 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10739 // Load the 64-bit value into an XMM register.
10740 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10742 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10743 MachinePointerInfo::getConstantPool(),
10744 false, false, false, 16);
10745 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10746 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10749 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10750 MachinePointerInfo::getConstantPool(),
10751 false, false, false, 16);
10752 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10753 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10756 if (Subtarget->hasSSE3()) {
10757 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10758 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10760 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10761 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10763 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10764 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10768 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10769 DAG.getIntPtrConstant(0));
10772 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10773 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10774 SelectionDAG &DAG) const {
10776 // FP constant to bias correct the final result.
10777 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10780 // Load the 32-bit value into an XMM register.
10781 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10784 // Zero out the upper parts of the register.
10785 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10787 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10788 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10789 DAG.getIntPtrConstant(0));
10791 // Or the load with the bias.
10792 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10793 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10794 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10795 MVT::v2f64, Load)),
10796 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10797 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10798 MVT::v2f64, Bias)));
10799 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10800 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10801 DAG.getIntPtrConstant(0));
10803 // Subtract the bias.
10804 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10806 // Handle final rounding.
10807 EVT DestVT = Op.getValueType();
10809 if (DestVT.bitsLT(MVT::f64))
10810 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10811 DAG.getIntPtrConstant(0));
10812 if (DestVT.bitsGT(MVT::f64))
10813 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10815 // Handle final rounding.
10819 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10820 SelectionDAG &DAG) const {
10821 SDValue N0 = Op.getOperand(0);
10822 MVT SVT = N0.getSimpleValueType();
10825 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10826 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10827 "Custom UINT_TO_FP is not supported!");
10829 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10830 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10831 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10834 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10835 SelectionDAG &DAG) const {
10836 SDValue N0 = Op.getOperand(0);
10839 if (Op.getValueType().isVector())
10840 return lowerUINT_TO_FP_vec(Op, DAG);
10842 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10843 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10844 // the optimization here.
10845 if (DAG.SignBitIsZero(N0))
10846 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10848 MVT SrcVT = N0.getSimpleValueType();
10849 MVT DstVT = Op.getSimpleValueType();
10850 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10851 return LowerUINT_TO_FP_i64(Op, DAG);
10852 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10853 return LowerUINT_TO_FP_i32(Op, DAG);
10854 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10857 // Make a 64-bit buffer, and use it to build an FILD.
10858 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10859 if (SrcVT == MVT::i32) {
10860 SDValue WordOff = DAG.getConstant(4, getPointerTy());
10861 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10862 getPointerTy(), StackSlot, WordOff);
10863 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10864 StackSlot, MachinePointerInfo(),
10866 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10867 OffsetSlot, MachinePointerInfo(),
10869 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10873 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10874 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10875 StackSlot, MachinePointerInfo(),
10877 // For i64 source, we need to add the appropriate power of 2 if the input
10878 // was negative. This is the same as the optimization in
10879 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10880 // we must be careful to do the computation in x87 extended precision, not
10881 // in SSE. (The generic code can't know it's OK to do this, or how to.)
10882 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10883 MachineMemOperand *MMO =
10884 DAG.getMachineFunction()
10885 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10886 MachineMemOperand::MOLoad, 8, 8);
10888 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10889 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10890 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10893 APInt FF(32, 0x5F800000ULL);
10895 // Check whether the sign bit is set.
10896 SDValue SignSet = DAG.getSetCC(dl,
10897 getSetCCResultType(*DAG.getContext(), MVT::i64),
10898 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10901 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10902 SDValue FudgePtr = DAG.getConstantPool(
10903 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10906 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10907 SDValue Zero = DAG.getIntPtrConstant(0);
10908 SDValue Four = DAG.getIntPtrConstant(4);
10909 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10911 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10913 // Load the value out, extending it from f32 to f80.
10914 // FIXME: Avoid the extend by constructing the right constant pool?
10915 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10916 FudgePtr, MachinePointerInfo::getConstantPool(),
10917 MVT::f32, false, false, 4);
10918 // Extend everything to 80 bits to force it to be done on x87.
10919 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10920 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10923 std::pair<SDValue,SDValue>
10924 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
10925 bool IsSigned, bool IsReplace) const {
10928 EVT DstTy = Op.getValueType();
10930 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
10931 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
10935 assert(DstTy.getSimpleVT() <= MVT::i64 &&
10936 DstTy.getSimpleVT() >= MVT::i16 &&
10937 "Unknown FP_TO_INT to lower!");
10939 // These are really Legal.
10940 if (DstTy == MVT::i32 &&
10941 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10942 return std::make_pair(SDValue(), SDValue());
10943 if (Subtarget->is64Bit() &&
10944 DstTy == MVT::i64 &&
10945 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10946 return std::make_pair(SDValue(), SDValue());
10948 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
10949 // stack slot, or into the FTOL runtime function.
10950 MachineFunction &MF = DAG.getMachineFunction();
10951 unsigned MemSize = DstTy.getSizeInBits()/8;
10952 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
10953 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10956 if (!IsSigned && isIntegerTypeFTOL(DstTy))
10957 Opc = X86ISD::WIN_FTOL;
10959 switch (DstTy.getSimpleVT().SimpleTy) {
10960 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
10961 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
10962 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
10963 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
10966 SDValue Chain = DAG.getEntryNode();
10967 SDValue Value = Op.getOperand(0);
10968 EVT TheVT = Op.getOperand(0).getValueType();
10969 // FIXME This causes a redundant load/store if the SSE-class value is already
10970 // in memory, such as if it is on the callstack.
10971 if (isScalarFPTypeInSSEReg(TheVT)) {
10972 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
10973 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
10974 MachinePointerInfo::getFixedStack(SSFI),
10976 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
10978 Chain, StackSlot, DAG.getValueType(TheVT)
10981 MachineMemOperand *MMO =
10982 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10983 MachineMemOperand::MOLoad, MemSize, MemSize);
10984 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
10985 Chain = Value.getValue(1);
10986 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
10987 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10990 MachineMemOperand *MMO =
10991 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10992 MachineMemOperand::MOStore, MemSize, MemSize);
10994 if (Opc != X86ISD::WIN_FTOL) {
10995 // Build the FP_TO_INT*_IN_MEM
10996 SDValue Ops[] = { Chain, Value, StackSlot };
10997 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
10999 return std::make_pair(FIST, StackSlot);
11001 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11002 DAG.getVTList(MVT::Other, MVT::Glue),
11004 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11005 MVT::i32, ftol.getValue(1));
11006 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11007 MVT::i32, eax.getValue(2));
11008 SDValue Ops[] = { eax, edx };
11009 SDValue pair = IsReplace
11010 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11011 : DAG.getMergeValues(Ops, DL);
11012 return std::make_pair(pair, SDValue());
11016 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11017 const X86Subtarget *Subtarget) {
11018 MVT VT = Op->getSimpleValueType(0);
11019 SDValue In = Op->getOperand(0);
11020 MVT InVT = In.getSimpleValueType();
11023 // Optimize vectors in AVX mode:
11026 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11027 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11028 // Concat upper and lower parts.
11031 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11032 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11033 // Concat upper and lower parts.
11036 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11037 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11038 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11041 if (Subtarget->hasInt256())
11042 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11044 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11045 SDValue Undef = DAG.getUNDEF(InVT);
11046 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11047 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11048 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11050 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11051 VT.getVectorNumElements()/2);
11053 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11054 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11056 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11059 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11060 SelectionDAG &DAG) {
11061 MVT VT = Op->getSimpleValueType(0);
11062 SDValue In = Op->getOperand(0);
11063 MVT InVT = In.getSimpleValueType();
11065 unsigned int NumElts = VT.getVectorNumElements();
11066 if (NumElts != 8 && NumElts != 16)
11069 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11070 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11072 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11073 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11074 // Now we have only mask extension
11075 assert(InVT.getVectorElementType() == MVT::i1);
11076 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11077 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11078 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11079 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11080 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11081 MachinePointerInfo::getConstantPool(),
11082 false, false, false, Alignment);
11084 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11085 if (VT.is512BitVector())
11087 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11090 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11091 SelectionDAG &DAG) {
11092 if (Subtarget->hasFp256()) {
11093 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11101 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11102 SelectionDAG &DAG) {
11104 MVT VT = Op.getSimpleValueType();
11105 SDValue In = Op.getOperand(0);
11106 MVT SVT = In.getSimpleValueType();
11108 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11109 return LowerZERO_EXTEND_AVX512(Op, DAG);
11111 if (Subtarget->hasFp256()) {
11112 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11117 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11118 VT.getVectorNumElements() != SVT.getVectorNumElements());
11122 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11124 MVT VT = Op.getSimpleValueType();
11125 SDValue In = Op.getOperand(0);
11126 MVT InVT = In.getSimpleValueType();
11128 if (VT == MVT::i1) {
11129 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11130 "Invalid scalar TRUNCATE operation");
11131 if (InVT == MVT::i32)
11133 if (InVT.getSizeInBits() == 64)
11134 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11135 else if (InVT.getSizeInBits() < 32)
11136 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11137 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11139 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11140 "Invalid TRUNCATE operation");
11142 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11143 if (VT.getVectorElementType().getSizeInBits() >=8)
11144 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11146 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11147 unsigned NumElts = InVT.getVectorNumElements();
11148 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11149 if (InVT.getSizeInBits() < 512) {
11150 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11151 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11155 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11156 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11157 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11158 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11159 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11160 MachinePointerInfo::getConstantPool(),
11161 false, false, false, Alignment);
11162 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11163 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11164 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11167 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11168 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11169 if (Subtarget->hasInt256()) {
11170 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11171 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11172 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11174 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11175 DAG.getIntPtrConstant(0));
11178 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11179 DAG.getIntPtrConstant(0));
11180 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11181 DAG.getIntPtrConstant(2));
11182 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11183 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11184 static const int ShufMask[] = {0, 2, 4, 6};
11185 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11188 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11189 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11190 if (Subtarget->hasInt256()) {
11191 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11193 SmallVector<SDValue,32> pshufbMask;
11194 for (unsigned i = 0; i < 2; ++i) {
11195 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11196 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11197 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11198 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11199 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11200 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11201 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11202 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11203 for (unsigned j = 0; j < 8; ++j)
11204 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11206 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11207 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11208 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11210 static const int ShufMask[] = {0, 2, -1, -1};
11211 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11213 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11214 DAG.getIntPtrConstant(0));
11215 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11218 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11219 DAG.getIntPtrConstant(0));
11221 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11222 DAG.getIntPtrConstant(4));
11224 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11225 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11227 // The PSHUFB mask:
11228 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11229 -1, -1, -1, -1, -1, -1, -1, -1};
11231 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11232 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11233 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11235 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11236 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11238 // The MOVLHPS Mask:
11239 static const int ShufMask2[] = {0, 1, 4, 5};
11240 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11241 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11244 // Handle truncation of V256 to V128 using shuffles.
11245 if (!VT.is128BitVector() || !InVT.is256BitVector())
11248 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11250 unsigned NumElems = VT.getVectorNumElements();
11251 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11253 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11254 // Prepare truncation shuffle mask
11255 for (unsigned i = 0; i != NumElems; ++i)
11256 MaskVec[i] = i * 2;
11257 SDValue V = DAG.getVectorShuffle(NVT, DL,
11258 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11259 DAG.getUNDEF(NVT), &MaskVec[0]);
11260 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11261 DAG.getIntPtrConstant(0));
11264 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11265 SelectionDAG &DAG) const {
11266 assert(!Op.getSimpleValueType().isVector());
11268 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11269 /*IsSigned=*/ true, /*IsReplace=*/ false);
11270 SDValue FIST = Vals.first, StackSlot = Vals.second;
11271 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11272 if (!FIST.getNode()) return Op;
11274 if (StackSlot.getNode())
11275 // Load the result.
11276 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11277 FIST, StackSlot, MachinePointerInfo(),
11278 false, false, false, 0);
11280 // The node is the result.
11284 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11285 SelectionDAG &DAG) const {
11286 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11287 /*IsSigned=*/ false, /*IsReplace=*/ false);
11288 SDValue FIST = Vals.first, StackSlot = Vals.second;
11289 assert(FIST.getNode() && "Unexpected failure");
11291 if (StackSlot.getNode())
11292 // Load the result.
11293 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11294 FIST, StackSlot, MachinePointerInfo(),
11295 false, false, false, 0);
11297 // The node is the result.
11301 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11303 MVT VT = Op.getSimpleValueType();
11304 SDValue In = Op.getOperand(0);
11305 MVT SVT = In.getSimpleValueType();
11307 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11309 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11310 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11311 In, DAG.getUNDEF(SVT)));
11314 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11315 LLVMContext *Context = DAG.getContext();
11317 MVT VT = Op.getSimpleValueType();
11319 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11320 if (VT.isVector()) {
11321 EltVT = VT.getVectorElementType();
11322 NumElts = VT.getVectorNumElements();
11325 if (EltVT == MVT::f64)
11326 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11327 APInt(64, ~(1ULL << 63))));
11329 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11330 APInt(32, ~(1U << 31))));
11331 C = ConstantVector::getSplat(NumElts, C);
11332 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11333 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11334 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11335 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11336 MachinePointerInfo::getConstantPool(),
11337 false, false, false, Alignment);
11338 if (VT.isVector()) {
11339 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11340 return DAG.getNode(ISD::BITCAST, dl, VT,
11341 DAG.getNode(ISD::AND, dl, ANDVT,
11342 DAG.getNode(ISD::BITCAST, dl, ANDVT,
11344 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11346 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11349 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11350 LLVMContext *Context = DAG.getContext();
11352 MVT VT = Op.getSimpleValueType();
11354 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11355 if (VT.isVector()) {
11356 EltVT = VT.getVectorElementType();
11357 NumElts = VT.getVectorNumElements();
11360 if (EltVT == MVT::f64)
11361 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11362 APInt(64, 1ULL << 63)));
11364 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11365 APInt(32, 1U << 31)));
11366 C = ConstantVector::getSplat(NumElts, C);
11367 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11368 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11369 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11370 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11371 MachinePointerInfo::getConstantPool(),
11372 false, false, false, Alignment);
11373 if (VT.isVector()) {
11374 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11375 return DAG.getNode(ISD::BITCAST, dl, VT,
11376 DAG.getNode(ISD::XOR, dl, XORVT,
11377 DAG.getNode(ISD::BITCAST, dl, XORVT,
11379 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11382 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11385 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11386 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11387 LLVMContext *Context = DAG.getContext();
11388 SDValue Op0 = Op.getOperand(0);
11389 SDValue Op1 = Op.getOperand(1);
11391 MVT VT = Op.getSimpleValueType();
11392 MVT SrcVT = Op1.getSimpleValueType();
11394 // If second operand is smaller, extend it first.
11395 if (SrcVT.bitsLT(VT)) {
11396 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11399 // And if it is bigger, shrink it first.
11400 if (SrcVT.bitsGT(VT)) {
11401 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11405 // At this point the operands and the result should have the same
11406 // type, and that won't be f80 since that is not custom lowered.
11408 // First get the sign bit of second operand.
11409 SmallVector<Constant*,4> CV;
11410 if (SrcVT == MVT::f64) {
11411 const fltSemantics &Sem = APFloat::IEEEdouble;
11412 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11413 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11415 const fltSemantics &Sem = APFloat::IEEEsingle;
11416 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11417 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11418 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11419 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11421 Constant *C = ConstantVector::get(CV);
11422 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11423 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11424 MachinePointerInfo::getConstantPool(),
11425 false, false, false, 16);
11426 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11428 // Shift sign bit right or left if the two operands have different types.
11429 if (SrcVT.bitsGT(VT)) {
11430 // Op0 is MVT::f32, Op1 is MVT::f64.
11431 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11432 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11433 DAG.getConstant(32, MVT::i32));
11434 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11435 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11436 DAG.getIntPtrConstant(0));
11439 // Clear first operand sign bit.
11441 if (VT == MVT::f64) {
11442 const fltSemantics &Sem = APFloat::IEEEdouble;
11443 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11444 APInt(64, ~(1ULL << 63)))));
11445 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11447 const fltSemantics &Sem = APFloat::IEEEsingle;
11448 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11449 APInt(32, ~(1U << 31)))));
11450 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11451 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11452 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11454 C = ConstantVector::get(CV);
11455 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11456 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11457 MachinePointerInfo::getConstantPool(),
11458 false, false, false, 16);
11459 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11461 // Or the value with the sign bit.
11462 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11465 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11466 SDValue N0 = Op.getOperand(0);
11468 MVT VT = Op.getSimpleValueType();
11470 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11471 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11472 DAG.getConstant(1, VT));
11473 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11476 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11478 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11479 SelectionDAG &DAG) {
11480 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11482 if (!Subtarget->hasSSE41())
11485 if (!Op->hasOneUse())
11488 SDNode *N = Op.getNode();
11491 SmallVector<SDValue, 8> Opnds;
11492 DenseMap<SDValue, unsigned> VecInMap;
11493 SmallVector<SDValue, 8> VecIns;
11494 EVT VT = MVT::Other;
11496 // Recognize a special case where a vector is casted into wide integer to
11498 Opnds.push_back(N->getOperand(0));
11499 Opnds.push_back(N->getOperand(1));
11501 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11502 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11503 // BFS traverse all OR'd operands.
11504 if (I->getOpcode() == ISD::OR) {
11505 Opnds.push_back(I->getOperand(0));
11506 Opnds.push_back(I->getOperand(1));
11507 // Re-evaluate the number of nodes to be traversed.
11508 e += 2; // 2 more nodes (LHS and RHS) are pushed.
11512 // Quit if a non-EXTRACT_VECTOR_ELT
11513 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11516 // Quit if without a constant index.
11517 SDValue Idx = I->getOperand(1);
11518 if (!isa<ConstantSDNode>(Idx))
11521 SDValue ExtractedFromVec = I->getOperand(0);
11522 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11523 if (M == VecInMap.end()) {
11524 VT = ExtractedFromVec.getValueType();
11525 // Quit if not 128/256-bit vector.
11526 if (!VT.is128BitVector() && !VT.is256BitVector())
11528 // Quit if not the same type.
11529 if (VecInMap.begin() != VecInMap.end() &&
11530 VT != VecInMap.begin()->first.getValueType())
11532 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11533 VecIns.push_back(ExtractedFromVec);
11535 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11538 assert((VT.is128BitVector() || VT.is256BitVector()) &&
11539 "Not extracted from 128-/256-bit vector.");
11541 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11543 for (DenseMap<SDValue, unsigned>::const_iterator
11544 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11545 // Quit if not all elements are used.
11546 if (I->second != FullMask)
11550 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11552 // Cast all vectors into TestVT for PTEST.
11553 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11554 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11556 // If more than one full vectors are evaluated, OR them first before PTEST.
11557 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11558 // Each iteration will OR 2 nodes and append the result until there is only
11559 // 1 node left, i.e. the final OR'd value of all vectors.
11560 SDValue LHS = VecIns[Slot];
11561 SDValue RHS = VecIns[Slot + 1];
11562 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11565 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11566 VecIns.back(), VecIns.back());
11569 /// \brief return true if \c Op has a use that doesn't just read flags.
11570 static bool hasNonFlagsUse(SDValue Op) {
11571 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11573 SDNode *User = *UI;
11574 unsigned UOpNo = UI.getOperandNo();
11575 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11576 // Look pass truncate.
11577 UOpNo = User->use_begin().getOperandNo();
11578 User = *User->use_begin();
11581 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11582 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11588 /// Emit nodes that will be selected as "test Op0,Op0", or something
11590 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11591 SelectionDAG &DAG) const {
11592 if (Op.getValueType() == MVT::i1)
11593 // KORTEST instruction should be selected
11594 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11595 DAG.getConstant(0, Op.getValueType()));
11597 // CF and OF aren't always set the way we want. Determine which
11598 // of these we need.
11599 bool NeedCF = false;
11600 bool NeedOF = false;
11603 case X86::COND_A: case X86::COND_AE:
11604 case X86::COND_B: case X86::COND_BE:
11607 case X86::COND_G: case X86::COND_GE:
11608 case X86::COND_L: case X86::COND_LE:
11609 case X86::COND_O: case X86::COND_NO: {
11610 // Check if we really need to set the
11611 // Overflow flag. If NoSignedWrap is present
11612 // that is not actually needed.
11613 switch (Op->getOpcode()) {
11618 const BinaryWithFlagsSDNode *BinNode =
11619 cast<BinaryWithFlagsSDNode>(Op.getNode());
11620 if (BinNode->hasNoSignedWrap())
11630 // See if we can use the EFLAGS value from the operand instead of
11631 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11632 // we prove that the arithmetic won't overflow, we can't use OF or CF.
11633 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11634 // Emit a CMP with 0, which is the TEST pattern.
11635 //if (Op.getValueType() == MVT::i1)
11636 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11637 // DAG.getConstant(0, MVT::i1));
11638 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11639 DAG.getConstant(0, Op.getValueType()));
11641 unsigned Opcode = 0;
11642 unsigned NumOperands = 0;
11644 // Truncate operations may prevent the merge of the SETCC instruction
11645 // and the arithmetic instruction before it. Attempt to truncate the operands
11646 // of the arithmetic instruction and use a reduced bit-width instruction.
11647 bool NeedTruncation = false;
11648 SDValue ArithOp = Op;
11649 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11650 SDValue Arith = Op->getOperand(0);
11651 // Both the trunc and the arithmetic op need to have one user each.
11652 if (Arith->hasOneUse())
11653 switch (Arith.getOpcode()) {
11660 NeedTruncation = true;
11666 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11667 // which may be the result of a CAST. We use the variable 'Op', which is the
11668 // non-casted variable when we check for possible users.
11669 switch (ArithOp.getOpcode()) {
11671 // Due to an isel shortcoming, be conservative if this add is likely to be
11672 // selected as part of a load-modify-store instruction. When the root node
11673 // in a match is a store, isel doesn't know how to remap non-chain non-flag
11674 // uses of other nodes in the match, such as the ADD in this case. This
11675 // leads to the ADD being left around and reselected, with the result being
11676 // two adds in the output. Alas, even if none our users are stores, that
11677 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
11678 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
11679 // climbing the DAG back to the root, and it doesn't seem to be worth the
11681 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11682 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11683 if (UI->getOpcode() != ISD::CopyToReg &&
11684 UI->getOpcode() != ISD::SETCC &&
11685 UI->getOpcode() != ISD::STORE)
11688 if (ConstantSDNode *C =
11689 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11690 // An add of one will be selected as an INC.
11691 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11692 Opcode = X86ISD::INC;
11697 // An add of negative one (subtract of one) will be selected as a DEC.
11698 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11699 Opcode = X86ISD::DEC;
11705 // Otherwise use a regular EFLAGS-setting add.
11706 Opcode = X86ISD::ADD;
11711 // If we have a constant logical shift that's only used in a comparison
11712 // against zero turn it into an equivalent AND. This allows turning it into
11713 // a TEST instruction later.
11714 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11715 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11716 EVT VT = Op.getValueType();
11717 unsigned BitWidth = VT.getSizeInBits();
11718 unsigned ShAmt = Op->getConstantOperandVal(1);
11719 if (ShAmt >= BitWidth) // Avoid undefined shifts.
11721 APInt Mask = ArithOp.getOpcode() == ISD::SRL
11722 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11723 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11724 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11726 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11727 DAG.getConstant(Mask, VT));
11728 DAG.ReplaceAllUsesWith(Op, New);
11734 // If the primary and result isn't used, don't bother using X86ISD::AND,
11735 // because a TEST instruction will be better.
11736 if (!hasNonFlagsUse(Op))
11742 // Due to the ISEL shortcoming noted above, be conservative if this op is
11743 // likely to be selected as part of a load-modify-store instruction.
11744 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11745 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11746 if (UI->getOpcode() == ISD::STORE)
11749 // Otherwise use a regular EFLAGS-setting instruction.
11750 switch (ArithOp.getOpcode()) {
11751 default: llvm_unreachable("unexpected operator!");
11752 case ISD::SUB: Opcode = X86ISD::SUB; break;
11753 case ISD::XOR: Opcode = X86ISD::XOR; break;
11754 case ISD::AND: Opcode = X86ISD::AND; break;
11756 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11757 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11758 if (EFLAGS.getNode())
11761 Opcode = X86ISD::OR;
11775 return SDValue(Op.getNode(), 1);
11781 // If we found that truncation is beneficial, perform the truncation and
11783 if (NeedTruncation) {
11784 EVT VT = Op.getValueType();
11785 SDValue WideVal = Op->getOperand(0);
11786 EVT WideVT = WideVal.getValueType();
11787 unsigned ConvertedOp = 0;
11788 // Use a target machine opcode to prevent further DAGCombine
11789 // optimizations that may separate the arithmetic operations
11790 // from the setcc node.
11791 switch (WideVal.getOpcode()) {
11793 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11794 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11795 case ISD::AND: ConvertedOp = X86ISD::AND; break;
11796 case ISD::OR: ConvertedOp = X86ISD::OR; break;
11797 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11801 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11802 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11803 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11804 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11805 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11811 // Emit a CMP with 0, which is the TEST pattern.
11812 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11813 DAG.getConstant(0, Op.getValueType()));
11815 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11816 SmallVector<SDValue, 4> Ops;
11817 for (unsigned i = 0; i != NumOperands; ++i)
11818 Ops.push_back(Op.getOperand(i));
11820 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11821 DAG.ReplaceAllUsesWith(Op, New);
11822 return SDValue(New.getNode(), 1);
11825 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11827 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11828 SDLoc dl, SelectionDAG &DAG) const {
11829 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11830 if (C->getAPIntValue() == 0)
11831 return EmitTest(Op0, X86CC, dl, DAG);
11833 if (Op0.getValueType() == MVT::i1)
11834 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11837 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11838 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11839 // Do the comparison at i32 if it's smaller, besides the Atom case.
11840 // This avoids subregister aliasing issues. Keep the smaller reference
11841 // if we're optimizing for size, however, as that'll allow better folding
11842 // of memory operations.
11843 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11844 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11845 AttributeSet::FunctionIndex, Attribute::MinSize) &&
11846 !Subtarget->isAtom()) {
11847 unsigned ExtendOp =
11848 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11849 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11850 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11852 // Use SUB instead of CMP to enable CSE between SUB and CMP.
11853 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11854 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11856 return SDValue(Sub.getNode(), 1);
11858 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11861 /// Convert a comparison if required by the subtarget.
11862 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11863 SelectionDAG &DAG) const {
11864 // If the subtarget does not support the FUCOMI instruction, floating-point
11865 // comparisons have to be converted.
11866 if (Subtarget->hasCMov() ||
11867 Cmp.getOpcode() != X86ISD::CMP ||
11868 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11869 !Cmp.getOperand(1).getValueType().isFloatingPoint())
11872 // The instruction selector will select an FUCOM instruction instead of
11873 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11874 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11875 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11877 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11878 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11879 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11880 DAG.getConstant(8, MVT::i8));
11881 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11882 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11885 static bool isAllOnes(SDValue V) {
11886 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11887 return C && C->isAllOnesValue();
11890 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11891 /// if it's possible.
11892 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11893 SDLoc dl, SelectionDAG &DAG) const {
11894 SDValue Op0 = And.getOperand(0);
11895 SDValue Op1 = And.getOperand(1);
11896 if (Op0.getOpcode() == ISD::TRUNCATE)
11897 Op0 = Op0.getOperand(0);
11898 if (Op1.getOpcode() == ISD::TRUNCATE)
11899 Op1 = Op1.getOperand(0);
11902 if (Op1.getOpcode() == ISD::SHL)
11903 std::swap(Op0, Op1);
11904 if (Op0.getOpcode() == ISD::SHL) {
11905 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11906 if (And00C->getZExtValue() == 1) {
11907 // If we looked past a truncate, check that it's only truncating away
11909 unsigned BitWidth = Op0.getValueSizeInBits();
11910 unsigned AndBitWidth = And.getValueSizeInBits();
11911 if (BitWidth > AndBitWidth) {
11913 DAG.computeKnownBits(Op0, Zeros, Ones);
11914 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11918 RHS = Op0.getOperand(1);
11920 } else if (Op1.getOpcode() == ISD::Constant) {
11921 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11922 uint64_t AndRHSVal = AndRHS->getZExtValue();
11923 SDValue AndLHS = Op0;
11925 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
11926 LHS = AndLHS.getOperand(0);
11927 RHS = AndLHS.getOperand(1);
11930 // Use BT if the immediate can't be encoded in a TEST instruction.
11931 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
11933 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
11937 if (LHS.getNode()) {
11938 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
11939 // instruction. Since the shift amount is in-range-or-undefined, we know
11940 // that doing a bittest on the i32 value is ok. We extend to i32 because
11941 // the encoding for the i16 version is larger than the i32 version.
11942 // Also promote i16 to i32 for performance / code size reason.
11943 if (LHS.getValueType() == MVT::i8 ||
11944 LHS.getValueType() == MVT::i16)
11945 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
11947 // If the operand types disagree, extend the shift amount to match. Since
11948 // BT ignores high bits (like shifts) we can use anyextend.
11949 if (LHS.getValueType() != RHS.getValueType())
11950 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
11952 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
11953 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
11954 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11955 DAG.getConstant(Cond, MVT::i8), BT);
11961 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
11963 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
11968 // SSE Condition code mapping:
11977 switch (SetCCOpcode) {
11978 default: llvm_unreachable("Unexpected SETCC condition");
11980 case ISD::SETEQ: SSECC = 0; break;
11982 case ISD::SETGT: Swap = true; // Fallthrough
11984 case ISD::SETOLT: SSECC = 1; break;
11986 case ISD::SETGE: Swap = true; // Fallthrough
11988 case ISD::SETOLE: SSECC = 2; break;
11989 case ISD::SETUO: SSECC = 3; break;
11991 case ISD::SETNE: SSECC = 4; break;
11992 case ISD::SETULE: Swap = true; // Fallthrough
11993 case ISD::SETUGE: SSECC = 5; break;
11994 case ISD::SETULT: Swap = true; // Fallthrough
11995 case ISD::SETUGT: SSECC = 6; break;
11996 case ISD::SETO: SSECC = 7; break;
11998 case ISD::SETONE: SSECC = 8; break;
12001 std::swap(Op0, Op1);
12006 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12007 // ones, and then concatenate the result back.
12008 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12009 MVT VT = Op.getSimpleValueType();
12011 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12012 "Unsupported value type for operation");
12014 unsigned NumElems = VT.getVectorNumElements();
12016 SDValue CC = Op.getOperand(2);
12018 // Extract the LHS vectors
12019 SDValue LHS = Op.getOperand(0);
12020 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12021 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12023 // Extract the RHS vectors
12024 SDValue RHS = Op.getOperand(1);
12025 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12026 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12028 // Issue the operation on the smaller types and concatenate the result back
12029 MVT EltVT = VT.getVectorElementType();
12030 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12031 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12032 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12033 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12036 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12037 const X86Subtarget *Subtarget) {
12038 SDValue Op0 = Op.getOperand(0);
12039 SDValue Op1 = Op.getOperand(1);
12040 SDValue CC = Op.getOperand(2);
12041 MVT VT = Op.getSimpleValueType();
12044 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12045 Op.getValueType().getScalarType() == MVT::i1 &&
12046 "Cannot set masked compare for this operation");
12048 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12050 bool Unsigned = false;
12053 switch (SetCCOpcode) {
12054 default: llvm_unreachable("Unexpected SETCC condition");
12055 case ISD::SETNE: SSECC = 4; break;
12056 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12057 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12058 case ISD::SETLT: Swap = true; //fall-through
12059 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12060 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12061 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12062 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12063 case ISD::SETULE: Unsigned = true; //fall-through
12064 case ISD::SETLE: SSECC = 2; break;
12068 std::swap(Op0, Op1);
12070 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12071 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12072 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12073 DAG.getConstant(SSECC, MVT::i8));
12076 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12077 /// operand \p Op1. If non-trivial (for example because it's not constant)
12078 /// return an empty value.
12079 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12081 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12085 MVT VT = Op1.getSimpleValueType();
12086 MVT EVT = VT.getVectorElementType();
12087 unsigned n = VT.getVectorNumElements();
12088 SmallVector<SDValue, 8> ULTOp1;
12090 for (unsigned i = 0; i < n; ++i) {
12091 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12092 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12095 // Avoid underflow.
12096 APInt Val = Elt->getAPIntValue();
12100 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12103 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12106 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12107 SelectionDAG &DAG) {
12108 SDValue Op0 = Op.getOperand(0);
12109 SDValue Op1 = Op.getOperand(1);
12110 SDValue CC = Op.getOperand(2);
12111 MVT VT = Op.getSimpleValueType();
12112 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12113 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12118 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12119 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12122 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12123 unsigned Opc = X86ISD::CMPP;
12124 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12125 assert(VT.getVectorNumElements() <= 16);
12126 Opc = X86ISD::CMPM;
12128 // In the two special cases we can't handle, emit two comparisons.
12131 unsigned CombineOpc;
12132 if (SetCCOpcode == ISD::SETUEQ) {
12133 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12135 assert(SetCCOpcode == ISD::SETONE);
12136 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12139 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12140 DAG.getConstant(CC0, MVT::i8));
12141 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12142 DAG.getConstant(CC1, MVT::i8));
12143 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12145 // Handle all other FP comparisons here.
12146 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12147 DAG.getConstant(SSECC, MVT::i8));
12150 // Break 256-bit integer vector compare into smaller ones.
12151 if (VT.is256BitVector() && !Subtarget->hasInt256())
12152 return Lower256IntVSETCC(Op, DAG);
12154 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12155 EVT OpVT = Op1.getValueType();
12156 if (Subtarget->hasAVX512()) {
12157 if (Op1.getValueType().is512BitVector() ||
12158 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12159 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12161 // In AVX-512 architecture setcc returns mask with i1 elements,
12162 // But there is no compare instruction for i8 and i16 elements.
12163 // We are not talking about 512-bit operands in this case, these
12164 // types are illegal.
12166 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12167 OpVT.getVectorElementType().getSizeInBits() >= 8))
12168 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12169 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12172 // We are handling one of the integer comparisons here. Since SSE only has
12173 // GT and EQ comparisons for integer, swapping operands and multiple
12174 // operations may be required for some comparisons.
12176 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12177 bool Subus = false;
12179 switch (SetCCOpcode) {
12180 default: llvm_unreachable("Unexpected SETCC condition");
12181 case ISD::SETNE: Invert = true;
12182 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12183 case ISD::SETLT: Swap = true;
12184 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12185 case ISD::SETGE: Swap = true;
12186 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12187 Invert = true; break;
12188 case ISD::SETULT: Swap = true;
12189 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12190 FlipSigns = true; break;
12191 case ISD::SETUGE: Swap = true;
12192 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12193 FlipSigns = true; Invert = true; break;
12196 // Special case: Use min/max operations for SETULE/SETUGE
12197 MVT VET = VT.getVectorElementType();
12199 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12200 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12203 switch (SetCCOpcode) {
12205 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12206 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12209 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12212 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12213 if (!MinMax && hasSubus) {
12214 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12216 // t = psubus Op0, Op1
12217 // pcmpeq t, <0..0>
12218 switch (SetCCOpcode) {
12220 case ISD::SETULT: {
12221 // If the comparison is against a constant we can turn this into a
12222 // setule. With psubus, setule does not require a swap. This is
12223 // beneficial because the constant in the register is no longer
12224 // destructed as the destination so it can be hoisted out of a loop.
12225 // Only do this pre-AVX since vpcmp* is no longer destructive.
12226 if (Subtarget->hasAVX())
12228 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12229 if (ULEOp1.getNode()) {
12231 Subus = true; Invert = false; Swap = false;
12235 // Psubus is better than flip-sign because it requires no inversion.
12236 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
12237 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12241 Opc = X86ISD::SUBUS;
12247 std::swap(Op0, Op1);
12249 // Check that the operation in question is available (most are plain SSE2,
12250 // but PCMPGTQ and PCMPEQQ have different requirements).
12251 if (VT == MVT::v2i64) {
12252 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12253 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12255 // First cast everything to the right type.
12256 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12257 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12259 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12260 // bits of the inputs before performing those operations. The lower
12261 // compare is always unsigned.
12264 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12266 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12267 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12268 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12269 Sign, Zero, Sign, Zero);
12271 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12272 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12274 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12275 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12276 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12278 // Create masks for only the low parts/high parts of the 64 bit integers.
12279 static const int MaskHi[] = { 1, 1, 3, 3 };
12280 static const int MaskLo[] = { 0, 0, 2, 2 };
12281 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12282 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12283 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12285 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12286 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12289 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12291 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12294 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12295 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12296 // pcmpeqd + pshufd + pand.
12297 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12299 // First cast everything to the right type.
12300 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12301 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12304 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12306 // Make sure the lower and upper halves are both all-ones.
12307 static const int Mask[] = { 1, 0, 3, 2 };
12308 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12309 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12312 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12314 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12318 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12319 // bits of the inputs before performing those operations.
12321 EVT EltVT = VT.getVectorElementType();
12322 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12323 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12324 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12327 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12329 // If the logical-not of the result is required, perform that now.
12331 Result = DAG.getNOT(dl, Result, VT);
12334 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12337 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12338 getZeroVector(VT, Subtarget, DAG, dl));
12343 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12345 MVT VT = Op.getSimpleValueType();
12347 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12349 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12350 && "SetCC type must be 8-bit or 1-bit integer");
12351 SDValue Op0 = Op.getOperand(0);
12352 SDValue Op1 = Op.getOperand(1);
12354 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12356 // Optimize to BT if possible.
12357 // Lower (X & (1 << N)) == 0 to BT(X, N).
12358 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12359 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12360 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12361 Op1.getOpcode() == ISD::Constant &&
12362 cast<ConstantSDNode>(Op1)->isNullValue() &&
12363 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12364 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12365 if (NewSetCC.getNode())
12369 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
12371 if (Op1.getOpcode() == ISD::Constant &&
12372 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12373 cast<ConstantSDNode>(Op1)->isNullValue()) &&
12374 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12376 // If the input is a setcc, then reuse the input setcc or use a new one with
12377 // the inverted condition.
12378 if (Op0.getOpcode() == X86ISD::SETCC) {
12379 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12380 bool Invert = (CC == ISD::SETNE) ^
12381 cast<ConstantSDNode>(Op1)->isNullValue();
12385 CCode = X86::GetOppositeBranchCondition(CCode);
12386 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12387 DAG.getConstant(CCode, MVT::i8),
12388 Op0.getOperand(1));
12390 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12394 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12395 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12396 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12398 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12399 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12402 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12403 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12404 if (X86CC == X86::COND_INVALID)
12407 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12408 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12409 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12410 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12412 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12416 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12417 static bool isX86LogicalCmp(SDValue Op) {
12418 unsigned Opc = Op.getNode()->getOpcode();
12419 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12420 Opc == X86ISD::SAHF)
12422 if (Op.getResNo() == 1 &&
12423 (Opc == X86ISD::ADD ||
12424 Opc == X86ISD::SUB ||
12425 Opc == X86ISD::ADC ||
12426 Opc == X86ISD::SBB ||
12427 Opc == X86ISD::SMUL ||
12428 Opc == X86ISD::UMUL ||
12429 Opc == X86ISD::INC ||
12430 Opc == X86ISD::DEC ||
12431 Opc == X86ISD::OR ||
12432 Opc == X86ISD::XOR ||
12433 Opc == X86ISD::AND))
12436 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12442 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12443 if (V.getOpcode() != ISD::TRUNCATE)
12446 SDValue VOp0 = V.getOperand(0);
12447 unsigned InBits = VOp0.getValueSizeInBits();
12448 unsigned Bits = V.getValueSizeInBits();
12449 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12452 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12453 bool addTest = true;
12454 SDValue Cond = Op.getOperand(0);
12455 SDValue Op1 = Op.getOperand(1);
12456 SDValue Op2 = Op.getOperand(2);
12458 EVT VT = Op1.getValueType();
12461 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12462 // are available. Otherwise fp cmovs get lowered into a less efficient branch
12463 // sequence later on.
12464 if (Cond.getOpcode() == ISD::SETCC &&
12465 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12466 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12467 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12468 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12469 int SSECC = translateX86FSETCC(
12470 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12473 if (Subtarget->hasAVX512()) {
12474 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12475 DAG.getConstant(SSECC, MVT::i8));
12476 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12478 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12479 DAG.getConstant(SSECC, MVT::i8));
12480 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12481 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12482 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12486 if (Cond.getOpcode() == ISD::SETCC) {
12487 SDValue NewCond = LowerSETCC(Cond, DAG);
12488 if (NewCond.getNode())
12492 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12493 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12494 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12495 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12496 if (Cond.getOpcode() == X86ISD::SETCC &&
12497 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12498 isZero(Cond.getOperand(1).getOperand(1))) {
12499 SDValue Cmp = Cond.getOperand(1);
12501 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12503 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12504 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12505 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12507 SDValue CmpOp0 = Cmp.getOperand(0);
12508 // Apply further optimizations for special cases
12509 // (select (x != 0), -1, 0) -> neg & sbb
12510 // (select (x == 0), 0, -1) -> neg & sbb
12511 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12512 if (YC->isNullValue() &&
12513 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12514 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12515 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12516 DAG.getConstant(0, CmpOp0.getValueType()),
12518 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12519 DAG.getConstant(X86::COND_B, MVT::i8),
12520 SDValue(Neg.getNode(), 1));
12524 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12525 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12526 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12528 SDValue Res = // Res = 0 or -1.
12529 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12530 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12532 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12533 Res = DAG.getNOT(DL, Res, Res.getValueType());
12535 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12536 if (!N2C || !N2C->isNullValue())
12537 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12542 // Look past (and (setcc_carry (cmp ...)), 1).
12543 if (Cond.getOpcode() == ISD::AND &&
12544 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12545 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12546 if (C && C->getAPIntValue() == 1)
12547 Cond = Cond.getOperand(0);
12550 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12551 // setting operand in place of the X86ISD::SETCC.
12552 unsigned CondOpcode = Cond.getOpcode();
12553 if (CondOpcode == X86ISD::SETCC ||
12554 CondOpcode == X86ISD::SETCC_CARRY) {
12555 CC = Cond.getOperand(0);
12557 SDValue Cmp = Cond.getOperand(1);
12558 unsigned Opc = Cmp.getOpcode();
12559 MVT VT = Op.getSimpleValueType();
12561 bool IllegalFPCMov = false;
12562 if (VT.isFloatingPoint() && !VT.isVector() &&
12563 !isScalarFPTypeInSSEReg(VT)) // FPStack?
12564 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12566 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12567 Opc == X86ISD::BT) { // FIXME
12571 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12572 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12573 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12574 Cond.getOperand(0).getValueType() != MVT::i8)) {
12575 SDValue LHS = Cond.getOperand(0);
12576 SDValue RHS = Cond.getOperand(1);
12577 unsigned X86Opcode;
12580 switch (CondOpcode) {
12581 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12582 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12583 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12584 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12585 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12586 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12587 default: llvm_unreachable("unexpected overflowing operator");
12589 if (CondOpcode == ISD::UMULO)
12590 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12593 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12595 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12597 if (CondOpcode == ISD::UMULO)
12598 Cond = X86Op.getValue(2);
12600 Cond = X86Op.getValue(1);
12602 CC = DAG.getConstant(X86Cond, MVT::i8);
12607 // Look pass the truncate if the high bits are known zero.
12608 if (isTruncWithZeroHighBitsInput(Cond, DAG))
12609 Cond = Cond.getOperand(0);
12611 // We know the result of AND is compared against zero. Try to match
12613 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12614 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12615 if (NewSetCC.getNode()) {
12616 CC = NewSetCC.getOperand(0);
12617 Cond = NewSetCC.getOperand(1);
12624 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12625 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12628 // a < b ? -1 : 0 -> RES = ~setcc_carry
12629 // a < b ? 0 : -1 -> RES = setcc_carry
12630 // a >= b ? -1 : 0 -> RES = setcc_carry
12631 // a >= b ? 0 : -1 -> RES = ~setcc_carry
12632 if (Cond.getOpcode() == X86ISD::SUB) {
12633 Cond = ConvertCmpIfNecessary(Cond, DAG);
12634 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12636 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12637 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12638 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12639 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12640 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12641 return DAG.getNOT(DL, Res, Res.getValueType());
12646 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12647 // widen the cmov and push the truncate through. This avoids introducing a new
12648 // branch during isel and doesn't add any extensions.
12649 if (Op.getValueType() == MVT::i8 &&
12650 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12651 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12652 if (T1.getValueType() == T2.getValueType() &&
12653 // Blacklist CopyFromReg to avoid partial register stalls.
12654 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12655 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12656 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12657 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12661 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12662 // condition is true.
12663 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12664 SDValue Ops[] = { Op2, Op1, CC, Cond };
12665 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12668 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12669 MVT VT = Op->getSimpleValueType(0);
12670 SDValue In = Op->getOperand(0);
12671 MVT InVT = In.getSimpleValueType();
12674 unsigned int NumElts = VT.getVectorNumElements();
12675 if (NumElts != 8 && NumElts != 16)
12678 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12679 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12681 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12682 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12684 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12685 Constant *C = ConstantInt::get(*DAG.getContext(),
12686 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12688 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12689 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12690 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12691 MachinePointerInfo::getConstantPool(),
12692 false, false, false, Alignment);
12693 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12694 if (VT.is512BitVector())
12696 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12699 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12700 SelectionDAG &DAG) {
12701 MVT VT = Op->getSimpleValueType(0);
12702 SDValue In = Op->getOperand(0);
12703 MVT InVT = In.getSimpleValueType();
12706 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12707 return LowerSIGN_EXTEND_AVX512(Op, DAG);
12709 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12710 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12711 (VT != MVT::v16i16 || InVT != MVT::v16i8))
12714 if (Subtarget->hasInt256())
12715 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12717 // Optimize vectors in AVX mode
12718 // Sign extend v8i16 to v8i32 and
12721 // Divide input vector into two parts
12722 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12723 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12724 // concat the vectors to original VT
12726 unsigned NumElems = InVT.getVectorNumElements();
12727 SDValue Undef = DAG.getUNDEF(InVT);
12729 SmallVector<int,8> ShufMask1(NumElems, -1);
12730 for (unsigned i = 0; i != NumElems/2; ++i)
12733 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12735 SmallVector<int,8> ShufMask2(NumElems, -1);
12736 for (unsigned i = 0; i != NumElems/2; ++i)
12737 ShufMask2[i] = i + NumElems/2;
12739 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12741 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12742 VT.getVectorNumElements()/2);
12744 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12745 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12747 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12750 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12751 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12752 // from the AND / OR.
12753 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12754 Opc = Op.getOpcode();
12755 if (Opc != ISD::OR && Opc != ISD::AND)
12757 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12758 Op.getOperand(0).hasOneUse() &&
12759 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12760 Op.getOperand(1).hasOneUse());
12763 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12764 // 1 and that the SETCC node has a single use.
12765 static bool isXor1OfSetCC(SDValue Op) {
12766 if (Op.getOpcode() != ISD::XOR)
12768 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12769 if (N1C && N1C->getAPIntValue() == 1) {
12770 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12771 Op.getOperand(0).hasOneUse();
12776 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12777 bool addTest = true;
12778 SDValue Chain = Op.getOperand(0);
12779 SDValue Cond = Op.getOperand(1);
12780 SDValue Dest = Op.getOperand(2);
12783 bool Inverted = false;
12785 if (Cond.getOpcode() == ISD::SETCC) {
12786 // Check for setcc([su]{add,sub,mul}o == 0).
12787 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12788 isa<ConstantSDNode>(Cond.getOperand(1)) &&
12789 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12790 Cond.getOperand(0).getResNo() == 1 &&
12791 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12792 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12793 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12794 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12795 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12796 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12798 Cond = Cond.getOperand(0);
12800 SDValue NewCond = LowerSETCC(Cond, DAG);
12801 if (NewCond.getNode())
12806 // FIXME: LowerXALUO doesn't handle these!!
12807 else if (Cond.getOpcode() == X86ISD::ADD ||
12808 Cond.getOpcode() == X86ISD::SUB ||
12809 Cond.getOpcode() == X86ISD::SMUL ||
12810 Cond.getOpcode() == X86ISD::UMUL)
12811 Cond = LowerXALUO(Cond, DAG);
12814 // Look pass (and (setcc_carry (cmp ...)), 1).
12815 if (Cond.getOpcode() == ISD::AND &&
12816 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12817 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12818 if (C && C->getAPIntValue() == 1)
12819 Cond = Cond.getOperand(0);
12822 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12823 // setting operand in place of the X86ISD::SETCC.
12824 unsigned CondOpcode = Cond.getOpcode();
12825 if (CondOpcode == X86ISD::SETCC ||
12826 CondOpcode == X86ISD::SETCC_CARRY) {
12827 CC = Cond.getOperand(0);
12829 SDValue Cmp = Cond.getOperand(1);
12830 unsigned Opc = Cmp.getOpcode();
12831 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12832 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12836 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12840 // These can only come from an arithmetic instruction with overflow,
12841 // e.g. SADDO, UADDO.
12842 Cond = Cond.getNode()->getOperand(1);
12848 CondOpcode = Cond.getOpcode();
12849 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12850 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12851 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12852 Cond.getOperand(0).getValueType() != MVT::i8)) {
12853 SDValue LHS = Cond.getOperand(0);
12854 SDValue RHS = Cond.getOperand(1);
12855 unsigned X86Opcode;
12858 // Keep this in sync with LowerXALUO, otherwise we might create redundant
12859 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12861 switch (CondOpcode) {
12862 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12864 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12866 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12869 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12870 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12872 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12874 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12877 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12878 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12879 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12880 default: llvm_unreachable("unexpected overflowing operator");
12883 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12884 if (CondOpcode == ISD::UMULO)
12885 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12888 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12890 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12892 if (CondOpcode == ISD::UMULO)
12893 Cond = X86Op.getValue(2);
12895 Cond = X86Op.getValue(1);
12897 CC = DAG.getConstant(X86Cond, MVT::i8);
12901 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12902 SDValue Cmp = Cond.getOperand(0).getOperand(1);
12903 if (CondOpc == ISD::OR) {
12904 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12905 // two branches instead of an explicit OR instruction with a
12907 if (Cmp == Cond.getOperand(1).getOperand(1) &&
12908 isX86LogicalCmp(Cmp)) {
12909 CC = Cond.getOperand(0).getOperand(0);
12910 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12911 Chain, Dest, CC, Cmp);
12912 CC = Cond.getOperand(1).getOperand(0);
12916 } else { // ISD::AND
12917 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12918 // two branches instead of an explicit AND instruction with a
12919 // separate test. However, we only do this if this block doesn't
12920 // have a fall-through edge, because this requires an explicit
12921 // jmp when the condition is false.
12922 if (Cmp == Cond.getOperand(1).getOperand(1) &&
12923 isX86LogicalCmp(Cmp) &&
12924 Op.getNode()->hasOneUse()) {
12925 X86::CondCode CCode =
12926 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12927 CCode = X86::GetOppositeBranchCondition(CCode);
12928 CC = DAG.getConstant(CCode, MVT::i8);
12929 SDNode *User = *Op.getNode()->use_begin();
12930 // Look for an unconditional branch following this conditional branch.
12931 // We need this because we need to reverse the successors in order
12932 // to implement FCMP_OEQ.
12933 if (User->getOpcode() == ISD::BR) {
12934 SDValue FalseBB = User->getOperand(1);
12936 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12937 assert(NewBR == User);
12941 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12942 Chain, Dest, CC, Cmp);
12943 X86::CondCode CCode =
12944 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
12945 CCode = X86::GetOppositeBranchCondition(CCode);
12946 CC = DAG.getConstant(CCode, MVT::i8);
12952 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
12953 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
12954 // It should be transformed during dag combiner except when the condition
12955 // is set by a arithmetics with overflow node.
12956 X86::CondCode CCode =
12957 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12958 CCode = X86::GetOppositeBranchCondition(CCode);
12959 CC = DAG.getConstant(CCode, MVT::i8);
12960 Cond = Cond.getOperand(0).getOperand(1);
12962 } else if (Cond.getOpcode() == ISD::SETCC &&
12963 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
12964 // For FCMP_OEQ, we can emit
12965 // two branches instead of an explicit AND instruction with a
12966 // separate test. However, we only do this if this block doesn't
12967 // have a fall-through edge, because this requires an explicit
12968 // jmp when the condition is false.
12969 if (Op.getNode()->hasOneUse()) {
12970 SDNode *User = *Op.getNode()->use_begin();
12971 // Look for an unconditional branch following this conditional branch.
12972 // We need this because we need to reverse the successors in order
12973 // to implement FCMP_OEQ.
12974 if (User->getOpcode() == ISD::BR) {
12975 SDValue FalseBB = User->getOperand(1);
12977 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12978 assert(NewBR == User);
12982 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12983 Cond.getOperand(0), Cond.getOperand(1));
12984 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12985 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12986 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12987 Chain, Dest, CC, Cmp);
12988 CC = DAG.getConstant(X86::COND_P, MVT::i8);
12993 } else if (Cond.getOpcode() == ISD::SETCC &&
12994 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
12995 // For FCMP_UNE, we can emit
12996 // two branches instead of an explicit AND instruction with a
12997 // separate test. However, we only do this if this block doesn't
12998 // have a fall-through edge, because this requires an explicit
12999 // jmp when the condition is false.
13000 if (Op.getNode()->hasOneUse()) {
13001 SDNode *User = *Op.getNode()->use_begin();
13002 // Look for an unconditional branch following this conditional branch.
13003 // We need this because we need to reverse the successors in order
13004 // to implement FCMP_UNE.
13005 if (User->getOpcode() == ISD::BR) {
13006 SDValue FalseBB = User->getOperand(1);
13008 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13009 assert(NewBR == User);
13012 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13013 Cond.getOperand(0), Cond.getOperand(1));
13014 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13015 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13016 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13017 Chain, Dest, CC, Cmp);
13018 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13028 // Look pass the truncate if the high bits are known zero.
13029 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13030 Cond = Cond.getOperand(0);
13032 // We know the result of AND is compared against zero. Try to match
13034 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13035 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13036 if (NewSetCC.getNode()) {
13037 CC = NewSetCC.getOperand(0);
13038 Cond = NewSetCC.getOperand(1);
13045 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13046 CC = DAG.getConstant(X86Cond, MVT::i8);
13047 Cond = EmitTest(Cond, X86Cond, dl, DAG);
13049 Cond = ConvertCmpIfNecessary(Cond, DAG);
13050 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13051 Chain, Dest, CC, Cond);
13054 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13055 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13056 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13057 // that the guard pages used by the OS virtual memory manager are allocated in
13058 // correct sequence.
13060 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13061 SelectionDAG &DAG) const {
13062 MachineFunction &MF = DAG.getMachineFunction();
13063 bool SplitStack = MF.shouldSplitStack();
13064 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13069 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13070 SDNode* Node = Op.getNode();
13072 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13073 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13074 " not tell us which reg is the stack pointer!");
13075 EVT VT = Node->getValueType(0);
13076 SDValue Tmp1 = SDValue(Node, 0);
13077 SDValue Tmp2 = SDValue(Node, 1);
13078 SDValue Tmp3 = Node->getOperand(2);
13079 SDValue Chain = Tmp1.getOperand(0);
13081 // Chain the dynamic stack allocation so that it doesn't modify the stack
13082 // pointer when other instructions are using the stack.
13083 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13086 SDValue Size = Tmp2.getOperand(1);
13087 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13088 Chain = SP.getValue(1);
13089 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13090 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13091 unsigned StackAlign = TFI.getStackAlignment();
13092 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13093 if (Align > StackAlign)
13094 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13095 DAG.getConstant(-(uint64_t)Align, VT));
13096 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13098 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13099 DAG.getIntPtrConstant(0, true), SDValue(),
13102 SDValue Ops[2] = { Tmp1, Tmp2 };
13103 return DAG.getMergeValues(Ops, dl);
13107 SDValue Chain = Op.getOperand(0);
13108 SDValue Size = Op.getOperand(1);
13109 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13110 EVT VT = Op.getNode()->getValueType(0);
13112 bool Is64Bit = Subtarget->is64Bit();
13113 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13116 MachineRegisterInfo &MRI = MF.getRegInfo();
13119 // The 64 bit implementation of segmented stacks needs to clobber both r10
13120 // r11. This makes it impossible to use it along with nested parameters.
13121 const Function *F = MF.getFunction();
13123 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13125 if (I->hasNestAttr())
13126 report_fatal_error("Cannot use segmented stacks with functions that "
13127 "have nested arguments.");
13130 const TargetRegisterClass *AddrRegClass =
13131 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13132 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13133 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13134 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13135 DAG.getRegister(Vreg, SPTy));
13136 SDValue Ops1[2] = { Value, Chain };
13137 return DAG.getMergeValues(Ops1, dl);
13140 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13142 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13143 Flag = Chain.getValue(1);
13144 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13146 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13148 const X86RegisterInfo *RegInfo =
13149 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13150 unsigned SPReg = RegInfo->getStackRegister();
13151 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13152 Chain = SP.getValue(1);
13155 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13156 DAG.getConstant(-(uint64_t)Align, VT));
13157 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13160 SDValue Ops1[2] = { SP, Chain };
13161 return DAG.getMergeValues(Ops1, dl);
13165 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13166 MachineFunction &MF = DAG.getMachineFunction();
13167 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13169 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13172 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13173 // vastart just stores the address of the VarArgsFrameIndex slot into the
13174 // memory location argument.
13175 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13177 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13178 MachinePointerInfo(SV), false, false, 0);
13182 // gp_offset (0 - 6 * 8)
13183 // fp_offset (48 - 48 + 8 * 16)
13184 // overflow_arg_area (point to parameters coming in memory).
13186 SmallVector<SDValue, 8> MemOps;
13187 SDValue FIN = Op.getOperand(1);
13189 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13190 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13192 FIN, MachinePointerInfo(SV), false, false, 0);
13193 MemOps.push_back(Store);
13196 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13197 FIN, DAG.getIntPtrConstant(4));
13198 Store = DAG.getStore(Op.getOperand(0), DL,
13199 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13201 FIN, MachinePointerInfo(SV, 4), false, false, 0);
13202 MemOps.push_back(Store);
13204 // Store ptr to overflow_arg_area
13205 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13206 FIN, DAG.getIntPtrConstant(4));
13207 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13209 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13210 MachinePointerInfo(SV, 8),
13212 MemOps.push_back(Store);
13214 // Store ptr to reg_save_area.
13215 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13216 FIN, DAG.getIntPtrConstant(8));
13217 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13219 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13220 MachinePointerInfo(SV, 16), false, false, 0);
13221 MemOps.push_back(Store);
13222 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13225 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13226 assert(Subtarget->is64Bit() &&
13227 "LowerVAARG only handles 64-bit va_arg!");
13228 assert((Subtarget->isTargetLinux() ||
13229 Subtarget->isTargetDarwin()) &&
13230 "Unhandled target in LowerVAARG");
13231 assert(Op.getNode()->getNumOperands() == 4);
13232 SDValue Chain = Op.getOperand(0);
13233 SDValue SrcPtr = Op.getOperand(1);
13234 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13235 unsigned Align = Op.getConstantOperandVal(3);
13238 EVT ArgVT = Op.getNode()->getValueType(0);
13239 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13240 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13243 // Decide which area this value should be read from.
13244 // TODO: Implement the AMD64 ABI in its entirety. This simple
13245 // selection mechanism works only for the basic types.
13246 if (ArgVT == MVT::f80) {
13247 llvm_unreachable("va_arg for f80 not yet implemented");
13248 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13249 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
13250 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13251 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
13253 llvm_unreachable("Unhandled argument type in LowerVAARG");
13256 if (ArgMode == 2) {
13257 // Sanity Check: Make sure using fp_offset makes sense.
13258 assert(!DAG.getTarget().Options.UseSoftFloat &&
13259 !(DAG.getMachineFunction()
13260 .getFunction()->getAttributes()
13261 .hasAttribute(AttributeSet::FunctionIndex,
13262 Attribute::NoImplicitFloat)) &&
13263 Subtarget->hasSSE1());
13266 // Insert VAARG_64 node into the DAG
13267 // VAARG_64 returns two values: Variable Argument Address, Chain
13268 SmallVector<SDValue, 11> InstOps;
13269 InstOps.push_back(Chain);
13270 InstOps.push_back(SrcPtr);
13271 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13272 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13273 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13274 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13275 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13276 VTs, InstOps, MVT::i64,
13277 MachinePointerInfo(SV),
13279 /*Volatile=*/false,
13281 /*WriteMem=*/true);
13282 Chain = VAARG.getValue(1);
13284 // Load the next argument and return it
13285 return DAG.getLoad(ArgVT, dl,
13288 MachinePointerInfo(),
13289 false, false, false, 0);
13292 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13293 SelectionDAG &DAG) {
13294 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13295 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13296 SDValue Chain = Op.getOperand(0);
13297 SDValue DstPtr = Op.getOperand(1);
13298 SDValue SrcPtr = Op.getOperand(2);
13299 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13300 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13303 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13304 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13306 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13309 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13310 // amount is a constant. Takes immediate version of shift as input.
13311 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13312 SDValue SrcOp, uint64_t ShiftAmt,
13313 SelectionDAG &DAG) {
13314 MVT ElementType = VT.getVectorElementType();
13316 // Fold this packed shift into its first operand if ShiftAmt is 0.
13320 // Check for ShiftAmt >= element width
13321 if (ShiftAmt >= ElementType.getSizeInBits()) {
13322 if (Opc == X86ISD::VSRAI)
13323 ShiftAmt = ElementType.getSizeInBits() - 1;
13325 return DAG.getConstant(0, VT);
13328 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13329 && "Unknown target vector shift-by-constant node");
13331 // Fold this packed vector shift into a build vector if SrcOp is a
13332 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13333 if (VT == SrcOp.getSimpleValueType() &&
13334 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13335 SmallVector<SDValue, 8> Elts;
13336 unsigned NumElts = SrcOp->getNumOperands();
13337 ConstantSDNode *ND;
13340 default: llvm_unreachable(nullptr);
13341 case X86ISD::VSHLI:
13342 for (unsigned i=0; i!=NumElts; ++i) {
13343 SDValue CurrentOp = SrcOp->getOperand(i);
13344 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13345 Elts.push_back(CurrentOp);
13348 ND = cast<ConstantSDNode>(CurrentOp);
13349 const APInt &C = ND->getAPIntValue();
13350 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13353 case X86ISD::VSRLI:
13354 for (unsigned i=0; i!=NumElts; ++i) {
13355 SDValue CurrentOp = SrcOp->getOperand(i);
13356 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13357 Elts.push_back(CurrentOp);
13360 ND = cast<ConstantSDNode>(CurrentOp);
13361 const APInt &C = ND->getAPIntValue();
13362 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13365 case X86ISD::VSRAI:
13366 for (unsigned i=0; i!=NumElts; ++i) {
13367 SDValue CurrentOp = SrcOp->getOperand(i);
13368 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13369 Elts.push_back(CurrentOp);
13372 ND = cast<ConstantSDNode>(CurrentOp);
13373 const APInt &C = ND->getAPIntValue();
13374 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13379 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13382 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13385 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13386 // may or may not be a constant. Takes immediate version of shift as input.
13387 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13388 SDValue SrcOp, SDValue ShAmt,
13389 SelectionDAG &DAG) {
13390 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13392 // Catch shift-by-constant.
13393 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13394 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13395 CShAmt->getZExtValue(), DAG);
13397 // Change opcode to non-immediate version
13399 default: llvm_unreachable("Unknown target vector shift node");
13400 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13401 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13402 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13405 // Need to build a vector containing shift amount
13406 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13409 ShOps[1] = DAG.getConstant(0, MVT::i32);
13410 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13411 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13413 // The return type has to be a 128-bit type with the same element
13414 // type as the input type.
13415 MVT EltVT = VT.getVectorElementType();
13416 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13418 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13419 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13422 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13424 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13426 default: return SDValue(); // Don't custom lower most intrinsics.
13427 // Comparison intrinsics.
13428 case Intrinsic::x86_sse_comieq_ss:
13429 case Intrinsic::x86_sse_comilt_ss:
13430 case Intrinsic::x86_sse_comile_ss:
13431 case Intrinsic::x86_sse_comigt_ss:
13432 case Intrinsic::x86_sse_comige_ss:
13433 case Intrinsic::x86_sse_comineq_ss:
13434 case Intrinsic::x86_sse_ucomieq_ss:
13435 case Intrinsic::x86_sse_ucomilt_ss:
13436 case Intrinsic::x86_sse_ucomile_ss:
13437 case Intrinsic::x86_sse_ucomigt_ss:
13438 case Intrinsic::x86_sse_ucomige_ss:
13439 case Intrinsic::x86_sse_ucomineq_ss:
13440 case Intrinsic::x86_sse2_comieq_sd:
13441 case Intrinsic::x86_sse2_comilt_sd:
13442 case Intrinsic::x86_sse2_comile_sd:
13443 case Intrinsic::x86_sse2_comigt_sd:
13444 case Intrinsic::x86_sse2_comige_sd:
13445 case Intrinsic::x86_sse2_comineq_sd:
13446 case Intrinsic::x86_sse2_ucomieq_sd:
13447 case Intrinsic::x86_sse2_ucomilt_sd:
13448 case Intrinsic::x86_sse2_ucomile_sd:
13449 case Intrinsic::x86_sse2_ucomigt_sd:
13450 case Intrinsic::x86_sse2_ucomige_sd:
13451 case Intrinsic::x86_sse2_ucomineq_sd: {
13455 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13456 case Intrinsic::x86_sse_comieq_ss:
13457 case Intrinsic::x86_sse2_comieq_sd:
13458 Opc = X86ISD::COMI;
13461 case Intrinsic::x86_sse_comilt_ss:
13462 case Intrinsic::x86_sse2_comilt_sd:
13463 Opc = X86ISD::COMI;
13466 case Intrinsic::x86_sse_comile_ss:
13467 case Intrinsic::x86_sse2_comile_sd:
13468 Opc = X86ISD::COMI;
13471 case Intrinsic::x86_sse_comigt_ss:
13472 case Intrinsic::x86_sse2_comigt_sd:
13473 Opc = X86ISD::COMI;
13476 case Intrinsic::x86_sse_comige_ss:
13477 case Intrinsic::x86_sse2_comige_sd:
13478 Opc = X86ISD::COMI;
13481 case Intrinsic::x86_sse_comineq_ss:
13482 case Intrinsic::x86_sse2_comineq_sd:
13483 Opc = X86ISD::COMI;
13486 case Intrinsic::x86_sse_ucomieq_ss:
13487 case Intrinsic::x86_sse2_ucomieq_sd:
13488 Opc = X86ISD::UCOMI;
13491 case Intrinsic::x86_sse_ucomilt_ss:
13492 case Intrinsic::x86_sse2_ucomilt_sd:
13493 Opc = X86ISD::UCOMI;
13496 case Intrinsic::x86_sse_ucomile_ss:
13497 case Intrinsic::x86_sse2_ucomile_sd:
13498 Opc = X86ISD::UCOMI;
13501 case Intrinsic::x86_sse_ucomigt_ss:
13502 case Intrinsic::x86_sse2_ucomigt_sd:
13503 Opc = X86ISD::UCOMI;
13506 case Intrinsic::x86_sse_ucomige_ss:
13507 case Intrinsic::x86_sse2_ucomige_sd:
13508 Opc = X86ISD::UCOMI;
13511 case Intrinsic::x86_sse_ucomineq_ss:
13512 case Intrinsic::x86_sse2_ucomineq_sd:
13513 Opc = X86ISD::UCOMI;
13518 SDValue LHS = Op.getOperand(1);
13519 SDValue RHS = Op.getOperand(2);
13520 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13521 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13522 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13523 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13524 DAG.getConstant(X86CC, MVT::i8), Cond);
13525 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13528 // Arithmetic intrinsics.
13529 case Intrinsic::x86_sse2_pmulu_dq:
13530 case Intrinsic::x86_avx2_pmulu_dq:
13531 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13532 Op.getOperand(1), Op.getOperand(2));
13534 case Intrinsic::x86_sse41_pmuldq:
13535 case Intrinsic::x86_avx2_pmul_dq:
13536 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13537 Op.getOperand(1), Op.getOperand(2));
13539 case Intrinsic::x86_sse2_pmulhu_w:
13540 case Intrinsic::x86_avx2_pmulhu_w:
13541 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13542 Op.getOperand(1), Op.getOperand(2));
13544 case Intrinsic::x86_sse2_pmulh_w:
13545 case Intrinsic::x86_avx2_pmulh_w:
13546 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13547 Op.getOperand(1), Op.getOperand(2));
13549 // SSE2/AVX2 sub with unsigned saturation intrinsics
13550 case Intrinsic::x86_sse2_psubus_b:
13551 case Intrinsic::x86_sse2_psubus_w:
13552 case Intrinsic::x86_avx2_psubus_b:
13553 case Intrinsic::x86_avx2_psubus_w:
13554 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13555 Op.getOperand(1), Op.getOperand(2));
13557 // SSE3/AVX horizontal add/sub intrinsics
13558 case Intrinsic::x86_sse3_hadd_ps:
13559 case Intrinsic::x86_sse3_hadd_pd:
13560 case Intrinsic::x86_avx_hadd_ps_256:
13561 case Intrinsic::x86_avx_hadd_pd_256:
13562 case Intrinsic::x86_sse3_hsub_ps:
13563 case Intrinsic::x86_sse3_hsub_pd:
13564 case Intrinsic::x86_avx_hsub_ps_256:
13565 case Intrinsic::x86_avx_hsub_pd_256:
13566 case Intrinsic::x86_ssse3_phadd_w_128:
13567 case Intrinsic::x86_ssse3_phadd_d_128:
13568 case Intrinsic::x86_avx2_phadd_w:
13569 case Intrinsic::x86_avx2_phadd_d:
13570 case Intrinsic::x86_ssse3_phsub_w_128:
13571 case Intrinsic::x86_ssse3_phsub_d_128:
13572 case Intrinsic::x86_avx2_phsub_w:
13573 case Intrinsic::x86_avx2_phsub_d: {
13576 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13577 case Intrinsic::x86_sse3_hadd_ps:
13578 case Intrinsic::x86_sse3_hadd_pd:
13579 case Intrinsic::x86_avx_hadd_ps_256:
13580 case Intrinsic::x86_avx_hadd_pd_256:
13581 Opcode = X86ISD::FHADD;
13583 case Intrinsic::x86_sse3_hsub_ps:
13584 case Intrinsic::x86_sse3_hsub_pd:
13585 case Intrinsic::x86_avx_hsub_ps_256:
13586 case Intrinsic::x86_avx_hsub_pd_256:
13587 Opcode = X86ISD::FHSUB;
13589 case Intrinsic::x86_ssse3_phadd_w_128:
13590 case Intrinsic::x86_ssse3_phadd_d_128:
13591 case Intrinsic::x86_avx2_phadd_w:
13592 case Intrinsic::x86_avx2_phadd_d:
13593 Opcode = X86ISD::HADD;
13595 case Intrinsic::x86_ssse3_phsub_w_128:
13596 case Intrinsic::x86_ssse3_phsub_d_128:
13597 case Intrinsic::x86_avx2_phsub_w:
13598 case Intrinsic::x86_avx2_phsub_d:
13599 Opcode = X86ISD::HSUB;
13602 return DAG.getNode(Opcode, dl, Op.getValueType(),
13603 Op.getOperand(1), Op.getOperand(2));
13606 // SSE2/SSE41/AVX2 integer max/min intrinsics.
13607 case Intrinsic::x86_sse2_pmaxu_b:
13608 case Intrinsic::x86_sse41_pmaxuw:
13609 case Intrinsic::x86_sse41_pmaxud:
13610 case Intrinsic::x86_avx2_pmaxu_b:
13611 case Intrinsic::x86_avx2_pmaxu_w:
13612 case Intrinsic::x86_avx2_pmaxu_d:
13613 case Intrinsic::x86_sse2_pminu_b:
13614 case Intrinsic::x86_sse41_pminuw:
13615 case Intrinsic::x86_sse41_pminud:
13616 case Intrinsic::x86_avx2_pminu_b:
13617 case Intrinsic::x86_avx2_pminu_w:
13618 case Intrinsic::x86_avx2_pminu_d:
13619 case Intrinsic::x86_sse41_pmaxsb:
13620 case Intrinsic::x86_sse2_pmaxs_w:
13621 case Intrinsic::x86_sse41_pmaxsd:
13622 case Intrinsic::x86_avx2_pmaxs_b:
13623 case Intrinsic::x86_avx2_pmaxs_w:
13624 case Intrinsic::x86_avx2_pmaxs_d:
13625 case Intrinsic::x86_sse41_pminsb:
13626 case Intrinsic::x86_sse2_pmins_w:
13627 case Intrinsic::x86_sse41_pminsd:
13628 case Intrinsic::x86_avx2_pmins_b:
13629 case Intrinsic::x86_avx2_pmins_w:
13630 case Intrinsic::x86_avx2_pmins_d: {
13633 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13634 case Intrinsic::x86_sse2_pmaxu_b:
13635 case Intrinsic::x86_sse41_pmaxuw:
13636 case Intrinsic::x86_sse41_pmaxud:
13637 case Intrinsic::x86_avx2_pmaxu_b:
13638 case Intrinsic::x86_avx2_pmaxu_w:
13639 case Intrinsic::x86_avx2_pmaxu_d:
13640 Opcode = X86ISD::UMAX;
13642 case Intrinsic::x86_sse2_pminu_b:
13643 case Intrinsic::x86_sse41_pminuw:
13644 case Intrinsic::x86_sse41_pminud:
13645 case Intrinsic::x86_avx2_pminu_b:
13646 case Intrinsic::x86_avx2_pminu_w:
13647 case Intrinsic::x86_avx2_pminu_d:
13648 Opcode = X86ISD::UMIN;
13650 case Intrinsic::x86_sse41_pmaxsb:
13651 case Intrinsic::x86_sse2_pmaxs_w:
13652 case Intrinsic::x86_sse41_pmaxsd:
13653 case Intrinsic::x86_avx2_pmaxs_b:
13654 case Intrinsic::x86_avx2_pmaxs_w:
13655 case Intrinsic::x86_avx2_pmaxs_d:
13656 Opcode = X86ISD::SMAX;
13658 case Intrinsic::x86_sse41_pminsb:
13659 case Intrinsic::x86_sse2_pmins_w:
13660 case Intrinsic::x86_sse41_pminsd:
13661 case Intrinsic::x86_avx2_pmins_b:
13662 case Intrinsic::x86_avx2_pmins_w:
13663 case Intrinsic::x86_avx2_pmins_d:
13664 Opcode = X86ISD::SMIN;
13667 return DAG.getNode(Opcode, dl, Op.getValueType(),
13668 Op.getOperand(1), Op.getOperand(2));
13671 // SSE/SSE2/AVX floating point max/min intrinsics.
13672 case Intrinsic::x86_sse_max_ps:
13673 case Intrinsic::x86_sse2_max_pd:
13674 case Intrinsic::x86_avx_max_ps_256:
13675 case Intrinsic::x86_avx_max_pd_256:
13676 case Intrinsic::x86_sse_min_ps:
13677 case Intrinsic::x86_sse2_min_pd:
13678 case Intrinsic::x86_avx_min_ps_256:
13679 case Intrinsic::x86_avx_min_pd_256: {
13682 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13683 case Intrinsic::x86_sse_max_ps:
13684 case Intrinsic::x86_sse2_max_pd:
13685 case Intrinsic::x86_avx_max_ps_256:
13686 case Intrinsic::x86_avx_max_pd_256:
13687 Opcode = X86ISD::FMAX;
13689 case Intrinsic::x86_sse_min_ps:
13690 case Intrinsic::x86_sse2_min_pd:
13691 case Intrinsic::x86_avx_min_ps_256:
13692 case Intrinsic::x86_avx_min_pd_256:
13693 Opcode = X86ISD::FMIN;
13696 return DAG.getNode(Opcode, dl, Op.getValueType(),
13697 Op.getOperand(1), Op.getOperand(2));
13700 // AVX2 variable shift intrinsics
13701 case Intrinsic::x86_avx2_psllv_d:
13702 case Intrinsic::x86_avx2_psllv_q:
13703 case Intrinsic::x86_avx2_psllv_d_256:
13704 case Intrinsic::x86_avx2_psllv_q_256:
13705 case Intrinsic::x86_avx2_psrlv_d:
13706 case Intrinsic::x86_avx2_psrlv_q:
13707 case Intrinsic::x86_avx2_psrlv_d_256:
13708 case Intrinsic::x86_avx2_psrlv_q_256:
13709 case Intrinsic::x86_avx2_psrav_d:
13710 case Intrinsic::x86_avx2_psrav_d_256: {
13713 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13714 case Intrinsic::x86_avx2_psllv_d:
13715 case Intrinsic::x86_avx2_psllv_q:
13716 case Intrinsic::x86_avx2_psllv_d_256:
13717 case Intrinsic::x86_avx2_psllv_q_256:
13720 case Intrinsic::x86_avx2_psrlv_d:
13721 case Intrinsic::x86_avx2_psrlv_q:
13722 case Intrinsic::x86_avx2_psrlv_d_256:
13723 case Intrinsic::x86_avx2_psrlv_q_256:
13726 case Intrinsic::x86_avx2_psrav_d:
13727 case Intrinsic::x86_avx2_psrav_d_256:
13731 return DAG.getNode(Opcode, dl, Op.getValueType(),
13732 Op.getOperand(1), Op.getOperand(2));
13735 case Intrinsic::x86_sse2_packssdw_128:
13736 case Intrinsic::x86_sse2_packsswb_128:
13737 case Intrinsic::x86_avx2_packssdw:
13738 case Intrinsic::x86_avx2_packsswb:
13739 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13740 Op.getOperand(1), Op.getOperand(2));
13742 case Intrinsic::x86_sse2_packuswb_128:
13743 case Intrinsic::x86_sse41_packusdw:
13744 case Intrinsic::x86_avx2_packuswb:
13745 case Intrinsic::x86_avx2_packusdw:
13746 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13747 Op.getOperand(1), Op.getOperand(2));
13749 case Intrinsic::x86_ssse3_pshuf_b_128:
13750 case Intrinsic::x86_avx2_pshuf_b:
13751 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13752 Op.getOperand(1), Op.getOperand(2));
13754 case Intrinsic::x86_sse2_pshuf_d:
13755 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13756 Op.getOperand(1), Op.getOperand(2));
13758 case Intrinsic::x86_sse2_pshufl_w:
13759 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13760 Op.getOperand(1), Op.getOperand(2));
13762 case Intrinsic::x86_sse2_pshufh_w:
13763 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13764 Op.getOperand(1), Op.getOperand(2));
13766 case Intrinsic::x86_ssse3_psign_b_128:
13767 case Intrinsic::x86_ssse3_psign_w_128:
13768 case Intrinsic::x86_ssse3_psign_d_128:
13769 case Intrinsic::x86_avx2_psign_b:
13770 case Intrinsic::x86_avx2_psign_w:
13771 case Intrinsic::x86_avx2_psign_d:
13772 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13773 Op.getOperand(1), Op.getOperand(2));
13775 case Intrinsic::x86_sse41_insertps:
13776 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13777 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13779 case Intrinsic::x86_avx_vperm2f128_ps_256:
13780 case Intrinsic::x86_avx_vperm2f128_pd_256:
13781 case Intrinsic::x86_avx_vperm2f128_si_256:
13782 case Intrinsic::x86_avx2_vperm2i128:
13783 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13784 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13786 case Intrinsic::x86_avx2_permd:
13787 case Intrinsic::x86_avx2_permps:
13788 // Operands intentionally swapped. Mask is last operand to intrinsic,
13789 // but second operand for node/instruction.
13790 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13791 Op.getOperand(2), Op.getOperand(1));
13793 case Intrinsic::x86_sse_sqrt_ps:
13794 case Intrinsic::x86_sse2_sqrt_pd:
13795 case Intrinsic::x86_avx_sqrt_ps_256:
13796 case Intrinsic::x86_avx_sqrt_pd_256:
13797 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13799 // ptest and testp intrinsics. The intrinsic these come from are designed to
13800 // return an integer value, not just an instruction so lower it to the ptest
13801 // or testp pattern and a setcc for the result.
13802 case Intrinsic::x86_sse41_ptestz:
13803 case Intrinsic::x86_sse41_ptestc:
13804 case Intrinsic::x86_sse41_ptestnzc:
13805 case Intrinsic::x86_avx_ptestz_256:
13806 case Intrinsic::x86_avx_ptestc_256:
13807 case Intrinsic::x86_avx_ptestnzc_256:
13808 case Intrinsic::x86_avx_vtestz_ps:
13809 case Intrinsic::x86_avx_vtestc_ps:
13810 case Intrinsic::x86_avx_vtestnzc_ps:
13811 case Intrinsic::x86_avx_vtestz_pd:
13812 case Intrinsic::x86_avx_vtestc_pd:
13813 case Intrinsic::x86_avx_vtestnzc_pd:
13814 case Intrinsic::x86_avx_vtestz_ps_256:
13815 case Intrinsic::x86_avx_vtestc_ps_256:
13816 case Intrinsic::x86_avx_vtestnzc_ps_256:
13817 case Intrinsic::x86_avx_vtestz_pd_256:
13818 case Intrinsic::x86_avx_vtestc_pd_256:
13819 case Intrinsic::x86_avx_vtestnzc_pd_256: {
13820 bool IsTestPacked = false;
13823 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13824 case Intrinsic::x86_avx_vtestz_ps:
13825 case Intrinsic::x86_avx_vtestz_pd:
13826 case Intrinsic::x86_avx_vtestz_ps_256:
13827 case Intrinsic::x86_avx_vtestz_pd_256:
13828 IsTestPacked = true; // Fallthrough
13829 case Intrinsic::x86_sse41_ptestz:
13830 case Intrinsic::x86_avx_ptestz_256:
13832 X86CC = X86::COND_E;
13834 case Intrinsic::x86_avx_vtestc_ps:
13835 case Intrinsic::x86_avx_vtestc_pd:
13836 case Intrinsic::x86_avx_vtestc_ps_256:
13837 case Intrinsic::x86_avx_vtestc_pd_256:
13838 IsTestPacked = true; // Fallthrough
13839 case Intrinsic::x86_sse41_ptestc:
13840 case Intrinsic::x86_avx_ptestc_256:
13842 X86CC = X86::COND_B;
13844 case Intrinsic::x86_avx_vtestnzc_ps:
13845 case Intrinsic::x86_avx_vtestnzc_pd:
13846 case Intrinsic::x86_avx_vtestnzc_ps_256:
13847 case Intrinsic::x86_avx_vtestnzc_pd_256:
13848 IsTestPacked = true; // Fallthrough
13849 case Intrinsic::x86_sse41_ptestnzc:
13850 case Intrinsic::x86_avx_ptestnzc_256:
13852 X86CC = X86::COND_A;
13856 SDValue LHS = Op.getOperand(1);
13857 SDValue RHS = Op.getOperand(2);
13858 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13859 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13860 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13861 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13862 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13864 case Intrinsic::x86_avx512_kortestz_w:
13865 case Intrinsic::x86_avx512_kortestc_w: {
13866 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13867 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13868 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13869 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13870 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13871 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13872 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13875 // SSE/AVX shift intrinsics
13876 case Intrinsic::x86_sse2_psll_w:
13877 case Intrinsic::x86_sse2_psll_d:
13878 case Intrinsic::x86_sse2_psll_q:
13879 case Intrinsic::x86_avx2_psll_w:
13880 case Intrinsic::x86_avx2_psll_d:
13881 case Intrinsic::x86_avx2_psll_q:
13882 case Intrinsic::x86_sse2_psrl_w:
13883 case Intrinsic::x86_sse2_psrl_d:
13884 case Intrinsic::x86_sse2_psrl_q:
13885 case Intrinsic::x86_avx2_psrl_w:
13886 case Intrinsic::x86_avx2_psrl_d:
13887 case Intrinsic::x86_avx2_psrl_q:
13888 case Intrinsic::x86_sse2_psra_w:
13889 case Intrinsic::x86_sse2_psra_d:
13890 case Intrinsic::x86_avx2_psra_w:
13891 case Intrinsic::x86_avx2_psra_d: {
13894 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13895 case Intrinsic::x86_sse2_psll_w:
13896 case Intrinsic::x86_sse2_psll_d:
13897 case Intrinsic::x86_sse2_psll_q:
13898 case Intrinsic::x86_avx2_psll_w:
13899 case Intrinsic::x86_avx2_psll_d:
13900 case Intrinsic::x86_avx2_psll_q:
13901 Opcode = X86ISD::VSHL;
13903 case Intrinsic::x86_sse2_psrl_w:
13904 case Intrinsic::x86_sse2_psrl_d:
13905 case Intrinsic::x86_sse2_psrl_q:
13906 case Intrinsic::x86_avx2_psrl_w:
13907 case Intrinsic::x86_avx2_psrl_d:
13908 case Intrinsic::x86_avx2_psrl_q:
13909 Opcode = X86ISD::VSRL;
13911 case Intrinsic::x86_sse2_psra_w:
13912 case Intrinsic::x86_sse2_psra_d:
13913 case Intrinsic::x86_avx2_psra_w:
13914 case Intrinsic::x86_avx2_psra_d:
13915 Opcode = X86ISD::VSRA;
13918 return DAG.getNode(Opcode, dl, Op.getValueType(),
13919 Op.getOperand(1), Op.getOperand(2));
13922 // SSE/AVX immediate shift intrinsics
13923 case Intrinsic::x86_sse2_pslli_w:
13924 case Intrinsic::x86_sse2_pslli_d:
13925 case Intrinsic::x86_sse2_pslli_q:
13926 case Intrinsic::x86_avx2_pslli_w:
13927 case Intrinsic::x86_avx2_pslli_d:
13928 case Intrinsic::x86_avx2_pslli_q:
13929 case Intrinsic::x86_sse2_psrli_w:
13930 case Intrinsic::x86_sse2_psrli_d:
13931 case Intrinsic::x86_sse2_psrli_q:
13932 case Intrinsic::x86_avx2_psrli_w:
13933 case Intrinsic::x86_avx2_psrli_d:
13934 case Intrinsic::x86_avx2_psrli_q:
13935 case Intrinsic::x86_sse2_psrai_w:
13936 case Intrinsic::x86_sse2_psrai_d:
13937 case Intrinsic::x86_avx2_psrai_w:
13938 case Intrinsic::x86_avx2_psrai_d: {
13941 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13942 case Intrinsic::x86_sse2_pslli_w:
13943 case Intrinsic::x86_sse2_pslli_d:
13944 case Intrinsic::x86_sse2_pslli_q:
13945 case Intrinsic::x86_avx2_pslli_w:
13946 case Intrinsic::x86_avx2_pslli_d:
13947 case Intrinsic::x86_avx2_pslli_q:
13948 Opcode = X86ISD::VSHLI;
13950 case Intrinsic::x86_sse2_psrli_w:
13951 case Intrinsic::x86_sse2_psrli_d:
13952 case Intrinsic::x86_sse2_psrli_q:
13953 case Intrinsic::x86_avx2_psrli_w:
13954 case Intrinsic::x86_avx2_psrli_d:
13955 case Intrinsic::x86_avx2_psrli_q:
13956 Opcode = X86ISD::VSRLI;
13958 case Intrinsic::x86_sse2_psrai_w:
13959 case Intrinsic::x86_sse2_psrai_d:
13960 case Intrinsic::x86_avx2_psrai_w:
13961 case Intrinsic::x86_avx2_psrai_d:
13962 Opcode = X86ISD::VSRAI;
13965 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
13966 Op.getOperand(1), Op.getOperand(2), DAG);
13969 case Intrinsic::x86_sse42_pcmpistria128:
13970 case Intrinsic::x86_sse42_pcmpestria128:
13971 case Intrinsic::x86_sse42_pcmpistric128:
13972 case Intrinsic::x86_sse42_pcmpestric128:
13973 case Intrinsic::x86_sse42_pcmpistrio128:
13974 case Intrinsic::x86_sse42_pcmpestrio128:
13975 case Intrinsic::x86_sse42_pcmpistris128:
13976 case Intrinsic::x86_sse42_pcmpestris128:
13977 case Intrinsic::x86_sse42_pcmpistriz128:
13978 case Intrinsic::x86_sse42_pcmpestriz128: {
13982 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13983 case Intrinsic::x86_sse42_pcmpistria128:
13984 Opcode = X86ISD::PCMPISTRI;
13985 X86CC = X86::COND_A;
13987 case Intrinsic::x86_sse42_pcmpestria128:
13988 Opcode = X86ISD::PCMPESTRI;
13989 X86CC = X86::COND_A;
13991 case Intrinsic::x86_sse42_pcmpistric128:
13992 Opcode = X86ISD::PCMPISTRI;
13993 X86CC = X86::COND_B;
13995 case Intrinsic::x86_sse42_pcmpestric128:
13996 Opcode = X86ISD::PCMPESTRI;
13997 X86CC = X86::COND_B;
13999 case Intrinsic::x86_sse42_pcmpistrio128:
14000 Opcode = X86ISD::PCMPISTRI;
14001 X86CC = X86::COND_O;
14003 case Intrinsic::x86_sse42_pcmpestrio128:
14004 Opcode = X86ISD::PCMPESTRI;
14005 X86CC = X86::COND_O;
14007 case Intrinsic::x86_sse42_pcmpistris128:
14008 Opcode = X86ISD::PCMPISTRI;
14009 X86CC = X86::COND_S;
14011 case Intrinsic::x86_sse42_pcmpestris128:
14012 Opcode = X86ISD::PCMPESTRI;
14013 X86CC = X86::COND_S;
14015 case Intrinsic::x86_sse42_pcmpistriz128:
14016 Opcode = X86ISD::PCMPISTRI;
14017 X86CC = X86::COND_E;
14019 case Intrinsic::x86_sse42_pcmpestriz128:
14020 Opcode = X86ISD::PCMPESTRI;
14021 X86CC = X86::COND_E;
14024 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14025 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14026 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14027 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14028 DAG.getConstant(X86CC, MVT::i8),
14029 SDValue(PCMP.getNode(), 1));
14030 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14033 case Intrinsic::x86_sse42_pcmpistri128:
14034 case Intrinsic::x86_sse42_pcmpestri128: {
14036 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14037 Opcode = X86ISD::PCMPISTRI;
14039 Opcode = X86ISD::PCMPESTRI;
14041 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14042 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14043 return DAG.getNode(Opcode, dl, VTs, NewOps);
14045 case Intrinsic::x86_fma_vfmadd_ps:
14046 case Intrinsic::x86_fma_vfmadd_pd:
14047 case Intrinsic::x86_fma_vfmsub_ps:
14048 case Intrinsic::x86_fma_vfmsub_pd:
14049 case Intrinsic::x86_fma_vfnmadd_ps:
14050 case Intrinsic::x86_fma_vfnmadd_pd:
14051 case Intrinsic::x86_fma_vfnmsub_ps:
14052 case Intrinsic::x86_fma_vfnmsub_pd:
14053 case Intrinsic::x86_fma_vfmaddsub_ps:
14054 case Intrinsic::x86_fma_vfmaddsub_pd:
14055 case Intrinsic::x86_fma_vfmsubadd_ps:
14056 case Intrinsic::x86_fma_vfmsubadd_pd:
14057 case Intrinsic::x86_fma_vfmadd_ps_256:
14058 case Intrinsic::x86_fma_vfmadd_pd_256:
14059 case Intrinsic::x86_fma_vfmsub_ps_256:
14060 case Intrinsic::x86_fma_vfmsub_pd_256:
14061 case Intrinsic::x86_fma_vfnmadd_ps_256:
14062 case Intrinsic::x86_fma_vfnmadd_pd_256:
14063 case Intrinsic::x86_fma_vfnmsub_ps_256:
14064 case Intrinsic::x86_fma_vfnmsub_pd_256:
14065 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14066 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14067 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14068 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14069 case Intrinsic::x86_fma_vfmadd_ps_512:
14070 case Intrinsic::x86_fma_vfmadd_pd_512:
14071 case Intrinsic::x86_fma_vfmsub_ps_512:
14072 case Intrinsic::x86_fma_vfmsub_pd_512:
14073 case Intrinsic::x86_fma_vfnmadd_ps_512:
14074 case Intrinsic::x86_fma_vfnmadd_pd_512:
14075 case Intrinsic::x86_fma_vfnmsub_ps_512:
14076 case Intrinsic::x86_fma_vfnmsub_pd_512:
14077 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14078 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14079 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14080 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14083 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14084 case Intrinsic::x86_fma_vfmadd_ps:
14085 case Intrinsic::x86_fma_vfmadd_pd:
14086 case Intrinsic::x86_fma_vfmadd_ps_256:
14087 case Intrinsic::x86_fma_vfmadd_pd_256:
14088 case Intrinsic::x86_fma_vfmadd_ps_512:
14089 case Intrinsic::x86_fma_vfmadd_pd_512:
14090 Opc = X86ISD::FMADD;
14092 case Intrinsic::x86_fma_vfmsub_ps:
14093 case Intrinsic::x86_fma_vfmsub_pd:
14094 case Intrinsic::x86_fma_vfmsub_ps_256:
14095 case Intrinsic::x86_fma_vfmsub_pd_256:
14096 case Intrinsic::x86_fma_vfmsub_ps_512:
14097 case Intrinsic::x86_fma_vfmsub_pd_512:
14098 Opc = X86ISD::FMSUB;
14100 case Intrinsic::x86_fma_vfnmadd_ps:
14101 case Intrinsic::x86_fma_vfnmadd_pd:
14102 case Intrinsic::x86_fma_vfnmadd_ps_256:
14103 case Intrinsic::x86_fma_vfnmadd_pd_256:
14104 case Intrinsic::x86_fma_vfnmadd_ps_512:
14105 case Intrinsic::x86_fma_vfnmadd_pd_512:
14106 Opc = X86ISD::FNMADD;
14108 case Intrinsic::x86_fma_vfnmsub_ps:
14109 case Intrinsic::x86_fma_vfnmsub_pd:
14110 case Intrinsic::x86_fma_vfnmsub_ps_256:
14111 case Intrinsic::x86_fma_vfnmsub_pd_256:
14112 case Intrinsic::x86_fma_vfnmsub_ps_512:
14113 case Intrinsic::x86_fma_vfnmsub_pd_512:
14114 Opc = X86ISD::FNMSUB;
14116 case Intrinsic::x86_fma_vfmaddsub_ps:
14117 case Intrinsic::x86_fma_vfmaddsub_pd:
14118 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14119 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14120 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14121 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14122 Opc = X86ISD::FMADDSUB;
14124 case Intrinsic::x86_fma_vfmsubadd_ps:
14125 case Intrinsic::x86_fma_vfmsubadd_pd:
14126 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14127 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14128 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14129 case Intrinsic::x86_fma_vfmsubadd_pd_512:
14130 Opc = X86ISD::FMSUBADD;
14134 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14135 Op.getOperand(2), Op.getOperand(3));
14140 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14141 SDValue Src, SDValue Mask, SDValue Base,
14142 SDValue Index, SDValue ScaleOp, SDValue Chain,
14143 const X86Subtarget * Subtarget) {
14145 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14146 assert(C && "Invalid scale type");
14147 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14148 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14149 Index.getSimpleValueType().getVectorNumElements());
14151 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14153 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14155 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14156 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14157 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14158 SDValue Segment = DAG.getRegister(0, MVT::i32);
14159 if (Src.getOpcode() == ISD::UNDEF)
14160 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14161 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14162 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14163 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14164 return DAG.getMergeValues(RetOps, dl);
14167 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14168 SDValue Src, SDValue Mask, SDValue Base,
14169 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14171 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14172 assert(C && "Invalid scale type");
14173 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14174 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14175 SDValue Segment = DAG.getRegister(0, MVT::i32);
14176 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14177 Index.getSimpleValueType().getVectorNumElements());
14179 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14181 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14183 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14184 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14185 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14186 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14187 return SDValue(Res, 1);
14190 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14191 SDValue Mask, SDValue Base, SDValue Index,
14192 SDValue ScaleOp, SDValue Chain) {
14194 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14195 assert(C && "Invalid scale type");
14196 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14197 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14198 SDValue Segment = DAG.getRegister(0, MVT::i32);
14200 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14202 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14204 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14206 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14207 //SDVTList VTs = DAG.getVTList(MVT::Other);
14208 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14209 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14210 return SDValue(Res, 0);
14213 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14214 // read performance monitor counters (x86_rdpmc).
14215 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14216 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14217 SmallVectorImpl<SDValue> &Results) {
14218 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14219 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14222 // The ECX register is used to select the index of the performance counter
14224 SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14226 SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14228 // Reads the content of a 64-bit performance counter and returns it in the
14229 // registers EDX:EAX.
14230 if (Subtarget->is64Bit()) {
14231 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14232 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14235 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14236 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14239 Chain = HI.getValue(1);
14241 if (Subtarget->is64Bit()) {
14242 // The EAX register is loaded with the low-order 32 bits. The EDX register
14243 // is loaded with the supported high-order bits of the counter.
14244 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14245 DAG.getConstant(32, MVT::i8));
14246 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14247 Results.push_back(Chain);
14251 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14252 SDValue Ops[] = { LO, HI };
14253 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14254 Results.push_back(Pair);
14255 Results.push_back(Chain);
14258 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14259 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14260 // also used to custom lower READCYCLECOUNTER nodes.
14261 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14262 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14263 SmallVectorImpl<SDValue> &Results) {
14264 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14265 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14268 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14269 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14270 // and the EAX register is loaded with the low-order 32 bits.
14271 if (Subtarget->is64Bit()) {
14272 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14273 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14276 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14277 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14280 SDValue Chain = HI.getValue(1);
14282 if (Opcode == X86ISD::RDTSCP_DAG) {
14283 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14285 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14286 // the ECX register. Add 'ecx' explicitly to the chain.
14287 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14289 // Explicitly store the content of ECX at the location passed in input
14290 // to the 'rdtscp' intrinsic.
14291 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14292 MachinePointerInfo(), false, false, 0);
14295 if (Subtarget->is64Bit()) {
14296 // The EDX register is loaded with the high-order 32 bits of the MSR, and
14297 // the EAX register is loaded with the low-order 32 bits.
14298 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14299 DAG.getConstant(32, MVT::i8));
14300 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14301 Results.push_back(Chain);
14305 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14306 SDValue Ops[] = { LO, HI };
14307 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14308 Results.push_back(Pair);
14309 Results.push_back(Chain);
14312 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14313 SelectionDAG &DAG) {
14314 SmallVector<SDValue, 2> Results;
14316 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14318 return DAG.getMergeValues(Results, DL);
14321 enum IntrinsicType {
14322 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14325 struct IntrinsicData {
14326 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14327 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14328 IntrinsicType Type;
14333 std::map < unsigned, IntrinsicData> IntrMap;
14334 static void InitIntinsicsMap() {
14335 static bool Initialized = false;
14338 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14339 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14340 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14341 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14342 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14343 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14344 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14345 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14346 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14347 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14348 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
14349 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14350 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
14351 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14352 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
14353 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14354 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
14355 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14357 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14358 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14359 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
14360 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14361 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
14362 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14363 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
14364 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14365 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
14366 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14367 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
14368 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14369 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
14370 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14371 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
14372 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14374 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
14375 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14376 X86::VGATHERPF1QPSm)));
14377 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
14378 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14379 X86::VGATHERPF1QPDm)));
14380 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
14381 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14382 X86::VGATHERPF1DPDm)));
14383 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
14384 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14385 X86::VGATHERPF1DPSm)));
14386 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
14387 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14388 X86::VSCATTERPF1QPSm)));
14389 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
14390 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14391 X86::VSCATTERPF1QPDm)));
14392 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
14393 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14394 X86::VSCATTERPF1DPDm)));
14395 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
14396 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14397 X86::VSCATTERPF1DPSm)));
14398 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14399 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14400 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14401 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14402 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14403 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14404 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14405 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14406 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14407 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14408 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14409 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14410 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14411 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
14412 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14413 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
14414 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14415 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
14416 IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14417 IntrinsicData(RDPMC, X86ISD::RDPMC_DAG, 0)));
14418 Initialized = true;
14421 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14422 SelectionDAG &DAG) {
14423 InitIntinsicsMap();
14424 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14425 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14426 if (itr == IntrMap.end())
14430 IntrinsicData Intr = itr->second;
14431 switch(Intr.Type) {
14434 // Emit the node with the right value type.
14435 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14436 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14438 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14439 // Otherwise return the value from Rand, which is always 0, casted to i32.
14440 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14441 DAG.getConstant(1, Op->getValueType(1)),
14442 DAG.getConstant(X86::COND_B, MVT::i32),
14443 SDValue(Result.getNode(), 1) };
14444 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14445 DAG.getVTList(Op->getValueType(1), MVT::Glue),
14448 // Return { result, isValid, chain }.
14449 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14450 SDValue(Result.getNode(), 2));
14453 //gather(v1, mask, index, base, scale);
14454 SDValue Chain = Op.getOperand(0);
14455 SDValue Src = Op.getOperand(2);
14456 SDValue Base = Op.getOperand(3);
14457 SDValue Index = Op.getOperand(4);
14458 SDValue Mask = Op.getOperand(5);
14459 SDValue Scale = Op.getOperand(6);
14460 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14464 //scatter(base, mask, index, v1, scale);
14465 SDValue Chain = Op.getOperand(0);
14466 SDValue Base = Op.getOperand(2);
14467 SDValue Mask = Op.getOperand(3);
14468 SDValue Index = Op.getOperand(4);
14469 SDValue Src = Op.getOperand(5);
14470 SDValue Scale = Op.getOperand(6);
14471 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14474 SDValue Hint = Op.getOperand(6);
14476 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14477 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14478 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14479 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14480 SDValue Chain = Op.getOperand(0);
14481 SDValue Mask = Op.getOperand(2);
14482 SDValue Index = Op.getOperand(3);
14483 SDValue Base = Op.getOperand(4);
14484 SDValue Scale = Op.getOperand(5);
14485 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14487 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14489 SmallVector<SDValue, 2> Results;
14490 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14491 return DAG.getMergeValues(Results, dl);
14493 // Read Performance Monitoring Counters.
14495 SmallVector<SDValue, 2> Results;
14496 getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14497 return DAG.getMergeValues(Results, dl);
14499 // XTEST intrinsics.
14501 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14502 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14503 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14504 DAG.getConstant(X86::COND_NE, MVT::i8),
14506 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14507 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14508 Ret, SDValue(InTrans.getNode(), 1));
14511 llvm_unreachable("Unknown Intrinsic Type");
14514 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14515 SelectionDAG &DAG) const {
14516 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14517 MFI->setReturnAddressIsTaken(true);
14519 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14522 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14524 EVT PtrVT = getPointerTy();
14527 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14528 const X86RegisterInfo *RegInfo =
14529 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14530 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14531 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14532 DAG.getNode(ISD::ADD, dl, PtrVT,
14533 FrameAddr, Offset),
14534 MachinePointerInfo(), false, false, false, 0);
14537 // Just load the return address.
14538 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14539 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14540 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14543 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14544 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14545 MFI->setFrameAddressIsTaken(true);
14547 EVT VT = Op.getValueType();
14548 SDLoc dl(Op); // FIXME probably not meaningful
14549 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14550 const X86RegisterInfo *RegInfo =
14551 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14552 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14553 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14554 (FrameReg == X86::EBP && VT == MVT::i32)) &&
14555 "Invalid Frame Register!");
14556 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14558 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14559 MachinePointerInfo(),
14560 false, false, false, 0);
14564 // FIXME? Maybe this could be a TableGen attribute on some registers and
14565 // this table could be generated automatically from RegInfo.
14566 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14568 unsigned Reg = StringSwitch<unsigned>(RegName)
14569 .Case("esp", X86::ESP)
14570 .Case("rsp", X86::RSP)
14574 report_fatal_error("Invalid register name global variable");
14577 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14578 SelectionDAG &DAG) const {
14579 const X86RegisterInfo *RegInfo =
14580 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14581 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14584 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14585 SDValue Chain = Op.getOperand(0);
14586 SDValue Offset = Op.getOperand(1);
14587 SDValue Handler = Op.getOperand(2);
14590 EVT PtrVT = getPointerTy();
14591 const X86RegisterInfo *RegInfo =
14592 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14593 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14594 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14595 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14596 "Invalid Frame Register!");
14597 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14598 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14600 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14601 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14602 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14603 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14605 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14607 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14608 DAG.getRegister(StoreAddrReg, PtrVT));
14611 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14612 SelectionDAG &DAG) const {
14614 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14615 DAG.getVTList(MVT::i32, MVT::Other),
14616 Op.getOperand(0), Op.getOperand(1));
14619 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14620 SelectionDAG &DAG) const {
14622 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14623 Op.getOperand(0), Op.getOperand(1));
14626 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14627 return Op.getOperand(0);
14630 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14631 SelectionDAG &DAG) const {
14632 SDValue Root = Op.getOperand(0);
14633 SDValue Trmp = Op.getOperand(1); // trampoline
14634 SDValue FPtr = Op.getOperand(2); // nested function
14635 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14638 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14639 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14641 if (Subtarget->is64Bit()) {
14642 SDValue OutChains[6];
14644 // Large code-model.
14645 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
14646 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14648 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14649 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14651 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14653 // Load the pointer to the nested function into R11.
14654 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14655 SDValue Addr = Trmp;
14656 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14657 Addr, MachinePointerInfo(TrmpAddr),
14660 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14661 DAG.getConstant(2, MVT::i64));
14662 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14663 MachinePointerInfo(TrmpAddr, 2),
14666 // Load the 'nest' parameter value into R10.
14667 // R10 is specified in X86CallingConv.td
14668 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14669 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14670 DAG.getConstant(10, MVT::i64));
14671 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14672 Addr, MachinePointerInfo(TrmpAddr, 10),
14675 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14676 DAG.getConstant(12, MVT::i64));
14677 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14678 MachinePointerInfo(TrmpAddr, 12),
14681 // Jump to the nested function.
14682 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14683 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14684 DAG.getConstant(20, MVT::i64));
14685 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14686 Addr, MachinePointerInfo(TrmpAddr, 20),
14689 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14690 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14691 DAG.getConstant(22, MVT::i64));
14692 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14693 MachinePointerInfo(TrmpAddr, 22),
14696 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14698 const Function *Func =
14699 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14700 CallingConv::ID CC = Func->getCallingConv();
14705 llvm_unreachable("Unsupported calling convention");
14706 case CallingConv::C:
14707 case CallingConv::X86_StdCall: {
14708 // Pass 'nest' parameter in ECX.
14709 // Must be kept in sync with X86CallingConv.td
14710 NestReg = X86::ECX;
14712 // Check that ECX wasn't needed by an 'inreg' parameter.
14713 FunctionType *FTy = Func->getFunctionType();
14714 const AttributeSet &Attrs = Func->getAttributes();
14716 if (!Attrs.isEmpty() && !Func->isVarArg()) {
14717 unsigned InRegCount = 0;
14720 for (FunctionType::param_iterator I = FTy->param_begin(),
14721 E = FTy->param_end(); I != E; ++I, ++Idx)
14722 if (Attrs.hasAttribute(Idx, Attribute::InReg))
14723 // FIXME: should only count parameters that are lowered to integers.
14724 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14726 if (InRegCount > 2) {
14727 report_fatal_error("Nest register in use - reduce number of inreg"
14733 case CallingConv::X86_FastCall:
14734 case CallingConv::X86_ThisCall:
14735 case CallingConv::Fast:
14736 // Pass 'nest' parameter in EAX.
14737 // Must be kept in sync with X86CallingConv.td
14738 NestReg = X86::EAX;
14742 SDValue OutChains[4];
14743 SDValue Addr, Disp;
14745 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14746 DAG.getConstant(10, MVT::i32));
14747 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14749 // This is storing the opcode for MOV32ri.
14750 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14751 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14752 OutChains[0] = DAG.getStore(Root, dl,
14753 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14754 Trmp, MachinePointerInfo(TrmpAddr),
14757 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14758 DAG.getConstant(1, MVT::i32));
14759 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14760 MachinePointerInfo(TrmpAddr, 1),
14763 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14764 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14765 DAG.getConstant(5, MVT::i32));
14766 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14767 MachinePointerInfo(TrmpAddr, 5),
14770 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14771 DAG.getConstant(6, MVT::i32));
14772 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14773 MachinePointerInfo(TrmpAddr, 6),
14776 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14780 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14781 SelectionDAG &DAG) const {
14783 The rounding mode is in bits 11:10 of FPSR, and has the following
14785 00 Round to nearest
14790 FLT_ROUNDS, on the other hand, expects the following:
14797 To perform the conversion, we do:
14798 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14801 MachineFunction &MF = DAG.getMachineFunction();
14802 const TargetMachine &TM = MF.getTarget();
14803 const TargetFrameLowering &TFI = *TM.getFrameLowering();
14804 unsigned StackAlignment = TFI.getStackAlignment();
14805 MVT VT = Op.getSimpleValueType();
14808 // Save FP Control Word to stack slot
14809 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14810 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14812 MachineMemOperand *MMO =
14813 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14814 MachineMemOperand::MOStore, 2, 2);
14816 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14817 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14818 DAG.getVTList(MVT::Other),
14819 Ops, MVT::i16, MMO);
14821 // Load FP Control Word from stack slot
14822 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14823 MachinePointerInfo(), false, false, false, 0);
14825 // Transform as necessary
14827 DAG.getNode(ISD::SRL, DL, MVT::i16,
14828 DAG.getNode(ISD::AND, DL, MVT::i16,
14829 CWD, DAG.getConstant(0x800, MVT::i16)),
14830 DAG.getConstant(11, MVT::i8));
14832 DAG.getNode(ISD::SRL, DL, MVT::i16,
14833 DAG.getNode(ISD::AND, DL, MVT::i16,
14834 CWD, DAG.getConstant(0x400, MVT::i16)),
14835 DAG.getConstant(9, MVT::i8));
14838 DAG.getNode(ISD::AND, DL, MVT::i16,
14839 DAG.getNode(ISD::ADD, DL, MVT::i16,
14840 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14841 DAG.getConstant(1, MVT::i16)),
14842 DAG.getConstant(3, MVT::i16));
14844 return DAG.getNode((VT.getSizeInBits() < 16 ?
14845 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14848 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14849 MVT VT = Op.getSimpleValueType();
14851 unsigned NumBits = VT.getSizeInBits();
14854 Op = Op.getOperand(0);
14855 if (VT == MVT::i8) {
14856 // Zero extend to i32 since there is not an i8 bsr.
14858 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14861 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14862 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14863 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14865 // If src is zero (i.e. bsr sets ZF), returns NumBits.
14868 DAG.getConstant(NumBits+NumBits-1, OpVT),
14869 DAG.getConstant(X86::COND_E, MVT::i8),
14872 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14874 // Finally xor with NumBits-1.
14875 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14878 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14882 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14883 MVT VT = Op.getSimpleValueType();
14885 unsigned NumBits = VT.getSizeInBits();
14888 Op = Op.getOperand(0);
14889 if (VT == MVT::i8) {
14890 // Zero extend to i32 since there is not an i8 bsr.
14892 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14895 // Issue a bsr (scan bits in reverse).
14896 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14897 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14899 // And xor with NumBits-1.
14900 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14903 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14907 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14908 MVT VT = Op.getSimpleValueType();
14909 unsigned NumBits = VT.getSizeInBits();
14911 Op = Op.getOperand(0);
14913 // Issue a bsf (scan bits forward) which also sets EFLAGS.
14914 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14915 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14917 // If src is zero (i.e. bsf sets ZF), returns NumBits.
14920 DAG.getConstant(NumBits, VT),
14921 DAG.getConstant(X86::COND_E, MVT::i8),
14924 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
14927 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
14928 // ones, and then concatenate the result back.
14929 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
14930 MVT VT = Op.getSimpleValueType();
14932 assert(VT.is256BitVector() && VT.isInteger() &&
14933 "Unsupported value type for operation");
14935 unsigned NumElems = VT.getVectorNumElements();
14938 // Extract the LHS vectors
14939 SDValue LHS = Op.getOperand(0);
14940 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14941 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14943 // Extract the RHS vectors
14944 SDValue RHS = Op.getOperand(1);
14945 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14946 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14948 MVT EltVT = VT.getVectorElementType();
14949 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14951 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14952 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
14953 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
14956 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
14957 assert(Op.getSimpleValueType().is256BitVector() &&
14958 Op.getSimpleValueType().isInteger() &&
14959 "Only handle AVX 256-bit vector integer operation");
14960 return Lower256IntArith(Op, DAG);
14963 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
14964 assert(Op.getSimpleValueType().is256BitVector() &&
14965 Op.getSimpleValueType().isInteger() &&
14966 "Only handle AVX 256-bit vector integer operation");
14967 return Lower256IntArith(Op, DAG);
14970 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
14971 SelectionDAG &DAG) {
14973 MVT VT = Op.getSimpleValueType();
14975 // Decompose 256-bit ops into smaller 128-bit ops.
14976 if (VT.is256BitVector() && !Subtarget->hasInt256())
14977 return Lower256IntArith(Op, DAG);
14979 SDValue A = Op.getOperand(0);
14980 SDValue B = Op.getOperand(1);
14982 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
14983 if (VT == MVT::v4i32) {
14984 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
14985 "Should not custom lower when pmuldq is available!");
14987 // Extract the odd parts.
14988 static const int UnpackMask[] = { 1, -1, 3, -1 };
14989 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
14990 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
14992 // Multiply the even parts.
14993 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
14994 // Now multiply odd parts.
14995 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
14997 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
14998 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15000 // Merge the two vectors back together with a shuffle. This expands into 2
15002 static const int ShufMask[] = { 0, 4, 2, 6 };
15003 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15006 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15007 "Only know how to lower V2I64/V4I64/V8I64 multiply");
15009 // Ahi = psrlqi(a, 32);
15010 // Bhi = psrlqi(b, 32);
15012 // AloBlo = pmuludq(a, b);
15013 // AloBhi = pmuludq(a, Bhi);
15014 // AhiBlo = pmuludq(Ahi, b);
15016 // AloBhi = psllqi(AloBhi, 32);
15017 // AhiBlo = psllqi(AhiBlo, 32);
15018 // return AloBlo + AloBhi + AhiBlo;
15020 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15021 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15023 // Bit cast to 32-bit vectors for MULUDQ
15024 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15025 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15026 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15027 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15028 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15029 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15031 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15032 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15033 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15035 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15036 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15038 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15039 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15042 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15043 assert(Subtarget->isTargetWin64() && "Unexpected target");
15044 EVT VT = Op.getValueType();
15045 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15046 "Unexpected return type for lowering");
15050 switch (Op->getOpcode()) {
15051 default: llvm_unreachable("Unexpected request for libcall!");
15052 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15053 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15054 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15055 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15056 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15057 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15061 SDValue InChain = DAG.getEntryNode();
15063 TargetLowering::ArgListTy Args;
15064 TargetLowering::ArgListEntry Entry;
15065 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15066 EVT ArgVT = Op->getOperand(i).getValueType();
15067 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15068 "Unexpected argument type for lowering");
15069 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15070 Entry.Node = StackPtr;
15071 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15073 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15074 Entry.Ty = PointerType::get(ArgTy,0);
15075 Entry.isSExt = false;
15076 Entry.isZExt = false;
15077 Args.push_back(Entry);
15080 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15083 TargetLowering::CallLoweringInfo CLI(DAG);
15084 CLI.setDebugLoc(dl).setChain(InChain)
15085 .setCallee(getLibcallCallingConv(LC),
15086 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15088 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15090 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15091 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15094 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15095 SelectionDAG &DAG) {
15096 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15097 EVT VT = Op0.getValueType();
15100 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15101 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15103 // Get the high parts.
15104 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
15105 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15106 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15108 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15110 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15111 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15113 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15114 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15115 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15116 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15117 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
15119 // Shuffle it back into the right order.
15120 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
15121 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15122 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
15123 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15125 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15126 // unsigned multiply.
15127 if (IsSigned && !Subtarget->hasSSE41()) {
15129 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15130 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15131 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15132 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15133 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15135 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15136 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15139 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
15142 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15143 const X86Subtarget *Subtarget) {
15144 MVT VT = Op.getSimpleValueType();
15146 SDValue R = Op.getOperand(0);
15147 SDValue Amt = Op.getOperand(1);
15149 // Optimize shl/srl/sra with constant shift amount.
15150 if (isSplatVector(Amt.getNode())) {
15151 SDValue SclrAmt = Amt->getOperand(0);
15152 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
15153 uint64_t ShiftAmt = C->getZExtValue();
15155 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15156 (Subtarget->hasInt256() &&
15157 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15158 (Subtarget->hasAVX512() &&
15159 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15160 if (Op.getOpcode() == ISD::SHL)
15161 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15163 if (Op.getOpcode() == ISD::SRL)
15164 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15166 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15167 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15171 if (VT == MVT::v16i8) {
15172 if (Op.getOpcode() == ISD::SHL) {
15173 // Make a large shift.
15174 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15175 MVT::v8i16, R, ShiftAmt,
15177 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15178 // Zero out the rightmost bits.
15179 SmallVector<SDValue, 16> V(16,
15180 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15182 return DAG.getNode(ISD::AND, dl, VT, SHL,
15183 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15185 if (Op.getOpcode() == ISD::SRL) {
15186 // Make a large shift.
15187 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15188 MVT::v8i16, R, ShiftAmt,
15190 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15191 // Zero out the leftmost bits.
15192 SmallVector<SDValue, 16> V(16,
15193 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15195 return DAG.getNode(ISD::AND, dl, VT, SRL,
15196 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15198 if (Op.getOpcode() == ISD::SRA) {
15199 if (ShiftAmt == 7) {
15200 // R s>> 7 === R s< 0
15201 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15202 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15205 // R s>> a === ((R u>> a) ^ m) - m
15206 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15207 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15209 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15210 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15211 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15214 llvm_unreachable("Unknown shift opcode.");
15217 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15218 if (Op.getOpcode() == ISD::SHL) {
15219 // Make a large shift.
15220 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15221 MVT::v16i16, R, ShiftAmt,
15223 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15224 // Zero out the rightmost bits.
15225 SmallVector<SDValue, 32> V(32,
15226 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15228 return DAG.getNode(ISD::AND, dl, VT, SHL,
15229 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15231 if (Op.getOpcode() == ISD::SRL) {
15232 // Make a large shift.
15233 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15234 MVT::v16i16, R, ShiftAmt,
15236 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15237 // Zero out the leftmost bits.
15238 SmallVector<SDValue, 32> V(32,
15239 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15241 return DAG.getNode(ISD::AND, dl, VT, SRL,
15242 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15244 if (Op.getOpcode() == ISD::SRA) {
15245 if (ShiftAmt == 7) {
15246 // R s>> 7 === R s< 0
15247 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15248 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15251 // R s>> a === ((R u>> a) ^ m) - m
15252 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15253 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15255 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15256 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15257 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15260 llvm_unreachable("Unknown shift opcode.");
15265 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15266 if (!Subtarget->is64Bit() &&
15267 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15268 Amt.getOpcode() == ISD::BITCAST &&
15269 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15270 Amt = Amt.getOperand(0);
15271 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15272 VT.getVectorNumElements();
15273 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15274 uint64_t ShiftAmt = 0;
15275 for (unsigned i = 0; i != Ratio; ++i) {
15276 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15280 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15282 // Check remaining shift amounts.
15283 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15284 uint64_t ShAmt = 0;
15285 for (unsigned j = 0; j != Ratio; ++j) {
15286 ConstantSDNode *C =
15287 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15291 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15293 if (ShAmt != ShiftAmt)
15296 switch (Op.getOpcode()) {
15298 llvm_unreachable("Unknown shift opcode!");
15300 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15303 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15306 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15314 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15315 const X86Subtarget* Subtarget) {
15316 MVT VT = Op.getSimpleValueType();
15318 SDValue R = Op.getOperand(0);
15319 SDValue Amt = Op.getOperand(1);
15321 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15322 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15323 (Subtarget->hasInt256() &&
15324 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15325 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15326 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15328 EVT EltVT = VT.getVectorElementType();
15330 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15331 unsigned NumElts = VT.getVectorNumElements();
15333 for (i = 0; i != NumElts; ++i) {
15334 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15338 for (j = i; j != NumElts; ++j) {
15339 SDValue Arg = Amt.getOperand(j);
15340 if (Arg.getOpcode() == ISD::UNDEF) continue;
15341 if (Arg != Amt.getOperand(i))
15344 if (i != NumElts && j == NumElts)
15345 BaseShAmt = Amt.getOperand(i);
15347 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15348 Amt = Amt.getOperand(0);
15349 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15350 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15351 SDValue InVec = Amt.getOperand(0);
15352 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15353 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15355 for (; i != NumElts; ++i) {
15356 SDValue Arg = InVec.getOperand(i);
15357 if (Arg.getOpcode() == ISD::UNDEF) continue;
15361 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15362 if (ConstantSDNode *C =
15363 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15364 unsigned SplatIdx =
15365 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15366 if (C->getZExtValue() == SplatIdx)
15367 BaseShAmt = InVec.getOperand(1);
15370 if (!BaseShAmt.getNode())
15371 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15372 DAG.getIntPtrConstant(0));
15376 if (BaseShAmt.getNode()) {
15377 if (EltVT.bitsGT(MVT::i32))
15378 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15379 else if (EltVT.bitsLT(MVT::i32))
15380 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15382 switch (Op.getOpcode()) {
15384 llvm_unreachable("Unknown shift opcode!");
15386 switch (VT.SimpleTy) {
15387 default: return SDValue();
15396 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15399 switch (VT.SimpleTy) {
15400 default: return SDValue();
15407 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15410 switch (VT.SimpleTy) {
15411 default: return SDValue();
15420 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15426 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15427 if (!Subtarget->is64Bit() &&
15428 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15429 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15430 Amt.getOpcode() == ISD::BITCAST &&
15431 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15432 Amt = Amt.getOperand(0);
15433 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15434 VT.getVectorNumElements();
15435 std::vector<SDValue> Vals(Ratio);
15436 for (unsigned i = 0; i != Ratio; ++i)
15437 Vals[i] = Amt.getOperand(i);
15438 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15439 for (unsigned j = 0; j != Ratio; ++j)
15440 if (Vals[j] != Amt.getOperand(i + j))
15443 switch (Op.getOpcode()) {
15445 llvm_unreachable("Unknown shift opcode!");
15447 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15449 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15451 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15458 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15459 SelectionDAG &DAG) {
15461 MVT VT = Op.getSimpleValueType();
15463 SDValue R = Op.getOperand(0);
15464 SDValue Amt = Op.getOperand(1);
15467 if (!Subtarget->hasSSE2())
15470 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15474 V = LowerScalarVariableShift(Op, DAG, Subtarget);
15478 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15480 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15481 if (Subtarget->hasInt256()) {
15482 if (Op.getOpcode() == ISD::SRL &&
15483 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15484 VT == MVT::v4i64 || VT == MVT::v8i32))
15486 if (Op.getOpcode() == ISD::SHL &&
15487 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15488 VT == MVT::v4i64 || VT == MVT::v8i32))
15490 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15494 // If possible, lower this packed shift into a vector multiply instead of
15495 // expanding it into a sequence of scalar shifts.
15496 // Do this only if the vector shift count is a constant build_vector.
15497 if (Op.getOpcode() == ISD::SHL &&
15498 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15499 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15500 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15501 SmallVector<SDValue, 8> Elts;
15502 EVT SVT = VT.getScalarType();
15503 unsigned SVTBits = SVT.getSizeInBits();
15504 const APInt &One = APInt(SVTBits, 1);
15505 unsigned NumElems = VT.getVectorNumElements();
15507 for (unsigned i=0; i !=NumElems; ++i) {
15508 SDValue Op = Amt->getOperand(i);
15509 if (Op->getOpcode() == ISD::UNDEF) {
15510 Elts.push_back(Op);
15514 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15515 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15516 uint64_t ShAmt = C.getZExtValue();
15517 if (ShAmt >= SVTBits) {
15518 Elts.push_back(DAG.getUNDEF(SVT));
15521 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15523 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15524 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15527 // Lower SHL with variable shift amount.
15528 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15529 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15531 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15532 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15533 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15534 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15537 // If possible, lower this shift as a sequence of two shifts by
15538 // constant plus a MOVSS/MOVSD instead of scalarizing it.
15540 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15542 // Could be rewritten as:
15543 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15545 // The advantage is that the two shifts from the example would be
15546 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15547 // the vector shift into four scalar shifts plus four pairs of vector
15549 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15550 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15551 unsigned TargetOpcode = X86ISD::MOVSS;
15552 bool CanBeSimplified;
15553 // The splat value for the first packed shift (the 'X' from the example).
15554 SDValue Amt1 = Amt->getOperand(0);
15555 // The splat value for the second packed shift (the 'Y' from the example).
15556 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15557 Amt->getOperand(2);
15559 // See if it is possible to replace this node with a sequence of
15560 // two shifts followed by a MOVSS/MOVSD
15561 if (VT == MVT::v4i32) {
15562 // Check if it is legal to use a MOVSS.
15563 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15564 Amt2 == Amt->getOperand(3);
15565 if (!CanBeSimplified) {
15566 // Otherwise, check if we can still simplify this node using a MOVSD.
15567 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15568 Amt->getOperand(2) == Amt->getOperand(3);
15569 TargetOpcode = X86ISD::MOVSD;
15570 Amt2 = Amt->getOperand(2);
15573 // Do similar checks for the case where the machine value type
15575 CanBeSimplified = Amt1 == Amt->getOperand(1);
15576 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15577 CanBeSimplified = Amt2 == Amt->getOperand(i);
15579 if (!CanBeSimplified) {
15580 TargetOpcode = X86ISD::MOVSD;
15581 CanBeSimplified = true;
15582 Amt2 = Amt->getOperand(4);
15583 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15584 CanBeSimplified = Amt1 == Amt->getOperand(i);
15585 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15586 CanBeSimplified = Amt2 == Amt->getOperand(j);
15590 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15591 isa<ConstantSDNode>(Amt2)) {
15592 // Replace this node with two shifts followed by a MOVSS/MOVSD.
15593 EVT CastVT = MVT::v4i32;
15595 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15596 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15598 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15599 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15600 if (TargetOpcode == X86ISD::MOVSD)
15601 CastVT = MVT::v2i64;
15602 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15603 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15604 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15606 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15610 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15611 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15614 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15615 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15617 // Turn 'a' into a mask suitable for VSELECT
15618 SDValue VSelM = DAG.getConstant(0x80, VT);
15619 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15620 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15622 SDValue CM1 = DAG.getConstant(0x0f, VT);
15623 SDValue CM2 = DAG.getConstant(0x3f, VT);
15625 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15626 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15627 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15628 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15629 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15632 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15633 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15634 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15636 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15637 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15638 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15639 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15640 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15643 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15644 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15645 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15647 // return VSELECT(r, r+r, a);
15648 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15649 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15653 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15654 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15655 // solution better.
15656 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15657 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15659 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15660 R = DAG.getNode(ExtOpc, dl, NewVT, R);
15661 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15662 return DAG.getNode(ISD::TRUNCATE, dl, VT,
15663 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15666 // Decompose 256-bit shifts into smaller 128-bit shifts.
15667 if (VT.is256BitVector()) {
15668 unsigned NumElems = VT.getVectorNumElements();
15669 MVT EltVT = VT.getVectorElementType();
15670 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15672 // Extract the two vectors
15673 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15674 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15676 // Recreate the shift amount vectors
15677 SDValue Amt1, Amt2;
15678 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15679 // Constant shift amount
15680 SmallVector<SDValue, 4> Amt1Csts;
15681 SmallVector<SDValue, 4> Amt2Csts;
15682 for (unsigned i = 0; i != NumElems/2; ++i)
15683 Amt1Csts.push_back(Amt->getOperand(i));
15684 for (unsigned i = NumElems/2; i != NumElems; ++i)
15685 Amt2Csts.push_back(Amt->getOperand(i));
15687 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15688 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15690 // Variable shift amount
15691 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15692 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15695 // Issue new vector shifts for the smaller types
15696 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15697 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15699 // Concatenate the result back
15700 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15706 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15707 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15708 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15709 // looks for this combo and may remove the "setcc" instruction if the "setcc"
15710 // has only one use.
15711 SDNode *N = Op.getNode();
15712 SDValue LHS = N->getOperand(0);
15713 SDValue RHS = N->getOperand(1);
15714 unsigned BaseOp = 0;
15717 switch (Op.getOpcode()) {
15718 default: llvm_unreachable("Unknown ovf instruction!");
15720 // A subtract of one will be selected as a INC. Note that INC doesn't
15721 // set CF, so we can't do this for UADDO.
15722 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15724 BaseOp = X86ISD::INC;
15725 Cond = X86::COND_O;
15728 BaseOp = X86ISD::ADD;
15729 Cond = X86::COND_O;
15732 BaseOp = X86ISD::ADD;
15733 Cond = X86::COND_B;
15736 // A subtract of one will be selected as a DEC. Note that DEC doesn't
15737 // set CF, so we can't do this for USUBO.
15738 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15740 BaseOp = X86ISD::DEC;
15741 Cond = X86::COND_O;
15744 BaseOp = X86ISD::SUB;
15745 Cond = X86::COND_O;
15748 BaseOp = X86ISD::SUB;
15749 Cond = X86::COND_B;
15752 BaseOp = X86ISD::SMUL;
15753 Cond = X86::COND_O;
15755 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15756 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15758 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15761 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15762 DAG.getConstant(X86::COND_O, MVT::i32),
15763 SDValue(Sum.getNode(), 2));
15765 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15769 // Also sets EFLAGS.
15770 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15771 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15774 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15775 DAG.getConstant(Cond, MVT::i32),
15776 SDValue(Sum.getNode(), 1));
15778 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15781 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15782 SelectionDAG &DAG) const {
15784 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15785 MVT VT = Op.getSimpleValueType();
15787 if (!Subtarget->hasSSE2() || !VT.isVector())
15790 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15791 ExtraVT.getScalarType().getSizeInBits();
15793 switch (VT.SimpleTy) {
15794 default: return SDValue();
15797 if (!Subtarget->hasFp256())
15799 if (!Subtarget->hasInt256()) {
15800 // needs to be split
15801 unsigned NumElems = VT.getVectorNumElements();
15803 // Extract the LHS vectors
15804 SDValue LHS = Op.getOperand(0);
15805 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15806 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15808 MVT EltVT = VT.getVectorElementType();
15809 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15811 EVT ExtraEltVT = ExtraVT.getVectorElementType();
15812 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15813 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15815 SDValue Extra = DAG.getValueType(ExtraVT);
15817 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15818 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15820 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15825 SDValue Op0 = Op.getOperand(0);
15826 SDValue Op00 = Op0.getOperand(0);
15828 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15829 if (Op0.getOpcode() == ISD::BITCAST &&
15830 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15831 // (sext (vzext x)) -> (vsext x)
15832 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15833 if (Tmp1.getNode()) {
15834 EVT ExtraEltVT = ExtraVT.getVectorElementType();
15835 // This folding is only valid when the in-reg type is a vector of i8,
15837 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15838 ExtraEltVT == MVT::i32) {
15839 SDValue Tmp1Op0 = Tmp1.getOperand(0);
15840 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15841 "This optimization is invalid without a VZEXT.");
15842 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15848 // If the above didn't work, then just use Shift-Left + Shift-Right.
15849 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15851 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15857 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15858 SelectionDAG &DAG) {
15860 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15861 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15862 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15863 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15865 // The only fence that needs an instruction is a sequentially-consistent
15866 // cross-thread fence.
15867 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15868 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15869 // no-sse2). There isn't any reason to disable it if the target processor
15871 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15872 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15874 SDValue Chain = Op.getOperand(0);
15875 SDValue Zero = DAG.getConstant(0, MVT::i32);
15877 DAG.getRegister(X86::ESP, MVT::i32), // Base
15878 DAG.getTargetConstant(1, MVT::i8), // Scale
15879 DAG.getRegister(0, MVT::i32), // Index
15880 DAG.getTargetConstant(0, MVT::i32), // Disp
15881 DAG.getRegister(0, MVT::i32), // Segment.
15885 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15886 return SDValue(Res, 0);
15889 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
15890 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
15893 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
15894 SelectionDAG &DAG) {
15895 MVT T = Op.getSimpleValueType();
15899 switch(T.SimpleTy) {
15900 default: llvm_unreachable("Invalid value type!");
15901 case MVT::i8: Reg = X86::AL; size = 1; break;
15902 case MVT::i16: Reg = X86::AX; size = 2; break;
15903 case MVT::i32: Reg = X86::EAX; size = 4; break;
15905 assert(Subtarget->is64Bit() && "Node not type legal!");
15906 Reg = X86::RAX; size = 8;
15909 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
15910 Op.getOperand(2), SDValue());
15911 SDValue Ops[] = { cpIn.getValue(0),
15914 DAG.getTargetConstant(size, MVT::i8),
15915 cpIn.getValue(1) };
15916 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15917 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
15918 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
15922 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
15923 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
15924 MVT::i32, cpOut.getValue(2));
15925 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
15926 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15928 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
15929 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
15930 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
15934 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
15935 SelectionDAG &DAG) {
15936 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
15937 MVT DstVT = Op.getSimpleValueType();
15939 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
15940 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15941 if (DstVT != MVT::f64)
15942 // This conversion needs to be expanded.
15945 SDValue InVec = Op->getOperand(0);
15947 unsigned NumElts = SrcVT.getVectorNumElements();
15948 EVT SVT = SrcVT.getVectorElementType();
15950 // Widen the vector in input in the case of MVT::v2i32.
15951 // Example: from MVT::v2i32 to MVT::v4i32.
15952 SmallVector<SDValue, 16> Elts;
15953 for (unsigned i = 0, e = NumElts; i != e; ++i)
15954 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
15955 DAG.getIntPtrConstant(i)));
15957 // Explicitly mark the extra elements as Undef.
15958 SDValue Undef = DAG.getUNDEF(SVT);
15959 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
15960 Elts.push_back(Undef);
15962 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15963 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
15964 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
15965 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
15966 DAG.getIntPtrConstant(0));
15969 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
15970 Subtarget->hasMMX() && "Unexpected custom BITCAST");
15971 assert((DstVT == MVT::i64 ||
15972 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
15973 "Unexpected custom BITCAST");
15974 // i64 <=> MMX conversions are Legal.
15975 if (SrcVT==MVT::i64 && DstVT.isVector())
15977 if (DstVT==MVT::i64 && SrcVT.isVector())
15979 // MMX <=> MMX conversions are Legal.
15980 if (SrcVT.isVector() && DstVT.isVector())
15982 // All other conversions need to be expanded.
15986 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
15987 SDNode *Node = Op.getNode();
15989 EVT T = Node->getValueType(0);
15990 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
15991 DAG.getConstant(0, T), Node->getOperand(2));
15992 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
15993 cast<AtomicSDNode>(Node)->getMemoryVT(),
15994 Node->getOperand(0),
15995 Node->getOperand(1), negOp,
15996 cast<AtomicSDNode>(Node)->getMemOperand(),
15997 cast<AtomicSDNode>(Node)->getOrdering(),
15998 cast<AtomicSDNode>(Node)->getSynchScope());
16001 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16002 SDNode *Node = Op.getNode();
16004 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16006 // Convert seq_cst store -> xchg
16007 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16008 // FIXME: On 32-bit, store -> fist or movq would be more efficient
16009 // (The only way to get a 16-byte store is cmpxchg16b)
16010 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16011 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16012 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16013 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16014 cast<AtomicSDNode>(Node)->getMemoryVT(),
16015 Node->getOperand(0),
16016 Node->getOperand(1), Node->getOperand(2),
16017 cast<AtomicSDNode>(Node)->getMemOperand(),
16018 cast<AtomicSDNode>(Node)->getOrdering(),
16019 cast<AtomicSDNode>(Node)->getSynchScope());
16020 return Swap.getValue(1);
16022 // Other atomic stores have a simple pattern.
16026 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16027 EVT VT = Op.getNode()->getSimpleValueType(0);
16029 // Let legalize expand this if it isn't a legal type yet.
16030 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16033 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16036 bool ExtraOp = false;
16037 switch (Op.getOpcode()) {
16038 default: llvm_unreachable("Invalid code");
16039 case ISD::ADDC: Opc = X86ISD::ADD; break;
16040 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16041 case ISD::SUBC: Opc = X86ISD::SUB; break;
16042 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16046 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16048 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16049 Op.getOperand(1), Op.getOperand(2));
16052 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16053 SelectionDAG &DAG) {
16054 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16056 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16057 // which returns the values as { float, float } (in XMM0) or
16058 // { double, double } (which is returned in XMM0, XMM1).
16060 SDValue Arg = Op.getOperand(0);
16061 EVT ArgVT = Arg.getValueType();
16062 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16064 TargetLowering::ArgListTy Args;
16065 TargetLowering::ArgListEntry Entry;
16069 Entry.isSExt = false;
16070 Entry.isZExt = false;
16071 Args.push_back(Entry);
16073 bool isF64 = ArgVT == MVT::f64;
16074 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16075 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16076 // the results are returned via SRet in memory.
16077 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16078 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16079 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16081 Type *RetTy = isF64
16082 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16083 : (Type*)VectorType::get(ArgTy, 4);
16085 TargetLowering::CallLoweringInfo CLI(DAG);
16086 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16087 .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
16089 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16092 // Returned in xmm0 and xmm1.
16093 return CallResult.first;
16095 // Returned in bits 0:31 and 32:64 xmm0.
16096 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16097 CallResult.first, DAG.getIntPtrConstant(0));
16098 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16099 CallResult.first, DAG.getIntPtrConstant(1));
16100 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16101 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16104 /// LowerOperation - Provide custom lowering hooks for some operations.
16106 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16107 switch (Op.getOpcode()) {
16108 default: llvm_unreachable("Should not custom lower this!");
16109 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
16110 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16111 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16112 return LowerCMP_SWAP(Op, Subtarget, DAG);
16113 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16114 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16115 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16116 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16117 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
16118 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16119 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16120 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16121 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16122 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16123 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16124 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16125 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16126 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16127 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16128 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16129 case ISD::SHL_PARTS:
16130 case ISD::SRA_PARTS:
16131 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16132 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16133 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16134 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16135 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16136 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16137 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16138 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16139 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16140 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16141 case ISD::FABS: return LowerFABS(Op, DAG);
16142 case ISD::FNEG: return LowerFNEG(Op, DAG);
16143 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16144 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16145 case ISD::SETCC: return LowerSETCC(Op, DAG);
16146 case ISD::SELECT: return LowerSELECT(Op, DAG);
16147 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16148 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16149 case ISD::VASTART: return LowerVASTART(Op, DAG);
16150 case ISD::VAARG: return LowerVAARG(Op, DAG);
16151 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16152 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16153 case ISD::INTRINSIC_VOID:
16154 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16155 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16156 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16157 case ISD::FRAME_TO_ARGS_OFFSET:
16158 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16159 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16160 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16161 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16162 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16163 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16164 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16165 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16166 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16167 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16168 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16169 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16170 case ISD::UMUL_LOHI:
16171 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16174 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16180 case ISD::UMULO: return LowerXALUO(Op, DAG);
16181 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16182 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16186 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16187 case ISD::ADD: return LowerADD(Op, DAG);
16188 case ISD::SUB: return LowerSUB(Op, DAG);
16189 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16193 static void ReplaceATOMIC_LOAD(SDNode *Node,
16194 SmallVectorImpl<SDValue> &Results,
16195 SelectionDAG &DAG) {
16197 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16199 // Convert wide load -> cmpxchg8b/cmpxchg16b
16200 // FIXME: On 32-bit, load -> fild or movq would be more efficient
16201 // (The only way to get a 16-byte load is cmpxchg16b)
16202 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16203 SDValue Zero = DAG.getConstant(0, VT);
16204 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16206 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16207 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16208 cast<AtomicSDNode>(Node)->getMemOperand(),
16209 cast<AtomicSDNode>(Node)->getOrdering(),
16210 cast<AtomicSDNode>(Node)->getOrdering(),
16211 cast<AtomicSDNode>(Node)->getSynchScope());
16212 Results.push_back(Swap.getValue(0));
16213 Results.push_back(Swap.getValue(2));
16216 /// ReplaceNodeResults - Replace a node with an illegal result type
16217 /// with a new node built out of custom code.
16218 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16219 SmallVectorImpl<SDValue>&Results,
16220 SelectionDAG &DAG) const {
16222 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16223 switch (N->getOpcode()) {
16225 llvm_unreachable("Do not know how to custom type legalize this operation!");
16226 case ISD::SIGN_EXTEND_INREG:
16231 // We don't want to expand or promote these.
16238 case ISD::UDIVREM: {
16239 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16240 Results.push_back(V);
16243 case ISD::FP_TO_SINT:
16244 case ISD::FP_TO_UINT: {
16245 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16247 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16250 std::pair<SDValue,SDValue> Vals =
16251 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16252 SDValue FIST = Vals.first, StackSlot = Vals.second;
16253 if (FIST.getNode()) {
16254 EVT VT = N->getValueType(0);
16255 // Return a load from the stack slot.
16256 if (StackSlot.getNode())
16257 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16258 MachinePointerInfo(),
16259 false, false, false, 0));
16261 Results.push_back(FIST);
16265 case ISD::UINT_TO_FP: {
16266 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16267 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16268 N->getValueType(0) != MVT::v2f32)
16270 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16272 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16274 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16275 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16276 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16277 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16278 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16279 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16282 case ISD::FP_ROUND: {
16283 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16285 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16286 Results.push_back(V);
16289 case ISD::INTRINSIC_W_CHAIN: {
16290 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16292 default : llvm_unreachable("Do not know how to custom type "
16293 "legalize this intrinsic operation!");
16294 case Intrinsic::x86_rdtsc:
16295 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16297 case Intrinsic::x86_rdtscp:
16298 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16300 case Intrinsic::x86_rdpmc:
16301 return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16304 case ISD::READCYCLECOUNTER: {
16305 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16308 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16309 EVT T = N->getValueType(0);
16310 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16311 bool Regs64bit = T == MVT::i128;
16312 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16313 SDValue cpInL, cpInH;
16314 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16315 DAG.getConstant(0, HalfT));
16316 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16317 DAG.getConstant(1, HalfT));
16318 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16319 Regs64bit ? X86::RAX : X86::EAX,
16321 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16322 Regs64bit ? X86::RDX : X86::EDX,
16323 cpInH, cpInL.getValue(1));
16324 SDValue swapInL, swapInH;
16325 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16326 DAG.getConstant(0, HalfT));
16327 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16328 DAG.getConstant(1, HalfT));
16329 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16330 Regs64bit ? X86::RBX : X86::EBX,
16331 swapInL, cpInH.getValue(1));
16332 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16333 Regs64bit ? X86::RCX : X86::ECX,
16334 swapInH, swapInL.getValue(1));
16335 SDValue Ops[] = { swapInH.getValue(0),
16337 swapInH.getValue(1) };
16338 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16339 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16340 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16341 X86ISD::LCMPXCHG8_DAG;
16342 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16343 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16344 Regs64bit ? X86::RAX : X86::EAX,
16345 HalfT, Result.getValue(1));
16346 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16347 Regs64bit ? X86::RDX : X86::EDX,
16348 HalfT, cpOutL.getValue(2));
16349 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16351 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16352 MVT::i32, cpOutH.getValue(2));
16354 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16355 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16356 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16358 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16359 Results.push_back(Success);
16360 Results.push_back(EFLAGS.getValue(1));
16363 case ISD::ATOMIC_LOAD: {
16364 ReplaceATOMIC_LOAD(N, Results, DAG);
16367 case ISD::BITCAST: {
16368 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16369 EVT DstVT = N->getValueType(0);
16370 EVT SrcVT = N->getOperand(0)->getValueType(0);
16372 if (SrcVT != MVT::f64 ||
16373 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16376 unsigned NumElts = DstVT.getVectorNumElements();
16377 EVT SVT = DstVT.getVectorElementType();
16378 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16379 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16380 MVT::v2f64, N->getOperand(0));
16381 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16383 SmallVector<SDValue, 8> Elts;
16384 for (unsigned i = 0, e = NumElts; i != e; ++i)
16385 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16386 ToVecInt, DAG.getIntPtrConstant(i)));
16388 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16393 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16395 default: return nullptr;
16396 case X86ISD::BSF: return "X86ISD::BSF";
16397 case X86ISD::BSR: return "X86ISD::BSR";
16398 case X86ISD::SHLD: return "X86ISD::SHLD";
16399 case X86ISD::SHRD: return "X86ISD::SHRD";
16400 case X86ISD::FAND: return "X86ISD::FAND";
16401 case X86ISD::FANDN: return "X86ISD::FANDN";
16402 case X86ISD::FOR: return "X86ISD::FOR";
16403 case X86ISD::FXOR: return "X86ISD::FXOR";
16404 case X86ISD::FSRL: return "X86ISD::FSRL";
16405 case X86ISD::FILD: return "X86ISD::FILD";
16406 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
16407 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16408 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16409 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16410 case X86ISD::FLD: return "X86ISD::FLD";
16411 case X86ISD::FST: return "X86ISD::FST";
16412 case X86ISD::CALL: return "X86ISD::CALL";
16413 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
16414 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
16415 case X86ISD::RDPMC_DAG: return "X86ISD::RDPMC_DAG";
16416 case X86ISD::BT: return "X86ISD::BT";
16417 case X86ISD::CMP: return "X86ISD::CMP";
16418 case X86ISD::COMI: return "X86ISD::COMI";
16419 case X86ISD::UCOMI: return "X86ISD::UCOMI";
16420 case X86ISD::CMPM: return "X86ISD::CMPM";
16421 case X86ISD::CMPMU: return "X86ISD::CMPMU";
16422 case X86ISD::SETCC: return "X86ISD::SETCC";
16423 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
16424 case X86ISD::FSETCC: return "X86ISD::FSETCC";
16425 case X86ISD::CMOV: return "X86ISD::CMOV";
16426 case X86ISD::BRCOND: return "X86ISD::BRCOND";
16427 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
16428 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
16429 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
16430 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
16431 case X86ISD::Wrapper: return "X86ISD::Wrapper";
16432 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
16433 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
16434 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
16435 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
16436 case X86ISD::PINSRB: return "X86ISD::PINSRB";
16437 case X86ISD::PINSRW: return "X86ISD::PINSRW";
16438 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
16439 case X86ISD::ANDNP: return "X86ISD::ANDNP";
16440 case X86ISD::PSIGN: return "X86ISD::PSIGN";
16441 case X86ISD::BLENDV: return "X86ISD::BLENDV";
16442 case X86ISD::BLENDI: return "X86ISD::BLENDI";
16443 case X86ISD::SUBUS: return "X86ISD::SUBUS";
16444 case X86ISD::HADD: return "X86ISD::HADD";
16445 case X86ISD::HSUB: return "X86ISD::HSUB";
16446 case X86ISD::FHADD: return "X86ISD::FHADD";
16447 case X86ISD::FHSUB: return "X86ISD::FHSUB";
16448 case X86ISD::UMAX: return "X86ISD::UMAX";
16449 case X86ISD::UMIN: return "X86ISD::UMIN";
16450 case X86ISD::SMAX: return "X86ISD::SMAX";
16451 case X86ISD::SMIN: return "X86ISD::SMIN";
16452 case X86ISD::FMAX: return "X86ISD::FMAX";
16453 case X86ISD::FMIN: return "X86ISD::FMIN";
16454 case X86ISD::FMAXC: return "X86ISD::FMAXC";
16455 case X86ISD::FMINC: return "X86ISD::FMINC";
16456 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
16457 case X86ISD::FRCP: return "X86ISD::FRCP";
16458 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
16459 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
16460 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
16461 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
16462 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
16463 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
16464 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
16465 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
16466 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
16467 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
16468 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
16469 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
16470 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
16471 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
16472 case X86ISD::VZEXT: return "X86ISD::VZEXT";
16473 case X86ISD::VSEXT: return "X86ISD::VSEXT";
16474 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
16475 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
16476 case X86ISD::VINSERT: return "X86ISD::VINSERT";
16477 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
16478 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
16479 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
16480 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
16481 case X86ISD::VSHL: return "X86ISD::VSHL";
16482 case X86ISD::VSRL: return "X86ISD::VSRL";
16483 case X86ISD::VSRA: return "X86ISD::VSRA";
16484 case X86ISD::VSHLI: return "X86ISD::VSHLI";
16485 case X86ISD::VSRLI: return "X86ISD::VSRLI";
16486 case X86ISD::VSRAI: return "X86ISD::VSRAI";
16487 case X86ISD::CMPP: return "X86ISD::CMPP";
16488 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
16489 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
16490 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
16491 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
16492 case X86ISD::ADD: return "X86ISD::ADD";
16493 case X86ISD::SUB: return "X86ISD::SUB";
16494 case X86ISD::ADC: return "X86ISD::ADC";
16495 case X86ISD::SBB: return "X86ISD::SBB";
16496 case X86ISD::SMUL: return "X86ISD::SMUL";
16497 case X86ISD::UMUL: return "X86ISD::UMUL";
16498 case X86ISD::INC: return "X86ISD::INC";
16499 case X86ISD::DEC: return "X86ISD::DEC";
16500 case X86ISD::OR: return "X86ISD::OR";
16501 case X86ISD::XOR: return "X86ISD::XOR";
16502 case X86ISD::AND: return "X86ISD::AND";
16503 case X86ISD::BEXTR: return "X86ISD::BEXTR";
16504 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
16505 case X86ISD::PTEST: return "X86ISD::PTEST";
16506 case X86ISD::TESTP: return "X86ISD::TESTP";
16507 case X86ISD::TESTM: return "X86ISD::TESTM";
16508 case X86ISD::TESTNM: return "X86ISD::TESTNM";
16509 case X86ISD::KORTEST: return "X86ISD::KORTEST";
16510 case X86ISD::PACKSS: return "X86ISD::PACKSS";
16511 case X86ISD::PACKUS: return "X86ISD::PACKUS";
16512 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
16513 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
16514 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
16515 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
16516 case X86ISD::SHUFP: return "X86ISD::SHUFP";
16517 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
16518 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
16519 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
16520 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
16521 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
16522 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
16523 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
16524 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
16525 case X86ISD::MOVSD: return "X86ISD::MOVSD";
16526 case X86ISD::MOVSS: return "X86ISD::MOVSS";
16527 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
16528 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
16529 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
16530 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
16531 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
16532 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
16533 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
16534 case X86ISD::VPERMV: return "X86ISD::VPERMV";
16535 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
16536 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
16537 case X86ISD::VPERMI: return "X86ISD::VPERMI";
16538 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
16539 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
16540 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16541 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
16542 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
16543 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
16544 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
16545 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
16546 case X86ISD::SAHF: return "X86ISD::SAHF";
16547 case X86ISD::RDRAND: return "X86ISD::RDRAND";
16548 case X86ISD::RDSEED: return "X86ISD::RDSEED";
16549 case X86ISD::FMADD: return "X86ISD::FMADD";
16550 case X86ISD::FMSUB: return "X86ISD::FMSUB";
16551 case X86ISD::FNMADD: return "X86ISD::FNMADD";
16552 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
16553 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
16554 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
16555 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
16556 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
16557 case X86ISD::XTEST: return "X86ISD::XTEST";
16561 // isLegalAddressingMode - Return true if the addressing mode represented
16562 // by AM is legal for this target, for a load/store of the specified type.
16563 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16565 // X86 supports extremely general addressing modes.
16566 CodeModel::Model M = getTargetMachine().getCodeModel();
16567 Reloc::Model R = getTargetMachine().getRelocationModel();
16569 // X86 allows a sign-extended 32-bit immediate field as a displacement.
16570 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16575 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16577 // If a reference to this global requires an extra load, we can't fold it.
16578 if (isGlobalStubReference(GVFlags))
16581 // If BaseGV requires a register for the PIC base, we cannot also have a
16582 // BaseReg specified.
16583 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16586 // If lower 4G is not available, then we must use rip-relative addressing.
16587 if ((M != CodeModel::Small || R != Reloc::Static) &&
16588 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16592 switch (AM.Scale) {
16598 // These scales always work.
16603 // These scales are formed with basereg+scalereg. Only accept if there is
16608 default: // Other stuff never works.
16615 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16616 unsigned Bits = Ty->getScalarSizeInBits();
16618 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16619 // particularly cheaper than those without.
16623 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16624 // variable shifts just as cheap as scalar ones.
16625 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16628 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16629 // fully general vector.
16633 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16634 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16636 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16637 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16638 return NumBits1 > NumBits2;
16641 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16642 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16645 if (!isTypeLegal(EVT::getEVT(Ty1)))
16648 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16650 // Assuming the caller doesn't have a zeroext or signext return parameter,
16651 // truncation all the way down to i1 is valid.
16655 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16656 return isInt<32>(Imm);
16659 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16660 // Can also use sub to handle negated immediates.
16661 return isInt<32>(Imm);
16664 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16665 if (!VT1.isInteger() || !VT2.isInteger())
16667 unsigned NumBits1 = VT1.getSizeInBits();
16668 unsigned NumBits2 = VT2.getSizeInBits();
16669 return NumBits1 > NumBits2;
16672 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16673 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16674 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16677 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16678 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16679 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16682 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16683 EVT VT1 = Val.getValueType();
16684 if (isZExtFree(VT1, VT2))
16687 if (Val.getOpcode() != ISD::LOAD)
16690 if (!VT1.isSimple() || !VT1.isInteger() ||
16691 !VT2.isSimple() || !VT2.isInteger())
16694 switch (VT1.getSimpleVT().SimpleTy) {
16699 // X86 has 8, 16, and 32-bit zero-extending loads.
16707 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16708 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16711 VT = VT.getScalarType();
16713 if (!VT.isSimple())
16716 switch (VT.getSimpleVT().SimpleTy) {
16727 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16728 // i16 instructions are longer (0x66 prefix) and potentially slower.
16729 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16732 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16733 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16734 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16735 /// are assumed to be legal.
16737 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16739 if (!VT.isSimple())
16742 MVT SVT = VT.getSimpleVT();
16744 // Very little shuffling can be done for 64-bit vectors right now.
16745 if (VT.getSizeInBits() == 64)
16748 // If this is a single-input shuffle with no 128 bit lane crossings we can
16749 // lower it into pshufb.
16750 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16751 (SVT.is256BitVector() && Subtarget->hasInt256())) {
16752 bool isLegal = true;
16753 for (unsigned I = 0, E = M.size(); I != E; ++I) {
16754 if (M[I] >= (int)SVT.getVectorNumElements() ||
16755 ShuffleCrosses128bitLane(SVT, I, M[I])) {
16764 // FIXME: blends, shifts.
16765 return (SVT.getVectorNumElements() == 2 ||
16766 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16767 isMOVLMask(M, SVT) ||
16768 isSHUFPMask(M, SVT) ||
16769 isPSHUFDMask(M, SVT) ||
16770 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16771 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16772 isPALIGNRMask(M, SVT, Subtarget) ||
16773 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16774 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16775 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16776 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16777 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16781 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16783 if (!VT.isSimple())
16786 MVT SVT = VT.getSimpleVT();
16787 unsigned NumElts = SVT.getVectorNumElements();
16788 // FIXME: This collection of masks seems suspect.
16791 if (NumElts == 4 && SVT.is128BitVector()) {
16792 return (isMOVLMask(Mask, SVT) ||
16793 isCommutedMOVLMask(Mask, SVT, true) ||
16794 isSHUFPMask(Mask, SVT) ||
16795 isSHUFPMask(Mask, SVT, /* Commuted */ true));
16800 //===----------------------------------------------------------------------===//
16801 // X86 Scheduler Hooks
16802 //===----------------------------------------------------------------------===//
16804 /// Utility function to emit xbegin specifying the start of an RTM region.
16805 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16806 const TargetInstrInfo *TII) {
16807 DebugLoc DL = MI->getDebugLoc();
16809 const BasicBlock *BB = MBB->getBasicBlock();
16810 MachineFunction::iterator I = MBB;
16813 // For the v = xbegin(), we generate
16824 MachineBasicBlock *thisMBB = MBB;
16825 MachineFunction *MF = MBB->getParent();
16826 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16827 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16828 MF->insert(I, mainMBB);
16829 MF->insert(I, sinkMBB);
16831 // Transfer the remainder of BB and its successor edges to sinkMBB.
16832 sinkMBB->splice(sinkMBB->begin(), MBB,
16833 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16834 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16838 // # fallthrough to mainMBB
16839 // # abortion to sinkMBB
16840 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16841 thisMBB->addSuccessor(mainMBB);
16842 thisMBB->addSuccessor(sinkMBB);
16846 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16847 mainMBB->addSuccessor(sinkMBB);
16850 // EAX is live into the sinkMBB
16851 sinkMBB->addLiveIn(X86::EAX);
16852 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16853 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16856 MI->eraseFromParent();
16860 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16861 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16862 // in the .td file.
16863 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16864 const TargetInstrInfo *TII) {
16866 switch (MI->getOpcode()) {
16867 default: llvm_unreachable("illegal opcode!");
16868 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
16869 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16870 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
16871 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16872 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
16873 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16874 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
16875 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16878 DebugLoc dl = MI->getDebugLoc();
16879 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16881 unsigned NumArgs = MI->getNumOperands();
16882 for (unsigned i = 1; i < NumArgs; ++i) {
16883 MachineOperand &Op = MI->getOperand(i);
16884 if (!(Op.isReg() && Op.isImplicit()))
16885 MIB.addOperand(Op);
16887 if (MI->hasOneMemOperand())
16888 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16890 BuildMI(*BB, MI, dl,
16891 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16892 .addReg(X86::XMM0);
16894 MI->eraseFromParent();
16898 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16899 // defs in an instruction pattern
16900 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16901 const TargetInstrInfo *TII) {
16903 switch (MI->getOpcode()) {
16904 default: llvm_unreachable("illegal opcode!");
16905 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
16906 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16907 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
16908 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16909 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
16910 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16911 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
16912 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16915 DebugLoc dl = MI->getDebugLoc();
16916 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16918 unsigned NumArgs = MI->getNumOperands(); // remove the results
16919 for (unsigned i = 1; i < NumArgs; ++i) {
16920 MachineOperand &Op = MI->getOperand(i);
16921 if (!(Op.isReg() && Op.isImplicit()))
16922 MIB.addOperand(Op);
16924 if (MI->hasOneMemOperand())
16925 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16927 BuildMI(*BB, MI, dl,
16928 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16931 MI->eraseFromParent();
16935 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16936 const TargetInstrInfo *TII,
16937 const X86Subtarget* Subtarget) {
16938 DebugLoc dl = MI->getDebugLoc();
16940 // Address into RAX/EAX, other two args into ECX, EDX.
16941 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16942 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16943 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16944 for (int i = 0; i < X86::AddrNumOperands; ++i)
16945 MIB.addOperand(MI->getOperand(i));
16947 unsigned ValOps = X86::AddrNumOperands;
16948 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16949 .addReg(MI->getOperand(ValOps).getReg());
16950 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16951 .addReg(MI->getOperand(ValOps+1).getReg());
16953 // The instruction doesn't actually take any operands though.
16954 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16956 MI->eraseFromParent(); // The pseudo is gone now.
16960 MachineBasicBlock *
16961 X86TargetLowering::EmitVAARG64WithCustomInserter(
16963 MachineBasicBlock *MBB) const {
16964 // Emit va_arg instruction on X86-64.
16966 // Operands to this pseudo-instruction:
16967 // 0 ) Output : destination address (reg)
16968 // 1-5) Input : va_list address (addr, i64mem)
16969 // 6 ) ArgSize : Size (in bytes) of vararg type
16970 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16971 // 8 ) Align : Alignment of type
16972 // 9 ) EFLAGS (implicit-def)
16974 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16975 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16977 unsigned DestReg = MI->getOperand(0).getReg();
16978 MachineOperand &Base = MI->getOperand(1);
16979 MachineOperand &Scale = MI->getOperand(2);
16980 MachineOperand &Index = MI->getOperand(3);
16981 MachineOperand &Disp = MI->getOperand(4);
16982 MachineOperand &Segment = MI->getOperand(5);
16983 unsigned ArgSize = MI->getOperand(6).getImm();
16984 unsigned ArgMode = MI->getOperand(7).getImm();
16985 unsigned Align = MI->getOperand(8).getImm();
16987 // Memory Reference
16988 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16989 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16990 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16992 // Machine Information
16993 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16994 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16995 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16996 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16997 DebugLoc DL = MI->getDebugLoc();
16999 // struct va_list {
17002 // i64 overflow_area (address)
17003 // i64 reg_save_area (address)
17005 // sizeof(va_list) = 24
17006 // alignment(va_list) = 8
17008 unsigned TotalNumIntRegs = 6;
17009 unsigned TotalNumXMMRegs = 8;
17010 bool UseGPOffset = (ArgMode == 1);
17011 bool UseFPOffset = (ArgMode == 2);
17012 unsigned MaxOffset = TotalNumIntRegs * 8 +
17013 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17015 /* Align ArgSize to a multiple of 8 */
17016 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17017 bool NeedsAlign = (Align > 8);
17019 MachineBasicBlock *thisMBB = MBB;
17020 MachineBasicBlock *overflowMBB;
17021 MachineBasicBlock *offsetMBB;
17022 MachineBasicBlock *endMBB;
17024 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17025 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17026 unsigned OffsetReg = 0;
17028 if (!UseGPOffset && !UseFPOffset) {
17029 // If we only pull from the overflow region, we don't create a branch.
17030 // We don't need to alter control flow.
17031 OffsetDestReg = 0; // unused
17032 OverflowDestReg = DestReg;
17034 offsetMBB = nullptr;
17035 overflowMBB = thisMBB;
17038 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17039 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17040 // If not, pull from overflow_area. (branch to overflowMBB)
17045 // offsetMBB overflowMBB
17050 // Registers for the PHI in endMBB
17051 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17052 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17054 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17055 MachineFunction *MF = MBB->getParent();
17056 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17057 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17058 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17060 MachineFunction::iterator MBBIter = MBB;
17063 // Insert the new basic blocks
17064 MF->insert(MBBIter, offsetMBB);
17065 MF->insert(MBBIter, overflowMBB);
17066 MF->insert(MBBIter, endMBB);
17068 // Transfer the remainder of MBB and its successor edges to endMBB.
17069 endMBB->splice(endMBB->begin(), thisMBB,
17070 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17071 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17073 // Make offsetMBB and overflowMBB successors of thisMBB
17074 thisMBB->addSuccessor(offsetMBB);
17075 thisMBB->addSuccessor(overflowMBB);
17077 // endMBB is a successor of both offsetMBB and overflowMBB
17078 offsetMBB->addSuccessor(endMBB);
17079 overflowMBB->addSuccessor(endMBB);
17081 // Load the offset value into a register
17082 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17083 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17087 .addDisp(Disp, UseFPOffset ? 4 : 0)
17088 .addOperand(Segment)
17089 .setMemRefs(MMOBegin, MMOEnd);
17091 // Check if there is enough room left to pull this argument.
17092 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17094 .addImm(MaxOffset + 8 - ArgSizeA8);
17096 // Branch to "overflowMBB" if offset >= max
17097 // Fall through to "offsetMBB" otherwise
17098 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17099 .addMBB(overflowMBB);
17102 // In offsetMBB, emit code to use the reg_save_area.
17104 assert(OffsetReg != 0);
17106 // Read the reg_save_area address.
17107 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17108 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17113 .addOperand(Segment)
17114 .setMemRefs(MMOBegin, MMOEnd);
17116 // Zero-extend the offset
17117 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17118 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17121 .addImm(X86::sub_32bit);
17123 // Add the offset to the reg_save_area to get the final address.
17124 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17125 .addReg(OffsetReg64)
17126 .addReg(RegSaveReg);
17128 // Compute the offset for the next argument
17129 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17130 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17132 .addImm(UseFPOffset ? 16 : 8);
17134 // Store it back into the va_list.
17135 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17139 .addDisp(Disp, UseFPOffset ? 4 : 0)
17140 .addOperand(Segment)
17141 .addReg(NextOffsetReg)
17142 .setMemRefs(MMOBegin, MMOEnd);
17145 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17150 // Emit code to use overflow area
17153 // Load the overflow_area address into a register.
17154 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17155 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17160 .addOperand(Segment)
17161 .setMemRefs(MMOBegin, MMOEnd);
17163 // If we need to align it, do so. Otherwise, just copy the address
17164 // to OverflowDestReg.
17166 // Align the overflow address
17167 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17168 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17170 // aligned_addr = (addr + (align-1)) & ~(align-1)
17171 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17172 .addReg(OverflowAddrReg)
17175 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17177 .addImm(~(uint64_t)(Align-1));
17179 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17180 .addReg(OverflowAddrReg);
17183 // Compute the next overflow address after this argument.
17184 // (the overflow address should be kept 8-byte aligned)
17185 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17186 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17187 .addReg(OverflowDestReg)
17188 .addImm(ArgSizeA8);
17190 // Store the new overflow address.
17191 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17196 .addOperand(Segment)
17197 .addReg(NextAddrReg)
17198 .setMemRefs(MMOBegin, MMOEnd);
17200 // If we branched, emit the PHI to the front of endMBB.
17202 BuildMI(*endMBB, endMBB->begin(), DL,
17203 TII->get(X86::PHI), DestReg)
17204 .addReg(OffsetDestReg).addMBB(offsetMBB)
17205 .addReg(OverflowDestReg).addMBB(overflowMBB);
17208 // Erase the pseudo instruction
17209 MI->eraseFromParent();
17214 MachineBasicBlock *
17215 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17217 MachineBasicBlock *MBB) const {
17218 // Emit code to save XMM registers to the stack. The ABI says that the
17219 // number of registers to save is given in %al, so it's theoretically
17220 // possible to do an indirect jump trick to avoid saving all of them,
17221 // however this code takes a simpler approach and just executes all
17222 // of the stores if %al is non-zero. It's less code, and it's probably
17223 // easier on the hardware branch predictor, and stores aren't all that
17224 // expensive anyway.
17226 // Create the new basic blocks. One block contains all the XMM stores,
17227 // and one block is the final destination regardless of whether any
17228 // stores were performed.
17229 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17230 MachineFunction *F = MBB->getParent();
17231 MachineFunction::iterator MBBIter = MBB;
17233 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17234 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17235 F->insert(MBBIter, XMMSaveMBB);
17236 F->insert(MBBIter, EndMBB);
17238 // Transfer the remainder of MBB and its successor edges to EndMBB.
17239 EndMBB->splice(EndMBB->begin(), MBB,
17240 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17241 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17243 // The original block will now fall through to the XMM save block.
17244 MBB->addSuccessor(XMMSaveMBB);
17245 // The XMMSaveMBB will fall through to the end block.
17246 XMMSaveMBB->addSuccessor(EndMBB);
17248 // Now add the instructions.
17249 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17250 DebugLoc DL = MI->getDebugLoc();
17252 unsigned CountReg = MI->getOperand(0).getReg();
17253 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17254 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17256 if (!Subtarget->isTargetWin64()) {
17257 // If %al is 0, branch around the XMM save block.
17258 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17259 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17260 MBB->addSuccessor(EndMBB);
17263 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17264 // that was just emitted, but clearly shouldn't be "saved".
17265 assert((MI->getNumOperands() <= 3 ||
17266 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17267 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17268 && "Expected last argument to be EFLAGS");
17269 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17270 // In the XMM save block, save all the XMM argument registers.
17271 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17272 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17273 MachineMemOperand *MMO =
17274 F->getMachineMemOperand(
17275 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17276 MachineMemOperand::MOStore,
17277 /*Size=*/16, /*Align=*/16);
17278 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17279 .addFrameIndex(RegSaveFrameIndex)
17280 .addImm(/*Scale=*/1)
17281 .addReg(/*IndexReg=*/0)
17282 .addImm(/*Disp=*/Offset)
17283 .addReg(/*Segment=*/0)
17284 .addReg(MI->getOperand(i).getReg())
17285 .addMemOperand(MMO);
17288 MI->eraseFromParent(); // The pseudo instruction is gone now.
17293 // The EFLAGS operand of SelectItr might be missing a kill marker
17294 // because there were multiple uses of EFLAGS, and ISel didn't know
17295 // which to mark. Figure out whether SelectItr should have had a
17296 // kill marker, and set it if it should. Returns the correct kill
17298 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17299 MachineBasicBlock* BB,
17300 const TargetRegisterInfo* TRI) {
17301 // Scan forward through BB for a use/def of EFLAGS.
17302 MachineBasicBlock::iterator miI(std::next(SelectItr));
17303 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17304 const MachineInstr& mi = *miI;
17305 if (mi.readsRegister(X86::EFLAGS))
17307 if (mi.definesRegister(X86::EFLAGS))
17308 break; // Should have kill-flag - update below.
17311 // If we hit the end of the block, check whether EFLAGS is live into a
17313 if (miI == BB->end()) {
17314 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17315 sEnd = BB->succ_end();
17316 sItr != sEnd; ++sItr) {
17317 MachineBasicBlock* succ = *sItr;
17318 if (succ->isLiveIn(X86::EFLAGS))
17323 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17324 // out. SelectMI should have a kill flag on EFLAGS.
17325 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17329 MachineBasicBlock *
17330 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17331 MachineBasicBlock *BB) const {
17332 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17333 DebugLoc DL = MI->getDebugLoc();
17335 // To "insert" a SELECT_CC instruction, we actually have to insert the
17336 // diamond control-flow pattern. The incoming instruction knows the
17337 // destination vreg to set, the condition code register to branch on, the
17338 // true/false values to select between, and a branch opcode to use.
17339 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17340 MachineFunction::iterator It = BB;
17346 // cmpTY ccX, r1, r2
17348 // fallthrough --> copy0MBB
17349 MachineBasicBlock *thisMBB = BB;
17350 MachineFunction *F = BB->getParent();
17351 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17352 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17353 F->insert(It, copy0MBB);
17354 F->insert(It, sinkMBB);
17356 // If the EFLAGS register isn't dead in the terminator, then claim that it's
17357 // live into the sink and copy blocks.
17358 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17359 if (!MI->killsRegister(X86::EFLAGS) &&
17360 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17361 copy0MBB->addLiveIn(X86::EFLAGS);
17362 sinkMBB->addLiveIn(X86::EFLAGS);
17365 // Transfer the remainder of BB and its successor edges to sinkMBB.
17366 sinkMBB->splice(sinkMBB->begin(), BB,
17367 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17368 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17370 // Add the true and fallthrough blocks as its successors.
17371 BB->addSuccessor(copy0MBB);
17372 BB->addSuccessor(sinkMBB);
17374 // Create the conditional branch instruction.
17376 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17377 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17380 // %FalseValue = ...
17381 // # fallthrough to sinkMBB
17382 copy0MBB->addSuccessor(sinkMBB);
17385 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17387 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17388 TII->get(X86::PHI), MI->getOperand(0).getReg())
17389 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17390 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17392 MI->eraseFromParent(); // The pseudo instruction is gone now.
17396 MachineBasicBlock *
17397 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17398 bool Is64Bit) const {
17399 MachineFunction *MF = BB->getParent();
17400 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17401 DebugLoc DL = MI->getDebugLoc();
17402 const BasicBlock *LLVM_BB = BB->getBasicBlock();
17404 assert(MF->shouldSplitStack());
17406 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17407 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17410 // ... [Till the alloca]
17411 // If stacklet is not large enough, jump to mallocMBB
17414 // Allocate by subtracting from RSP
17415 // Jump to continueMBB
17418 // Allocate by call to runtime
17422 // [rest of original BB]
17425 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17426 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17427 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17429 MachineRegisterInfo &MRI = MF->getRegInfo();
17430 const TargetRegisterClass *AddrRegClass =
17431 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17433 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17434 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17435 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17436 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17437 sizeVReg = MI->getOperand(1).getReg(),
17438 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17440 MachineFunction::iterator MBBIter = BB;
17443 MF->insert(MBBIter, bumpMBB);
17444 MF->insert(MBBIter, mallocMBB);
17445 MF->insert(MBBIter, continueMBB);
17447 continueMBB->splice(continueMBB->begin(), BB,
17448 std::next(MachineBasicBlock::iterator(MI)), BB->end());
17449 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17451 // Add code to the main basic block to check if the stack limit has been hit,
17452 // and if so, jump to mallocMBB otherwise to bumpMBB.
17453 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17454 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17455 .addReg(tmpSPVReg).addReg(sizeVReg);
17456 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17457 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17458 .addReg(SPLimitVReg);
17459 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17461 // bumpMBB simply decreases the stack pointer, since we know the current
17462 // stacklet has enough space.
17463 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17464 .addReg(SPLimitVReg);
17465 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17466 .addReg(SPLimitVReg);
17467 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17469 // Calls into a routine in libgcc to allocate more space from the heap.
17470 const uint32_t *RegMask =
17471 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17473 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17475 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17476 .addExternalSymbol("__morestack_allocate_stack_space")
17477 .addRegMask(RegMask)
17478 .addReg(X86::RDI, RegState::Implicit)
17479 .addReg(X86::RAX, RegState::ImplicitDefine);
17481 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17483 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17484 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17485 .addExternalSymbol("__morestack_allocate_stack_space")
17486 .addRegMask(RegMask)
17487 .addReg(X86::EAX, RegState::ImplicitDefine);
17491 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17494 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17495 .addReg(Is64Bit ? X86::RAX : X86::EAX);
17496 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17498 // Set up the CFG correctly.
17499 BB->addSuccessor(bumpMBB);
17500 BB->addSuccessor(mallocMBB);
17501 mallocMBB->addSuccessor(continueMBB);
17502 bumpMBB->addSuccessor(continueMBB);
17504 // Take care of the PHI nodes.
17505 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17506 MI->getOperand(0).getReg())
17507 .addReg(mallocPtrVReg).addMBB(mallocMBB)
17508 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17510 // Delete the original pseudo instruction.
17511 MI->eraseFromParent();
17514 return continueMBB;
17517 MachineBasicBlock *
17518 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17519 MachineBasicBlock *BB) const {
17520 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17521 DebugLoc DL = MI->getDebugLoc();
17523 assert(!Subtarget->isTargetMacho());
17525 // The lowering is pretty easy: we're just emitting the call to _alloca. The
17526 // non-trivial part is impdef of ESP.
17528 if (Subtarget->isTargetWin64()) {
17529 if (Subtarget->isTargetCygMing()) {
17530 // ___chkstk(Mingw64):
17531 // Clobbers R10, R11, RAX and EFLAGS.
17533 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17534 .addExternalSymbol("___chkstk")
17535 .addReg(X86::RAX, RegState::Implicit)
17536 .addReg(X86::RSP, RegState::Implicit)
17537 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17538 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17539 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17541 // __chkstk(MSVCRT): does not update stack pointer.
17542 // Clobbers R10, R11 and EFLAGS.
17543 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17544 .addExternalSymbol("__chkstk")
17545 .addReg(X86::RAX, RegState::Implicit)
17546 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17547 // RAX has the offset to be subtracted from RSP.
17548 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17553 const char *StackProbeSymbol =
17554 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17556 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17557 .addExternalSymbol(StackProbeSymbol)
17558 .addReg(X86::EAX, RegState::Implicit)
17559 .addReg(X86::ESP, RegState::Implicit)
17560 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17561 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17562 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17565 MI->eraseFromParent(); // The pseudo instruction is gone now.
17569 MachineBasicBlock *
17570 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17571 MachineBasicBlock *BB) const {
17572 // This is pretty easy. We're taking the value that we received from
17573 // our load from the relocation, sticking it in either RDI (x86-64)
17574 // or EAX and doing an indirect call. The return value will then
17575 // be in the normal return register.
17576 MachineFunction *F = BB->getParent();
17577 const X86InstrInfo *TII
17578 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17579 DebugLoc DL = MI->getDebugLoc();
17581 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17582 assert(MI->getOperand(3).isGlobal() && "This should be a global");
17584 // Get a register mask for the lowered call.
17585 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17586 // proper register mask.
17587 const uint32_t *RegMask =
17588 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17589 if (Subtarget->is64Bit()) {
17590 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17591 TII->get(X86::MOV64rm), X86::RDI)
17593 .addImm(0).addReg(0)
17594 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17595 MI->getOperand(3).getTargetFlags())
17597 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17598 addDirectMem(MIB, X86::RDI);
17599 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17600 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17601 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17602 TII->get(X86::MOV32rm), X86::EAX)
17604 .addImm(0).addReg(0)
17605 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17606 MI->getOperand(3).getTargetFlags())
17608 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17609 addDirectMem(MIB, X86::EAX);
17610 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17612 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17613 TII->get(X86::MOV32rm), X86::EAX)
17614 .addReg(TII->getGlobalBaseReg(F))
17615 .addImm(0).addReg(0)
17616 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17617 MI->getOperand(3).getTargetFlags())
17619 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17620 addDirectMem(MIB, X86::EAX);
17621 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17624 MI->eraseFromParent(); // The pseudo instruction is gone now.
17628 MachineBasicBlock *
17629 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17630 MachineBasicBlock *MBB) const {
17631 DebugLoc DL = MI->getDebugLoc();
17632 MachineFunction *MF = MBB->getParent();
17633 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17634 MachineRegisterInfo &MRI = MF->getRegInfo();
17636 const BasicBlock *BB = MBB->getBasicBlock();
17637 MachineFunction::iterator I = MBB;
17640 // Memory Reference
17641 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17642 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17645 unsigned MemOpndSlot = 0;
17647 unsigned CurOp = 0;
17649 DstReg = MI->getOperand(CurOp++).getReg();
17650 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17651 assert(RC->hasType(MVT::i32) && "Invalid destination!");
17652 unsigned mainDstReg = MRI.createVirtualRegister(RC);
17653 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17655 MemOpndSlot = CurOp;
17657 MVT PVT = getPointerTy();
17658 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17659 "Invalid Pointer Size!");
17661 // For v = setjmp(buf), we generate
17664 // buf[LabelOffset] = restoreMBB
17665 // SjLjSetup restoreMBB
17671 // v = phi(main, restore)
17676 MachineBasicBlock *thisMBB = MBB;
17677 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17678 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17679 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17680 MF->insert(I, mainMBB);
17681 MF->insert(I, sinkMBB);
17682 MF->push_back(restoreMBB);
17684 MachineInstrBuilder MIB;
17686 // Transfer the remainder of BB and its successor edges to sinkMBB.
17687 sinkMBB->splice(sinkMBB->begin(), MBB,
17688 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17689 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17692 unsigned PtrStoreOpc = 0;
17693 unsigned LabelReg = 0;
17694 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17695 Reloc::Model RM = MF->getTarget().getRelocationModel();
17696 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17697 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17699 // Prepare IP either in reg or imm.
17700 if (!UseImmLabel) {
17701 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17702 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17703 LabelReg = MRI.createVirtualRegister(PtrRC);
17704 if (Subtarget->is64Bit()) {
17705 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17709 .addMBB(restoreMBB)
17712 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17713 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17714 .addReg(XII->getGlobalBaseReg(MF))
17717 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17721 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17723 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17724 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17725 if (i == X86::AddrDisp)
17726 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17728 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17731 MIB.addReg(LabelReg);
17733 MIB.addMBB(restoreMBB);
17734 MIB.setMemRefs(MMOBegin, MMOEnd);
17736 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17737 .addMBB(restoreMBB);
17739 const X86RegisterInfo *RegInfo =
17740 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17741 MIB.addRegMask(RegInfo->getNoPreservedMask());
17742 thisMBB->addSuccessor(mainMBB);
17743 thisMBB->addSuccessor(restoreMBB);
17747 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17748 mainMBB->addSuccessor(sinkMBB);
17751 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17752 TII->get(X86::PHI), DstReg)
17753 .addReg(mainDstReg).addMBB(mainMBB)
17754 .addReg(restoreDstReg).addMBB(restoreMBB);
17757 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17758 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17759 restoreMBB->addSuccessor(sinkMBB);
17761 MI->eraseFromParent();
17765 MachineBasicBlock *
17766 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17767 MachineBasicBlock *MBB) const {
17768 DebugLoc DL = MI->getDebugLoc();
17769 MachineFunction *MF = MBB->getParent();
17770 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17771 MachineRegisterInfo &MRI = MF->getRegInfo();
17773 // Memory Reference
17774 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17775 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17777 MVT PVT = getPointerTy();
17778 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17779 "Invalid Pointer Size!");
17781 const TargetRegisterClass *RC =
17782 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17783 unsigned Tmp = MRI.createVirtualRegister(RC);
17784 // Since FP is only updated here but NOT referenced, it's treated as GPR.
17785 const X86RegisterInfo *RegInfo =
17786 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17787 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17788 unsigned SP = RegInfo->getStackRegister();
17790 MachineInstrBuilder MIB;
17792 const int64_t LabelOffset = 1 * PVT.getStoreSize();
17793 const int64_t SPOffset = 2 * PVT.getStoreSize();
17795 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17796 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17799 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17800 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17801 MIB.addOperand(MI->getOperand(i));
17802 MIB.setMemRefs(MMOBegin, MMOEnd);
17804 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17805 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17806 if (i == X86::AddrDisp)
17807 MIB.addDisp(MI->getOperand(i), LabelOffset);
17809 MIB.addOperand(MI->getOperand(i));
17811 MIB.setMemRefs(MMOBegin, MMOEnd);
17813 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17814 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17815 if (i == X86::AddrDisp)
17816 MIB.addDisp(MI->getOperand(i), SPOffset);
17818 MIB.addOperand(MI->getOperand(i));
17820 MIB.setMemRefs(MMOBegin, MMOEnd);
17822 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17824 MI->eraseFromParent();
17828 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17829 // accumulator loops. Writing back to the accumulator allows the coalescer
17830 // to remove extra copies in the loop.
17831 MachineBasicBlock *
17832 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17833 MachineBasicBlock *MBB) const {
17834 MachineOperand &AddendOp = MI->getOperand(3);
17836 // Bail out early if the addend isn't a register - we can't switch these.
17837 if (!AddendOp.isReg())
17840 MachineFunction &MF = *MBB->getParent();
17841 MachineRegisterInfo &MRI = MF.getRegInfo();
17843 // Check whether the addend is defined by a PHI:
17844 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17845 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17846 if (!AddendDef.isPHI())
17849 // Look for the following pattern:
17851 // %addend = phi [%entry, 0], [%loop, %result]
17853 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17857 // %addend = phi [%entry, 0], [%loop, %result]
17859 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17861 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17862 assert(AddendDef.getOperand(i).isReg());
17863 MachineOperand PHISrcOp = AddendDef.getOperand(i);
17864 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17865 if (&PHISrcInst == MI) {
17866 // Found a matching instruction.
17867 unsigned NewFMAOpc = 0;
17868 switch (MI->getOpcode()) {
17869 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17870 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17871 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17872 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17873 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17874 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17875 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17876 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17877 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17878 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17879 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17880 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17881 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17882 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17883 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17884 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17885 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17886 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17887 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17888 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17889 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17890 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17891 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17892 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17893 default: llvm_unreachable("Unrecognized FMA variant.");
17896 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17897 MachineInstrBuilder MIB =
17898 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17899 .addOperand(MI->getOperand(0))
17900 .addOperand(MI->getOperand(3))
17901 .addOperand(MI->getOperand(2))
17902 .addOperand(MI->getOperand(1));
17903 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17904 MI->eraseFromParent();
17911 MachineBasicBlock *
17912 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17913 MachineBasicBlock *BB) const {
17914 switch (MI->getOpcode()) {
17915 default: llvm_unreachable("Unexpected instr type to insert");
17916 case X86::TAILJMPd64:
17917 case X86::TAILJMPr64:
17918 case X86::TAILJMPm64:
17919 llvm_unreachable("TAILJMP64 would not be touched here.");
17920 case X86::TCRETURNdi64:
17921 case X86::TCRETURNri64:
17922 case X86::TCRETURNmi64:
17924 case X86::WIN_ALLOCA:
17925 return EmitLoweredWinAlloca(MI, BB);
17926 case X86::SEG_ALLOCA_32:
17927 return EmitLoweredSegAlloca(MI, BB, false);
17928 case X86::SEG_ALLOCA_64:
17929 return EmitLoweredSegAlloca(MI, BB, true);
17930 case X86::TLSCall_32:
17931 case X86::TLSCall_64:
17932 return EmitLoweredTLSCall(MI, BB);
17933 case X86::CMOV_GR8:
17934 case X86::CMOV_FR32:
17935 case X86::CMOV_FR64:
17936 case X86::CMOV_V4F32:
17937 case X86::CMOV_V2F64:
17938 case X86::CMOV_V2I64:
17939 case X86::CMOV_V8F32:
17940 case X86::CMOV_V4F64:
17941 case X86::CMOV_V4I64:
17942 case X86::CMOV_V16F32:
17943 case X86::CMOV_V8F64:
17944 case X86::CMOV_V8I64:
17945 case X86::CMOV_GR16:
17946 case X86::CMOV_GR32:
17947 case X86::CMOV_RFP32:
17948 case X86::CMOV_RFP64:
17949 case X86::CMOV_RFP80:
17950 return EmitLoweredSelect(MI, BB);
17952 case X86::FP32_TO_INT16_IN_MEM:
17953 case X86::FP32_TO_INT32_IN_MEM:
17954 case X86::FP32_TO_INT64_IN_MEM:
17955 case X86::FP64_TO_INT16_IN_MEM:
17956 case X86::FP64_TO_INT32_IN_MEM:
17957 case X86::FP64_TO_INT64_IN_MEM:
17958 case X86::FP80_TO_INT16_IN_MEM:
17959 case X86::FP80_TO_INT32_IN_MEM:
17960 case X86::FP80_TO_INT64_IN_MEM: {
17961 MachineFunction *F = BB->getParent();
17962 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
17963 DebugLoc DL = MI->getDebugLoc();
17965 // Change the floating point control register to use "round towards zero"
17966 // mode when truncating to an integer value.
17967 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17968 addFrameReference(BuildMI(*BB, MI, DL,
17969 TII->get(X86::FNSTCW16m)), CWFrameIdx);
17971 // Load the old value of the high byte of the control word...
17973 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17974 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17977 // Set the high part to be round to zero...
17978 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17981 // Reload the modified control word now...
17982 addFrameReference(BuildMI(*BB, MI, DL,
17983 TII->get(X86::FLDCW16m)), CWFrameIdx);
17985 // Restore the memory image of control word to original value
17986 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17989 // Get the X86 opcode to use.
17991 switch (MI->getOpcode()) {
17992 default: llvm_unreachable("illegal opcode!");
17993 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17994 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17995 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17996 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17997 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17998 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17999 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18000 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18001 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18005 MachineOperand &Op = MI->getOperand(0);
18007 AM.BaseType = X86AddressMode::RegBase;
18008 AM.Base.Reg = Op.getReg();
18010 AM.BaseType = X86AddressMode::FrameIndexBase;
18011 AM.Base.FrameIndex = Op.getIndex();
18013 Op = MI->getOperand(1);
18015 AM.Scale = Op.getImm();
18016 Op = MI->getOperand(2);
18018 AM.IndexReg = Op.getImm();
18019 Op = MI->getOperand(3);
18020 if (Op.isGlobal()) {
18021 AM.GV = Op.getGlobal();
18023 AM.Disp = Op.getImm();
18025 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18026 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18028 // Reload the original control word now.
18029 addFrameReference(BuildMI(*BB, MI, DL,
18030 TII->get(X86::FLDCW16m)), CWFrameIdx);
18032 MI->eraseFromParent(); // The pseudo instruction is gone now.
18035 // String/text processing lowering.
18036 case X86::PCMPISTRM128REG:
18037 case X86::VPCMPISTRM128REG:
18038 case X86::PCMPISTRM128MEM:
18039 case X86::VPCMPISTRM128MEM:
18040 case X86::PCMPESTRM128REG:
18041 case X86::VPCMPESTRM128REG:
18042 case X86::PCMPESTRM128MEM:
18043 case X86::VPCMPESTRM128MEM:
18044 assert(Subtarget->hasSSE42() &&
18045 "Target must have SSE4.2 or AVX features enabled");
18046 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18048 // String/text processing lowering.
18049 case X86::PCMPISTRIREG:
18050 case X86::VPCMPISTRIREG:
18051 case X86::PCMPISTRIMEM:
18052 case X86::VPCMPISTRIMEM:
18053 case X86::PCMPESTRIREG:
18054 case X86::VPCMPESTRIREG:
18055 case X86::PCMPESTRIMEM:
18056 case X86::VPCMPESTRIMEM:
18057 assert(Subtarget->hasSSE42() &&
18058 "Target must have SSE4.2 or AVX features enabled");
18059 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18061 // Thread synchronization.
18063 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18067 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18069 case X86::VASTART_SAVE_XMM_REGS:
18070 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18072 case X86::VAARG_64:
18073 return EmitVAARG64WithCustomInserter(MI, BB);
18075 case X86::EH_SjLj_SetJmp32:
18076 case X86::EH_SjLj_SetJmp64:
18077 return emitEHSjLjSetJmp(MI, BB);
18079 case X86::EH_SjLj_LongJmp32:
18080 case X86::EH_SjLj_LongJmp64:
18081 return emitEHSjLjLongJmp(MI, BB);
18083 case TargetOpcode::STACKMAP:
18084 case TargetOpcode::PATCHPOINT:
18085 return emitPatchPoint(MI, BB);
18087 case X86::VFMADDPDr213r:
18088 case X86::VFMADDPSr213r:
18089 case X86::VFMADDSDr213r:
18090 case X86::VFMADDSSr213r:
18091 case X86::VFMSUBPDr213r:
18092 case X86::VFMSUBPSr213r:
18093 case X86::VFMSUBSDr213r:
18094 case X86::VFMSUBSSr213r:
18095 case X86::VFNMADDPDr213r:
18096 case X86::VFNMADDPSr213r:
18097 case X86::VFNMADDSDr213r:
18098 case X86::VFNMADDSSr213r:
18099 case X86::VFNMSUBPDr213r:
18100 case X86::VFNMSUBPSr213r:
18101 case X86::VFNMSUBSDr213r:
18102 case X86::VFNMSUBSSr213r:
18103 case X86::VFMADDPDr213rY:
18104 case X86::VFMADDPSr213rY:
18105 case X86::VFMSUBPDr213rY:
18106 case X86::VFMSUBPSr213rY:
18107 case X86::VFNMADDPDr213rY:
18108 case X86::VFNMADDPSr213rY:
18109 case X86::VFNMSUBPDr213rY:
18110 case X86::VFNMSUBPSr213rY:
18111 return emitFMA3Instr(MI, BB);
18115 //===----------------------------------------------------------------------===//
18116 // X86 Optimization Hooks
18117 //===----------------------------------------------------------------------===//
18119 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18122 const SelectionDAG &DAG,
18123 unsigned Depth) const {
18124 unsigned BitWidth = KnownZero.getBitWidth();
18125 unsigned Opc = Op.getOpcode();
18126 assert((Opc >= ISD::BUILTIN_OP_END ||
18127 Opc == ISD::INTRINSIC_WO_CHAIN ||
18128 Opc == ISD::INTRINSIC_W_CHAIN ||
18129 Opc == ISD::INTRINSIC_VOID) &&
18130 "Should use MaskedValueIsZero if you don't know whether Op"
18131 " is a target node!");
18133 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
18147 // These nodes' second result is a boolean.
18148 if (Op.getResNo() == 0)
18151 case X86ISD::SETCC:
18152 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18154 case ISD::INTRINSIC_WO_CHAIN: {
18155 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18156 unsigned NumLoBits = 0;
18159 case Intrinsic::x86_sse_movmsk_ps:
18160 case Intrinsic::x86_avx_movmsk_ps_256:
18161 case Intrinsic::x86_sse2_movmsk_pd:
18162 case Intrinsic::x86_avx_movmsk_pd_256:
18163 case Intrinsic::x86_mmx_pmovmskb:
18164 case Intrinsic::x86_sse2_pmovmskb_128:
18165 case Intrinsic::x86_avx2_pmovmskb: {
18166 // High bits of movmskp{s|d}, pmovmskb are known zero.
18168 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18169 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
18170 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
18171 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
18172 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
18173 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
18174 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
18175 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
18177 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18186 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18188 const SelectionDAG &,
18189 unsigned Depth) const {
18190 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18191 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18192 return Op.getValueType().getScalarType().getSizeInBits();
18198 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18199 /// node is a GlobalAddress + offset.
18200 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18201 const GlobalValue* &GA,
18202 int64_t &Offset) const {
18203 if (N->getOpcode() == X86ISD::Wrapper) {
18204 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18205 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18206 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18210 return TargetLowering::isGAPlusOffset(N, GA, Offset);
18213 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18214 /// same as extracting the high 128-bit part of 256-bit vector and then
18215 /// inserting the result into the low part of a new 256-bit vector
18216 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18217 EVT VT = SVOp->getValueType(0);
18218 unsigned NumElems = VT.getVectorNumElements();
18220 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18221 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18222 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18223 SVOp->getMaskElt(j) >= 0)
18229 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18230 /// same as extracting the low 128-bit part of 256-bit vector and then
18231 /// inserting the result into the high part of a new 256-bit vector
18232 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18233 EVT VT = SVOp->getValueType(0);
18234 unsigned NumElems = VT.getVectorNumElements();
18236 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18237 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18238 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18239 SVOp->getMaskElt(j) >= 0)
18245 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18246 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18247 TargetLowering::DAGCombinerInfo &DCI,
18248 const X86Subtarget* Subtarget) {
18250 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18251 SDValue V1 = SVOp->getOperand(0);
18252 SDValue V2 = SVOp->getOperand(1);
18253 EVT VT = SVOp->getValueType(0);
18254 unsigned NumElems = VT.getVectorNumElements();
18256 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18257 V2.getOpcode() == ISD::CONCAT_VECTORS) {
18261 // V UNDEF BUILD_VECTOR UNDEF
18263 // CONCAT_VECTOR CONCAT_VECTOR
18266 // RESULT: V + zero extended
18268 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18269 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18270 V1.getOperand(1).getOpcode() != ISD::UNDEF)
18273 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18276 // To match the shuffle mask, the first half of the mask should
18277 // be exactly the first vector, and all the rest a splat with the
18278 // first element of the second one.
18279 for (unsigned i = 0; i != NumElems/2; ++i)
18280 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18281 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18284 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18285 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18286 if (Ld->hasNUsesOfValue(1, 0)) {
18287 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18288 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18290 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18292 Ld->getPointerInfo(),
18293 Ld->getAlignment(),
18294 false/*isVolatile*/, true/*ReadMem*/,
18295 false/*WriteMem*/);
18297 // Make sure the newly-created LOAD is in the same position as Ld in
18298 // terms of dependency. We create a TokenFactor for Ld and ResNode,
18299 // and update uses of Ld's output chain to use the TokenFactor.
18300 if (Ld->hasAnyUseOfValue(1)) {
18301 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18302 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18303 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18304 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18305 SDValue(ResNode.getNode(), 1));
18308 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18312 // Emit a zeroed vector and insert the desired subvector on its
18314 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18315 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18316 return DCI.CombineTo(N, InsV);
18319 //===--------------------------------------------------------------------===//
18320 // Combine some shuffles into subvector extracts and inserts:
18323 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18324 if (isShuffleHigh128VectorInsertLow(SVOp)) {
18325 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18326 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18327 return DCI.CombineTo(N, InsV);
18330 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18331 if (isShuffleLow128VectorInsertHigh(SVOp)) {
18332 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18333 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18334 return DCI.CombineTo(N, InsV);
18340 /// \brief Get the PSHUF-style mask from PSHUF node.
18342 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18343 /// PSHUF-style masks that can be reused with such instructions.
18344 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18345 SmallVector<int, 4> Mask;
18347 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18351 switch (N.getOpcode()) {
18352 case X86ISD::PSHUFD:
18354 case X86ISD::PSHUFLW:
18357 case X86ISD::PSHUFHW:
18358 Mask.erase(Mask.begin(), Mask.begin() + 4);
18359 for (int &M : Mask)
18363 llvm_unreachable("No valid shuffle instruction found!");
18367 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18369 /// We walk up the chain and look for a combinable shuffle, skipping over
18370 /// shuffles that we could hoist this shuffle's transformation past without
18371 /// altering anything.
18372 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18374 TargetLowering::DAGCombinerInfo &DCI) {
18375 assert(N.getOpcode() == X86ISD::PSHUFD &&
18376 "Called with something other than an x86 128-bit half shuffle!");
18379 // Walk up a single-use chain looking for a combinable shuffle.
18380 SDValue V = N.getOperand(0);
18381 for (; V.hasOneUse(); V = V.getOperand(0)) {
18382 switch (V.getOpcode()) {
18384 return false; // Nothing combined!
18387 // Skip bitcasts as we always know the type for the target specific
18391 case X86ISD::PSHUFD:
18392 // Found another dword shuffle.
18395 case X86ISD::PSHUFLW:
18396 // Check that the low words (being shuffled) are the identity in the
18397 // dword shuffle, and the high words are self-contained.
18398 if (Mask[0] != 0 || Mask[1] != 1 ||
18399 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
18404 case X86ISD::PSHUFHW:
18405 // Check that the high words (being shuffled) are the identity in the
18406 // dword shuffle, and the low words are self-contained.
18407 if (Mask[2] != 2 || Mask[3] != 3 ||
18408 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
18413 // Break out of the loop if we break out of the switch.
18417 if (!V.hasOneUse())
18418 // We fell out of the loop without finding a viable combining instruction.
18421 // Record the old value to use in RAUW-ing.
18424 // Merge this node's mask and our incoming mask.
18425 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18426 for (int &M : Mask)
18428 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V.getOperand(0),
18429 getV4X86ShuffleImm8ForMask(Mask, DAG));
18431 // Replace N with its operand as we're going to combine that shuffle away.
18432 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18434 // Replace the combinable shuffle with the combined one, updating all users
18435 // so that we re-evaluate the chain here.
18436 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18440 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
18442 /// We walk up the chain, skipping shuffles of the other half and looking
18443 /// through shuffles which switch halves trying to find a shuffle of the same
18444 /// pair of dwords.
18445 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
18447 TargetLowering::DAGCombinerInfo &DCI) {
18449 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
18450 "Called with something other than an x86 128-bit half shuffle!");
18452 unsigned CombineOpcode = N.getOpcode();
18454 // Walk up a single-use chain looking for a combinable shuffle.
18455 SDValue V = N.getOperand(0);
18456 for (; V.hasOneUse(); V = V.getOperand(0)) {
18457 switch (V.getOpcode()) {
18459 return false; // Nothing combined!
18462 // Skip bitcasts as we always know the type for the target specific
18466 case X86ISD::PSHUFLW:
18467 case X86ISD::PSHUFHW:
18468 if (V.getOpcode() == CombineOpcode)
18471 // Other-half shuffles are no-ops.
18474 case X86ISD::PSHUFD: {
18475 // We can only handle pshufd if the half we are combining either stays in
18476 // its half, or switches to the other half. Bail if one of these isn't
18478 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18479 int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
18480 if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
18481 (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
18484 // Map the mask through the pshufd and keep walking up the chain.
18485 for (int i = 0; i < 4; ++i)
18486 Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
18488 // Switch halves if the pshufd does.
18490 VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18494 // Break out of the loop if we break out of the switch.
18498 if (!V.hasOneUse())
18499 // We fell out of the loop without finding a viable combining instruction.
18502 // Record the old value to use in RAUW-ing.
18505 // Merge this node's mask and our incoming mask (adjusted to account for all
18506 // the pshufd instructions encountered).
18507 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18508 for (int &M : Mask)
18510 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
18511 getV4X86ShuffleImm8ForMask(Mask, DAG));
18513 // Replace N with its operand as we're going to combine that shuffle away.
18514 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18516 // Replace the combinable shuffle with the combined one, updating all users
18517 // so that we re-evaluate the chain here.
18518 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18522 /// \brief Try to combine x86 target specific shuffles.
18523 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
18524 TargetLowering::DAGCombinerInfo &DCI,
18525 const X86Subtarget *Subtarget) {
18527 MVT VT = N.getSimpleValueType();
18528 SmallVector<int, 4> Mask;
18530 switch (N.getOpcode()) {
18531 case X86ISD::PSHUFD:
18532 case X86ISD::PSHUFLW:
18533 case X86ISD::PSHUFHW:
18534 Mask = getPSHUFShuffleMask(N);
18535 assert(Mask.size() == 4);
18541 // Nuke no-op shuffles that show up after combining.
18542 if (isNoopShuffleMask(Mask))
18543 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
18545 // Look for simplifications involving one or two shuffle instructions.
18546 SDValue V = N.getOperand(0);
18547 switch (N.getOpcode()) {
18550 case X86ISD::PSHUFLW:
18551 case X86ISD::PSHUFHW:
18552 assert(VT == MVT::v8i16);
18555 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
18556 return SDValue(); // We combined away this shuffle, so we're done.
18558 // See if this reduces to a PSHUFD which is no more expensive and can
18559 // combine with more operations.
18560 if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
18561 areAdjacentMasksSequential(Mask)) {
18562 int DMask[] = {-1, -1, -1, -1};
18563 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
18564 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
18565 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
18566 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
18567 DCI.AddToWorklist(V.getNode());
18568 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
18569 getV4X86ShuffleImm8ForMask(DMask, DAG));
18570 DCI.AddToWorklist(V.getNode());
18571 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
18576 case X86ISD::PSHUFD:
18577 if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
18578 return SDValue(); // We combined away this shuffle.
18586 /// PerformShuffleCombine - Performs several different shuffle combines.
18587 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
18588 TargetLowering::DAGCombinerInfo &DCI,
18589 const X86Subtarget *Subtarget) {
18591 SDValue N0 = N->getOperand(0);
18592 SDValue N1 = N->getOperand(1);
18593 EVT VT = N->getValueType(0);
18595 // Canonicalize shuffles that perform 'addsub' on packed float vectors
18596 // according to the rule:
18597 // (shuffle (FADD A, B), (FSUB A, B), Mask) ->
18598 // (shuffle (FSUB A, -B), (FADD A, -B), Mask)
18600 // Where 'Mask' is:
18601 // <0,5,2,7> -- for v4f32 and v4f64 shuffles;
18602 // <0,3> -- for v2f64 shuffles;
18603 // <0,9,2,11,4,13,6,15> -- for v8f32 shuffles.
18605 // This helps pattern-matching more SSE3/AVX ADDSUB instructions
18606 // during ISel stage.
18607 if (N->getOpcode() == ISD::VECTOR_SHUFFLE &&
18608 ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18609 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18610 N0->getOpcode() == ISD::FADD && N1->getOpcode() == ISD::FSUB &&
18611 // Operands to the FADD and FSUB must be the same.
18612 ((N0->getOperand(0) == N1->getOperand(0) &&
18613 N0->getOperand(1) == N1->getOperand(1)) ||
18614 // FADD is commutable. See if by commuting the operands of the FADD
18615 // we would still be able to match the operands of the FSUB dag node.
18616 (N0->getOperand(1) == N1->getOperand(0) &&
18617 N0->getOperand(0) == N1->getOperand(1))) &&
18618 N0->getOperand(0)->getOpcode() != ISD::UNDEF &&
18619 N0->getOperand(1)->getOpcode() != ISD::UNDEF) {
18621 ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
18622 unsigned NumElts = VT.getVectorNumElements();
18623 ArrayRef<int> Mask = SV->getMask();
18624 bool CanFold = true;
18626 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i)
18627 CanFold = Mask[i] == (int)((i & 1) ? i + NumElts : i);
18630 SDValue Op0 = N1->getOperand(0);
18631 SDValue Op1 = DAG.getNode(ISD::FNEG, dl, VT, N1->getOperand(1));
18632 SDValue Sub = DAG.getNode(ISD::FSUB, dl, VT, Op0, Op1);
18633 SDValue Add = DAG.getNode(ISD::FADD, dl, VT, Op0, Op1);
18634 return DAG.getVectorShuffle(VT, dl, Sub, Add, Mask);
18638 // Don't create instructions with illegal types after legalize types has run.
18639 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18640 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
18643 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
18644 if (Subtarget->hasFp256() && VT.is256BitVector() &&
18645 N->getOpcode() == ISD::VECTOR_SHUFFLE)
18646 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
18648 // During Type Legalization, when promoting illegal vector types,
18649 // the backend might introduce new shuffle dag nodes and bitcasts.
18651 // This code performs the following transformation:
18652 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
18653 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
18655 // We do this only if both the bitcast and the BINOP dag nodes have
18656 // one use. Also, perform this transformation only if the new binary
18657 // operation is legal. This is to avoid introducing dag nodes that
18658 // potentially need to be further expanded (or custom lowered) into a
18659 // less optimal sequence of dag nodes.
18660 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
18661 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
18662 N0.getOpcode() == ISD::BITCAST) {
18663 SDValue BC0 = N0.getOperand(0);
18664 EVT SVT = BC0.getValueType();
18665 unsigned Opcode = BC0.getOpcode();
18666 unsigned NumElts = VT.getVectorNumElements();
18668 if (BC0.hasOneUse() && SVT.isVector() &&
18669 SVT.getVectorNumElements() * 2 == NumElts &&
18670 TLI.isOperationLegal(Opcode, VT)) {
18671 bool CanFold = false;
18683 unsigned SVTNumElts = SVT.getVectorNumElements();
18684 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18685 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
18686 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
18687 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
18688 CanFold = SVOp->getMaskElt(i) < 0;
18691 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
18692 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
18693 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
18694 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
18699 // Only handle 128 wide vector from here on.
18700 if (!VT.is128BitVector())
18703 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
18704 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
18705 // consecutive, non-overlapping, and in the right order.
18706 SmallVector<SDValue, 16> Elts;
18707 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
18708 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
18710 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
18714 if (isTargetShuffle(N->getOpcode())) {
18716 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
18717 if (Shuffle.getNode())
18724 /// PerformTruncateCombine - Converts truncate operation to
18725 /// a sequence of vector shuffle operations.
18726 /// It is possible when we truncate 256-bit vector to 128-bit vector
18727 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
18728 TargetLowering::DAGCombinerInfo &DCI,
18729 const X86Subtarget *Subtarget) {
18733 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
18734 /// specific shuffle of a load can be folded into a single element load.
18735 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
18736 /// shuffles have been customed lowered so we need to handle those here.
18737 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
18738 TargetLowering::DAGCombinerInfo &DCI) {
18739 if (DCI.isBeforeLegalizeOps())
18742 SDValue InVec = N->getOperand(0);
18743 SDValue EltNo = N->getOperand(1);
18745 if (!isa<ConstantSDNode>(EltNo))
18748 EVT VT = InVec.getValueType();
18750 bool HasShuffleIntoBitcast = false;
18751 if (InVec.getOpcode() == ISD::BITCAST) {
18752 // Don't duplicate a load with other uses.
18753 if (!InVec.hasOneUse())
18755 EVT BCVT = InVec.getOperand(0).getValueType();
18756 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
18758 InVec = InVec.getOperand(0);
18759 HasShuffleIntoBitcast = true;
18762 if (!isTargetShuffle(InVec.getOpcode()))
18765 // Don't duplicate a load with other uses.
18766 if (!InVec.hasOneUse())
18769 SmallVector<int, 16> ShuffleMask;
18771 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18775 // Select the input vector, guarding against out of range extract vector.
18776 unsigned NumElems = VT.getVectorNumElements();
18777 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18778 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18779 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18780 : InVec.getOperand(1);
18782 // If inputs to shuffle are the same for both ops, then allow 2 uses
18783 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18785 if (LdNode.getOpcode() == ISD::BITCAST) {
18786 // Don't duplicate a load with other uses.
18787 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18790 AllowedUses = 1; // only allow 1 load use if we have a bitcast
18791 LdNode = LdNode.getOperand(0);
18794 if (!ISD::isNormalLoad(LdNode.getNode()))
18797 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
18799 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
18802 if (HasShuffleIntoBitcast) {
18803 // If there's a bitcast before the shuffle, check if the load type and
18804 // alignment is valid.
18805 unsigned Align = LN0->getAlignment();
18806 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18807 unsigned NewAlign = TLI.getDataLayout()->
18808 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
18810 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
18814 // All checks match so transform back to vector_shuffle so that DAG combiner
18815 // can finish the job
18818 // Create shuffle node taking into account the case that its a unary shuffle
18819 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
18820 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
18821 InVec.getOperand(0), Shuffle,
18823 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
18824 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
18828 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
18829 /// generation and convert it from being a bunch of shuffles and extracts
18830 /// to a simple store and scalar loads to extract the elements.
18831 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
18832 TargetLowering::DAGCombinerInfo &DCI) {
18833 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
18834 if (NewOp.getNode())
18837 SDValue InputVector = N->getOperand(0);
18839 // Detect whether we are trying to convert from mmx to i32 and the bitcast
18840 // from mmx to v2i32 has a single usage.
18841 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
18842 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
18843 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
18844 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
18845 N->getValueType(0),
18846 InputVector.getNode()->getOperand(0));
18848 // Only operate on vectors of 4 elements, where the alternative shuffling
18849 // gets to be more expensive.
18850 if (InputVector.getValueType() != MVT::v4i32)
18853 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
18854 // single use which is a sign-extend or zero-extend, and all elements are
18856 SmallVector<SDNode *, 4> Uses;
18857 unsigned ExtractedElements = 0;
18858 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
18859 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
18860 if (UI.getUse().getResNo() != InputVector.getResNo())
18863 SDNode *Extract = *UI;
18864 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
18867 if (Extract->getValueType(0) != MVT::i32)
18869 if (!Extract->hasOneUse())
18871 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
18872 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
18874 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
18877 // Record which element was extracted.
18878 ExtractedElements |=
18879 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
18881 Uses.push_back(Extract);
18884 // If not all the elements were used, this may not be worthwhile.
18885 if (ExtractedElements != 15)
18888 // Ok, we've now decided to do the transformation.
18889 SDLoc dl(InputVector);
18891 // Store the value to a temporary stack slot.
18892 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
18893 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
18894 MachinePointerInfo(), false, false, 0);
18896 // Replace each use (extract) with a load of the appropriate element.
18897 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
18898 UE = Uses.end(); UI != UE; ++UI) {
18899 SDNode *Extract = *UI;
18901 // cOMpute the element's address.
18902 SDValue Idx = Extract->getOperand(1);
18904 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
18905 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
18906 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18907 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
18909 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
18910 StackPtr, OffsetVal);
18912 // Load the scalar.
18913 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
18914 ScalarAddr, MachinePointerInfo(),
18915 false, false, false, 0);
18917 // Replace the exact with the load.
18918 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
18921 // The replacement was made in place; don't return anything.
18925 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
18926 static std::pair<unsigned, bool>
18927 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
18928 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
18929 if (!VT.isVector())
18930 return std::make_pair(0, false);
18932 bool NeedSplit = false;
18933 switch (VT.getSimpleVT().SimpleTy) {
18934 default: return std::make_pair(0, false);
18938 if (!Subtarget->hasAVX2())
18940 if (!Subtarget->hasAVX())
18941 return std::make_pair(0, false);
18946 if (!Subtarget->hasSSE2())
18947 return std::make_pair(0, false);
18950 // SSE2 has only a small subset of the operations.
18951 bool hasUnsigned = Subtarget->hasSSE41() ||
18952 (Subtarget->hasSSE2() && VT == MVT::v16i8);
18953 bool hasSigned = Subtarget->hasSSE41() ||
18954 (Subtarget->hasSSE2() && VT == MVT::v8i16);
18956 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18959 // Check for x CC y ? x : y.
18960 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18961 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18966 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18969 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18972 Opc = hasSigned ? X86ISD::SMIN : 0; break;
18975 Opc = hasSigned ? X86ISD::SMAX : 0; break;
18977 // Check for x CC y ? y : x -- a min/max with reversed arms.
18978 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18979 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18984 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18987 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18990 Opc = hasSigned ? X86ISD::SMAX : 0; break;
18993 Opc = hasSigned ? X86ISD::SMIN : 0; break;
18997 return std::make_pair(Opc, NeedSplit);
19001 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19002 const X86Subtarget *Subtarget) {
19004 SDValue Cond = N->getOperand(0);
19005 SDValue LHS = N->getOperand(1);
19006 SDValue RHS = N->getOperand(2);
19008 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19009 SDValue CondSrc = Cond->getOperand(0);
19010 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19011 Cond = CondSrc->getOperand(0);
19014 MVT VT = N->getSimpleValueType(0);
19015 MVT EltVT = VT.getVectorElementType();
19016 unsigned NumElems = VT.getVectorNumElements();
19017 // There is no blend with immediate in AVX-512.
19018 if (VT.is512BitVector())
19021 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19023 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19026 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19029 unsigned MaskValue = 0;
19030 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19033 SmallVector<int, 8> ShuffleMask(NumElems, -1);
19034 for (unsigned i = 0; i < NumElems; ++i) {
19035 // Be sure we emit undef where we can.
19036 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19037 ShuffleMask[i] = -1;
19039 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19042 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19045 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19047 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19048 TargetLowering::DAGCombinerInfo &DCI,
19049 const X86Subtarget *Subtarget) {
19051 SDValue Cond = N->getOperand(0);
19052 // Get the LHS/RHS of the select.
19053 SDValue LHS = N->getOperand(1);
19054 SDValue RHS = N->getOperand(2);
19055 EVT VT = LHS.getValueType();
19056 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19058 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19059 // instructions match the semantics of the common C idiom x<y?x:y but not
19060 // x<=y?x:y, because of how they handle negative zero (which can be
19061 // ignored in unsafe-math mode).
19062 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19063 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19064 (Subtarget->hasSSE2() ||
19065 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19066 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19068 unsigned Opcode = 0;
19069 // Check for x CC y ? x : y.
19070 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19071 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19075 // Converting this to a min would handle NaNs incorrectly, and swapping
19076 // the operands would cause it to handle comparisons between positive
19077 // and negative zero incorrectly.
19078 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19079 if (!DAG.getTarget().Options.UnsafeFPMath &&
19080 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19082 std::swap(LHS, RHS);
19084 Opcode = X86ISD::FMIN;
19087 // Converting this to a min would handle comparisons between positive
19088 // and negative zero incorrectly.
19089 if (!DAG.getTarget().Options.UnsafeFPMath &&
19090 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19092 Opcode = X86ISD::FMIN;
19095 // Converting this to a min would handle both negative zeros and NaNs
19096 // incorrectly, but we can swap the operands to fix both.
19097 std::swap(LHS, RHS);
19101 Opcode = X86ISD::FMIN;
19105 // Converting this to a max would handle comparisons between positive
19106 // and negative zero incorrectly.
19107 if (!DAG.getTarget().Options.UnsafeFPMath &&
19108 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19110 Opcode = X86ISD::FMAX;
19113 // Converting this to a max would handle NaNs incorrectly, and swapping
19114 // the operands would cause it to handle comparisons between positive
19115 // and negative zero incorrectly.
19116 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19117 if (!DAG.getTarget().Options.UnsafeFPMath &&
19118 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19120 std::swap(LHS, RHS);
19122 Opcode = X86ISD::FMAX;
19125 // Converting this to a max would handle both negative zeros and NaNs
19126 // incorrectly, but we can swap the operands to fix both.
19127 std::swap(LHS, RHS);
19131 Opcode = X86ISD::FMAX;
19134 // Check for x CC y ? y : x -- a min/max with reversed arms.
19135 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19136 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19140 // Converting this to a min would handle comparisons between positive
19141 // and negative zero incorrectly, and swapping the operands would
19142 // cause it to handle NaNs incorrectly.
19143 if (!DAG.getTarget().Options.UnsafeFPMath &&
19144 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19145 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19147 std::swap(LHS, RHS);
19149 Opcode = X86ISD::FMIN;
19152 // Converting this to a min would handle NaNs incorrectly.
19153 if (!DAG.getTarget().Options.UnsafeFPMath &&
19154 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19156 Opcode = X86ISD::FMIN;
19159 // Converting this to a min would handle both negative zeros and NaNs
19160 // incorrectly, but we can swap the operands to fix both.
19161 std::swap(LHS, RHS);
19165 Opcode = X86ISD::FMIN;
19169 // Converting this to a max would handle NaNs incorrectly.
19170 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19172 Opcode = X86ISD::FMAX;
19175 // Converting this to a max would handle comparisons between positive
19176 // and negative zero incorrectly, and swapping the operands would
19177 // cause it to handle NaNs incorrectly.
19178 if (!DAG.getTarget().Options.UnsafeFPMath &&
19179 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19180 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19182 std::swap(LHS, RHS);
19184 Opcode = X86ISD::FMAX;
19187 // Converting this to a max would handle both negative zeros and NaNs
19188 // incorrectly, but we can swap the operands to fix both.
19189 std::swap(LHS, RHS);
19193 Opcode = X86ISD::FMAX;
19199 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19202 EVT CondVT = Cond.getValueType();
19203 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19204 CondVT.getVectorElementType() == MVT::i1) {
19205 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19206 // lowering on AVX-512. In this case we convert it to
19207 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19208 // The same situation for all 128 and 256-bit vectors of i8 and i16
19209 EVT OpVT = LHS.getValueType();
19210 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19211 (OpVT.getVectorElementType() == MVT::i8 ||
19212 OpVT.getVectorElementType() == MVT::i16)) {
19213 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19214 DCI.AddToWorklist(Cond.getNode());
19215 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19218 // If this is a select between two integer constants, try to do some
19220 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19221 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19222 // Don't do this for crazy integer types.
19223 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19224 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19225 // so that TrueC (the true value) is larger than FalseC.
19226 bool NeedsCondInvert = false;
19228 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19229 // Efficiently invertible.
19230 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
19231 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
19232 isa<ConstantSDNode>(Cond.getOperand(1))))) {
19233 NeedsCondInvert = true;
19234 std::swap(TrueC, FalseC);
19237 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
19238 if (FalseC->getAPIntValue() == 0 &&
19239 TrueC->getAPIntValue().isPowerOf2()) {
19240 if (NeedsCondInvert) // Invert the condition if needed.
19241 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19242 DAG.getConstant(1, Cond.getValueType()));
19244 // Zero extend the condition if needed.
19245 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19247 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19248 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19249 DAG.getConstant(ShAmt, MVT::i8));
19252 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19253 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19254 if (NeedsCondInvert) // Invert the condition if needed.
19255 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19256 DAG.getConstant(1, Cond.getValueType()));
19258 // Zero extend the condition if needed.
19259 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19260 FalseC->getValueType(0), Cond);
19261 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19262 SDValue(FalseC, 0));
19265 // Optimize cases that will turn into an LEA instruction. This requires
19266 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19267 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19268 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19269 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19271 bool isFastMultiplier = false;
19273 switch ((unsigned char)Diff) {
19275 case 1: // result = add base, cond
19276 case 2: // result = lea base( , cond*2)
19277 case 3: // result = lea base(cond, cond*2)
19278 case 4: // result = lea base( , cond*4)
19279 case 5: // result = lea base(cond, cond*4)
19280 case 8: // result = lea base( , cond*8)
19281 case 9: // result = lea base(cond, cond*8)
19282 isFastMultiplier = true;
19287 if (isFastMultiplier) {
19288 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19289 if (NeedsCondInvert) // Invert the condition if needed.
19290 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19291 DAG.getConstant(1, Cond.getValueType()));
19293 // Zero extend the condition if needed.
19294 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19296 // Scale the condition by the difference.
19298 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19299 DAG.getConstant(Diff, Cond.getValueType()));
19301 // Add the base if non-zero.
19302 if (FalseC->getAPIntValue() != 0)
19303 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19304 SDValue(FalseC, 0));
19311 // Canonicalize max and min:
19312 // (x > y) ? x : y -> (x >= y) ? x : y
19313 // (x < y) ? x : y -> (x <= y) ? x : y
19314 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19315 // the need for an extra compare
19316 // against zero. e.g.
19317 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19319 // testl %edi, %edi
19321 // cmovgl %edi, %eax
19325 // cmovsl %eax, %edi
19326 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19327 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19328 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19329 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19334 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19335 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19336 Cond.getOperand(0), Cond.getOperand(1), NewCC);
19337 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19342 // Early exit check
19343 if (!TLI.isTypeLegal(VT))
19346 // Match VSELECTs into subs with unsigned saturation.
19347 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19348 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
19349 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
19350 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
19351 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19353 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
19354 // left side invert the predicate to simplify logic below.
19356 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
19358 CC = ISD::getSetCCInverse(CC, true);
19359 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
19363 if (Other.getNode() && Other->getNumOperands() == 2 &&
19364 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
19365 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
19366 SDValue CondRHS = Cond->getOperand(1);
19368 // Look for a general sub with unsigned saturation first.
19369 // x >= y ? x-y : 0 --> subus x, y
19370 // x > y ? x-y : 0 --> subus x, y
19371 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
19372 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
19373 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19375 // If the RHS is a constant we have to reverse the const canonicalization.
19376 // x > C-1 ? x+-C : 0 --> subus x, C
19377 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
19378 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
19379 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
19380 if (CondRHS.getConstantOperandVal(0) == -A-1)
19381 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
19382 DAG.getConstant(-A, VT));
19385 // Another special case: If C was a sign bit, the sub has been
19386 // canonicalized into a xor.
19387 // FIXME: Would it be better to use computeKnownBits to determine whether
19388 // it's safe to decanonicalize the xor?
19389 // x s< 0 ? x^C : 0 --> subus x, C
19390 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
19391 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
19392 isSplatVector(OpRHS.getNode())) {
19393 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
19395 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19400 // Try to match a min/max vector operation.
19401 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
19402 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
19403 unsigned Opc = ret.first;
19404 bool NeedSplit = ret.second;
19406 if (Opc && NeedSplit) {
19407 unsigned NumElems = VT.getVectorNumElements();
19408 // Extract the LHS vectors
19409 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
19410 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
19412 // Extract the RHS vectors
19413 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
19414 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
19416 // Create min/max for each subvector
19417 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
19418 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
19420 // Merge the result
19421 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
19423 return DAG.getNode(Opc, DL, VT, LHS, RHS);
19426 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
19427 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19428 // Check if SETCC has already been promoted
19429 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
19430 // Check that condition value type matches vselect operand type
19433 assert(Cond.getValueType().isVector() &&
19434 "vector select expects a vector selector!");
19436 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
19437 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
19439 if (!TValIsAllOnes && !FValIsAllZeros) {
19440 // Try invert the condition if true value is not all 1s and false value
19442 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
19443 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
19445 if (TValIsAllZeros || FValIsAllOnes) {
19446 SDValue CC = Cond.getOperand(2);
19447 ISD::CondCode NewCC =
19448 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
19449 Cond.getOperand(0).getValueType().isInteger());
19450 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
19451 std::swap(LHS, RHS);
19452 TValIsAllOnes = FValIsAllOnes;
19453 FValIsAllZeros = TValIsAllZeros;
19457 if (TValIsAllOnes || FValIsAllZeros) {
19460 if (TValIsAllOnes && FValIsAllZeros)
19462 else if (TValIsAllOnes)
19463 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
19464 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
19465 else if (FValIsAllZeros)
19466 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
19467 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
19469 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
19473 // Try to fold this VSELECT into a MOVSS/MOVSD
19474 if (N->getOpcode() == ISD::VSELECT &&
19475 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
19476 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
19477 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
19478 bool CanFold = false;
19479 unsigned NumElems = Cond.getNumOperands();
19483 if (isZero(Cond.getOperand(0))) {
19486 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
19487 // fold (vselect <0,-1> -> (movsd A, B)
19488 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19489 CanFold = isAllOnes(Cond.getOperand(i));
19490 } else if (isAllOnes(Cond.getOperand(0))) {
19494 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
19495 // fold (vselect <-1,0> -> (movsd B, A)
19496 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19497 CanFold = isZero(Cond.getOperand(i));
19501 if (VT == MVT::v4i32 || VT == MVT::v4f32)
19502 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
19503 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
19506 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
19507 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
19508 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
19509 // (v2i64 (bitcast B)))))
19511 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
19512 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
19513 // (v2f64 (bitcast B)))))
19515 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
19516 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
19517 // (v2i64 (bitcast A)))))
19519 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
19520 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
19521 // (v2f64 (bitcast A)))))
19523 CanFold = (isZero(Cond.getOperand(0)) &&
19524 isZero(Cond.getOperand(1)) &&
19525 isAllOnes(Cond.getOperand(2)) &&
19526 isAllOnes(Cond.getOperand(3)));
19528 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
19529 isAllOnes(Cond.getOperand(1)) &&
19530 isZero(Cond.getOperand(2)) &&
19531 isZero(Cond.getOperand(3))) {
19533 std::swap(LHS, RHS);
19537 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
19538 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
19539 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
19540 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
19542 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
19548 // If we know that this node is legal then we know that it is going to be
19549 // matched by one of the SSE/AVX BLEND instructions. These instructions only
19550 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
19551 // to simplify previous instructions.
19552 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
19553 !DCI.isBeforeLegalize() &&
19554 // We explicitly check against v8i16 and v16i16 because, although
19555 // they're marked as Custom, they might only be legal when Cond is a
19556 // build_vector of constants. This will be taken care in a later
19558 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
19559 VT != MVT::v8i16)) {
19560 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
19562 // Don't optimize vector selects that map to mask-registers.
19566 // Check all uses of that condition operand to check whether it will be
19567 // consumed by non-BLEND instructions, which may depend on all bits are set
19569 for (SDNode::use_iterator I = Cond->use_begin(),
19570 E = Cond->use_end(); I != E; ++I)
19571 if (I->getOpcode() != ISD::VSELECT)
19572 // TODO: Add other opcodes eventually lowered into BLEND.
19575 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
19576 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
19578 APInt KnownZero, KnownOne;
19579 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
19580 DCI.isBeforeLegalizeOps());
19581 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
19582 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
19583 DCI.CommitTargetLoweringOpt(TLO);
19586 // We should generate an X86ISD::BLENDI from a vselect if its argument
19587 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
19588 // constants. This specific pattern gets generated when we split a
19589 // selector for a 512 bit vector in a machine without AVX512 (but with
19590 // 256-bit vectors), during legalization:
19592 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
19594 // Iff we find this pattern and the build_vectors are built from
19595 // constants, we translate the vselect into a shuffle_vector that we
19596 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
19597 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
19598 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
19599 if (Shuffle.getNode())
19606 // Check whether a boolean test is testing a boolean value generated by
19607 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
19610 // Simplify the following patterns:
19611 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
19612 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
19613 // to (Op EFLAGS Cond)
19615 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
19616 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
19617 // to (Op EFLAGS !Cond)
19619 // where Op could be BRCOND or CMOV.
19621 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
19622 // Quit if not CMP and SUB with its value result used.
19623 if (Cmp.getOpcode() != X86ISD::CMP &&
19624 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
19627 // Quit if not used as a boolean value.
19628 if (CC != X86::COND_E && CC != X86::COND_NE)
19631 // Check CMP operands. One of them should be 0 or 1 and the other should be
19632 // an SetCC or extended from it.
19633 SDValue Op1 = Cmp.getOperand(0);
19634 SDValue Op2 = Cmp.getOperand(1);
19637 const ConstantSDNode* C = nullptr;
19638 bool needOppositeCond = (CC == X86::COND_E);
19639 bool checkAgainstTrue = false; // Is it a comparison against 1?
19641 if ((C = dyn_cast<ConstantSDNode>(Op1)))
19643 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
19645 else // Quit if all operands are not constants.
19648 if (C->getZExtValue() == 1) {
19649 needOppositeCond = !needOppositeCond;
19650 checkAgainstTrue = true;
19651 } else if (C->getZExtValue() != 0)
19652 // Quit if the constant is neither 0 or 1.
19655 bool truncatedToBoolWithAnd = false;
19656 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
19657 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
19658 SetCC.getOpcode() == ISD::TRUNCATE ||
19659 SetCC.getOpcode() == ISD::AND) {
19660 if (SetCC.getOpcode() == ISD::AND) {
19662 ConstantSDNode *CS;
19663 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
19664 CS->getZExtValue() == 1)
19666 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
19667 CS->getZExtValue() == 1)
19671 SetCC = SetCC.getOperand(OpIdx);
19672 truncatedToBoolWithAnd = true;
19674 SetCC = SetCC.getOperand(0);
19677 switch (SetCC.getOpcode()) {
19678 case X86ISD::SETCC_CARRY:
19679 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
19680 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
19681 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
19682 // truncated to i1 using 'and'.
19683 if (checkAgainstTrue && !truncatedToBoolWithAnd)
19685 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
19686 "Invalid use of SETCC_CARRY!");
19688 case X86ISD::SETCC:
19689 // Set the condition code or opposite one if necessary.
19690 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
19691 if (needOppositeCond)
19692 CC = X86::GetOppositeBranchCondition(CC);
19693 return SetCC.getOperand(1);
19694 case X86ISD::CMOV: {
19695 // Check whether false/true value has canonical one, i.e. 0 or 1.
19696 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
19697 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
19698 // Quit if true value is not a constant.
19701 // Quit if false value is not a constant.
19703 SDValue Op = SetCC.getOperand(0);
19704 // Skip 'zext' or 'trunc' node.
19705 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
19706 Op.getOpcode() == ISD::TRUNCATE)
19707 Op = Op.getOperand(0);
19708 // A special case for rdrand/rdseed, where 0 is set if false cond is
19710 if ((Op.getOpcode() != X86ISD::RDRAND &&
19711 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
19714 // Quit if false value is not the constant 0 or 1.
19715 bool FValIsFalse = true;
19716 if (FVal && FVal->getZExtValue() != 0) {
19717 if (FVal->getZExtValue() != 1)
19719 // If FVal is 1, opposite cond is needed.
19720 needOppositeCond = !needOppositeCond;
19721 FValIsFalse = false;
19723 // Quit if TVal is not the constant opposite of FVal.
19724 if (FValIsFalse && TVal->getZExtValue() != 1)
19726 if (!FValIsFalse && TVal->getZExtValue() != 0)
19728 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
19729 if (needOppositeCond)
19730 CC = X86::GetOppositeBranchCondition(CC);
19731 return SetCC.getOperand(3);
19738 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
19739 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
19740 TargetLowering::DAGCombinerInfo &DCI,
19741 const X86Subtarget *Subtarget) {
19744 // If the flag operand isn't dead, don't touch this CMOV.
19745 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
19748 SDValue FalseOp = N->getOperand(0);
19749 SDValue TrueOp = N->getOperand(1);
19750 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
19751 SDValue Cond = N->getOperand(3);
19753 if (CC == X86::COND_E || CC == X86::COND_NE) {
19754 switch (Cond.getOpcode()) {
19758 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
19759 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
19760 return (CC == X86::COND_E) ? FalseOp : TrueOp;
19766 Flags = checkBoolTestSetCCCombine(Cond, CC);
19767 if (Flags.getNode() &&
19768 // Extra check as FCMOV only supports a subset of X86 cond.
19769 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
19770 SDValue Ops[] = { FalseOp, TrueOp,
19771 DAG.getConstant(CC, MVT::i8), Flags };
19772 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19775 // If this is a select between two integer constants, try to do some
19776 // optimizations. Note that the operands are ordered the opposite of SELECT
19778 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19779 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19780 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19781 // larger than FalseC (the false value).
19782 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19783 CC = X86::GetOppositeBranchCondition(CC);
19784 std::swap(TrueC, FalseC);
19785 std::swap(TrueOp, FalseOp);
19788 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
19789 // This is efficient for any integer data type (including i8/i16) and
19791 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
19792 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19793 DAG.getConstant(CC, MVT::i8), Cond);
19795 // Zero extend the condition if needed.
19796 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
19798 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19799 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
19800 DAG.getConstant(ShAmt, MVT::i8));
19801 if (N->getNumValues() == 2) // Dead flag value?
19802 return DCI.CombineTo(N, Cond, SDValue());
19806 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
19807 // for any integer data type, including i8/i16.
19808 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19809 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19810 DAG.getConstant(CC, MVT::i8), Cond);
19812 // Zero extend the condition if needed.
19813 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19814 FalseC->getValueType(0), Cond);
19815 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19816 SDValue(FalseC, 0));
19818 if (N->getNumValues() == 2) // Dead flag value?
19819 return DCI.CombineTo(N, Cond, SDValue());
19823 // Optimize cases that will turn into an LEA instruction. This requires
19824 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19825 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19826 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19827 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19829 bool isFastMultiplier = false;
19831 switch ((unsigned char)Diff) {
19833 case 1: // result = add base, cond
19834 case 2: // result = lea base( , cond*2)
19835 case 3: // result = lea base(cond, cond*2)
19836 case 4: // result = lea base( , cond*4)
19837 case 5: // result = lea base(cond, cond*4)
19838 case 8: // result = lea base( , cond*8)
19839 case 9: // result = lea base(cond, cond*8)
19840 isFastMultiplier = true;
19845 if (isFastMultiplier) {
19846 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19847 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19848 DAG.getConstant(CC, MVT::i8), Cond);
19849 // Zero extend the condition if needed.
19850 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19852 // Scale the condition by the difference.
19854 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19855 DAG.getConstant(Diff, Cond.getValueType()));
19857 // Add the base if non-zero.
19858 if (FalseC->getAPIntValue() != 0)
19859 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19860 SDValue(FalseC, 0));
19861 if (N->getNumValues() == 2) // Dead flag value?
19862 return DCI.CombineTo(N, Cond, SDValue());
19869 // Handle these cases:
19870 // (select (x != c), e, c) -> select (x != c), e, x),
19871 // (select (x == c), c, e) -> select (x == c), x, e)
19872 // where the c is an integer constant, and the "select" is the combination
19873 // of CMOV and CMP.
19875 // The rationale for this change is that the conditional-move from a constant
19876 // needs two instructions, however, conditional-move from a register needs
19877 // only one instruction.
19879 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
19880 // some instruction-combining opportunities. This opt needs to be
19881 // postponed as late as possible.
19883 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
19884 // the DCI.xxxx conditions are provided to postpone the optimization as
19885 // late as possible.
19887 ConstantSDNode *CmpAgainst = nullptr;
19888 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
19889 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
19890 !isa<ConstantSDNode>(Cond.getOperand(0))) {
19892 if (CC == X86::COND_NE &&
19893 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
19894 CC = X86::GetOppositeBranchCondition(CC);
19895 std::swap(TrueOp, FalseOp);
19898 if (CC == X86::COND_E &&
19899 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
19900 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
19901 DAG.getConstant(CC, MVT::i8), Cond };
19902 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
19910 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
19911 const X86Subtarget *Subtarget) {
19912 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
19914 default: return SDValue();
19915 // SSE/AVX/AVX2 blend intrinsics.
19916 case Intrinsic::x86_avx2_pblendvb:
19917 case Intrinsic::x86_avx2_pblendw:
19918 case Intrinsic::x86_avx2_pblendd_128:
19919 case Intrinsic::x86_avx2_pblendd_256:
19920 // Don't try to simplify this intrinsic if we don't have AVX2.
19921 if (!Subtarget->hasAVX2())
19924 case Intrinsic::x86_avx_blend_pd_256:
19925 case Intrinsic::x86_avx_blend_ps_256:
19926 case Intrinsic::x86_avx_blendv_pd_256:
19927 case Intrinsic::x86_avx_blendv_ps_256:
19928 // Don't try to simplify this intrinsic if we don't have AVX.
19929 if (!Subtarget->hasAVX())
19932 case Intrinsic::x86_sse41_pblendw:
19933 case Intrinsic::x86_sse41_blendpd:
19934 case Intrinsic::x86_sse41_blendps:
19935 case Intrinsic::x86_sse41_blendvps:
19936 case Intrinsic::x86_sse41_blendvpd:
19937 case Intrinsic::x86_sse41_pblendvb: {
19938 SDValue Op0 = N->getOperand(1);
19939 SDValue Op1 = N->getOperand(2);
19940 SDValue Mask = N->getOperand(3);
19942 // Don't try to simplify this intrinsic if we don't have SSE4.1.
19943 if (!Subtarget->hasSSE41())
19946 // fold (blend A, A, Mask) -> A
19949 // fold (blend A, B, allZeros) -> A
19950 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
19952 // fold (blend A, B, allOnes) -> B
19953 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
19956 // Simplify the case where the mask is a constant i32 value.
19957 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
19958 if (C->isNullValue())
19960 if (C->isAllOnesValue())
19967 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
19968 case Intrinsic::x86_sse2_psrai_w:
19969 case Intrinsic::x86_sse2_psrai_d:
19970 case Intrinsic::x86_avx2_psrai_w:
19971 case Intrinsic::x86_avx2_psrai_d:
19972 case Intrinsic::x86_sse2_psra_w:
19973 case Intrinsic::x86_sse2_psra_d:
19974 case Intrinsic::x86_avx2_psra_w:
19975 case Intrinsic::x86_avx2_psra_d: {
19976 SDValue Op0 = N->getOperand(1);
19977 SDValue Op1 = N->getOperand(2);
19978 EVT VT = Op0.getValueType();
19979 assert(VT.isVector() && "Expected a vector type!");
19981 if (isa<BuildVectorSDNode>(Op1))
19982 Op1 = Op1.getOperand(0);
19984 if (!isa<ConstantSDNode>(Op1))
19987 EVT SVT = VT.getVectorElementType();
19988 unsigned SVTBits = SVT.getSizeInBits();
19990 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
19991 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
19992 uint64_t ShAmt = C.getZExtValue();
19994 // Don't try to convert this shift into a ISD::SRA if the shift
19995 // count is bigger than or equal to the element size.
19996 if (ShAmt >= SVTBits)
19999 // Trivial case: if the shift count is zero, then fold this
20000 // into the first operand.
20004 // Replace this packed shift intrinsic with a target independent
20006 SDValue Splat = DAG.getConstant(C, VT);
20007 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20012 /// PerformMulCombine - Optimize a single multiply with constant into two
20013 /// in order to implement it with two cheaper instructions, e.g.
20014 /// LEA + SHL, LEA + LEA.
20015 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20016 TargetLowering::DAGCombinerInfo &DCI) {
20017 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20020 EVT VT = N->getValueType(0);
20021 if (VT != MVT::i64)
20024 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20027 uint64_t MulAmt = C->getZExtValue();
20028 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20031 uint64_t MulAmt1 = 0;
20032 uint64_t MulAmt2 = 0;
20033 if ((MulAmt % 9) == 0) {
20035 MulAmt2 = MulAmt / 9;
20036 } else if ((MulAmt % 5) == 0) {
20038 MulAmt2 = MulAmt / 5;
20039 } else if ((MulAmt % 3) == 0) {
20041 MulAmt2 = MulAmt / 3;
20044 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20047 if (isPowerOf2_64(MulAmt2) &&
20048 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20049 // If second multiplifer is pow2, issue it first. We want the multiply by
20050 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20052 std::swap(MulAmt1, MulAmt2);
20055 if (isPowerOf2_64(MulAmt1))
20056 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20057 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20059 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20060 DAG.getConstant(MulAmt1, VT));
20062 if (isPowerOf2_64(MulAmt2))
20063 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20064 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20066 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20067 DAG.getConstant(MulAmt2, VT));
20069 // Do not add new nodes to DAG combiner worklist.
20070 DCI.CombineTo(N, NewMul, false);
20075 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20076 SDValue N0 = N->getOperand(0);
20077 SDValue N1 = N->getOperand(1);
20078 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20079 EVT VT = N0.getValueType();
20081 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20082 // since the result of setcc_c is all zero's or all ones.
20083 if (VT.isInteger() && !VT.isVector() &&
20084 N1C && N0.getOpcode() == ISD::AND &&
20085 N0.getOperand(1).getOpcode() == ISD::Constant) {
20086 SDValue N00 = N0.getOperand(0);
20087 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20088 ((N00.getOpcode() == ISD::ANY_EXTEND ||
20089 N00.getOpcode() == ISD::ZERO_EXTEND) &&
20090 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20091 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20092 APInt ShAmt = N1C->getAPIntValue();
20093 Mask = Mask.shl(ShAmt);
20095 return DAG.getNode(ISD::AND, SDLoc(N), VT,
20096 N00, DAG.getConstant(Mask, VT));
20100 // Hardware support for vector shifts is sparse which makes us scalarize the
20101 // vector operations in many cases. Also, on sandybridge ADD is faster than
20103 // (shl V, 1) -> add V,V
20104 if (isSplatVector(N1.getNode())) {
20105 assert(N0.getValueType().isVector() && "Invalid vector shift type");
20106 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
20107 // We shift all of the values by one. In many cases we do not have
20108 // hardware support for this operation. This is better expressed as an ADD
20110 if (N1C && (1 == N1C->getZExtValue())) {
20111 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20118 /// \brief Returns a vector of 0s if the node in input is a vector logical
20119 /// shift by a constant amount which is known to be bigger than or equal
20120 /// to the vector element size in bits.
20121 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20122 const X86Subtarget *Subtarget) {
20123 EVT VT = N->getValueType(0);
20125 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20126 (!Subtarget->hasInt256() ||
20127 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20130 SDValue Amt = N->getOperand(1);
20132 if (isSplatVector(Amt.getNode())) {
20133 SDValue SclrAmt = Amt->getOperand(0);
20134 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
20135 APInt ShiftAmt = C->getAPIntValue();
20136 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20138 // SSE2/AVX2 logical shifts always return a vector of 0s
20139 // if the shift amount is bigger than or equal to
20140 // the element size. The constant shift amount will be
20141 // encoded as a 8-bit immediate.
20142 if (ShiftAmt.trunc(8).uge(MaxAmount))
20143 return getZeroVector(VT, Subtarget, DAG, DL);
20150 /// PerformShiftCombine - Combine shifts.
20151 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20152 TargetLowering::DAGCombinerInfo &DCI,
20153 const X86Subtarget *Subtarget) {
20154 if (N->getOpcode() == ISD::SHL) {
20155 SDValue V = PerformSHLCombine(N, DAG);
20156 if (V.getNode()) return V;
20159 if (N->getOpcode() != ISD::SRA) {
20160 // Try to fold this logical shift into a zero vector.
20161 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20162 if (V.getNode()) return V;
20168 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
20169 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20170 // and friends. Likewise for OR -> CMPNEQSS.
20171 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20172 TargetLowering::DAGCombinerInfo &DCI,
20173 const X86Subtarget *Subtarget) {
20176 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20177 // we're requiring SSE2 for both.
20178 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20179 SDValue N0 = N->getOperand(0);
20180 SDValue N1 = N->getOperand(1);
20181 SDValue CMP0 = N0->getOperand(1);
20182 SDValue CMP1 = N1->getOperand(1);
20185 // The SETCCs should both refer to the same CMP.
20186 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20189 SDValue CMP00 = CMP0->getOperand(0);
20190 SDValue CMP01 = CMP0->getOperand(1);
20191 EVT VT = CMP00.getValueType();
20193 if (VT == MVT::f32 || VT == MVT::f64) {
20194 bool ExpectingFlags = false;
20195 // Check for any users that want flags:
20196 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20197 !ExpectingFlags && UI != UE; ++UI)
20198 switch (UI->getOpcode()) {
20203 ExpectingFlags = true;
20205 case ISD::CopyToReg:
20206 case ISD::SIGN_EXTEND:
20207 case ISD::ZERO_EXTEND:
20208 case ISD::ANY_EXTEND:
20212 if (!ExpectingFlags) {
20213 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20214 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20216 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20217 X86::CondCode tmp = cc0;
20222 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
20223 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20224 // FIXME: need symbolic constants for these magic numbers.
20225 // See X86ATTInstPrinter.cpp:printSSECC().
20226 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20227 if (Subtarget->hasAVX512()) {
20228 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20229 CMP01, DAG.getConstant(x86cc, MVT::i8));
20230 if (N->getValueType(0) != MVT::i1)
20231 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20235 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20236 CMP00.getValueType(), CMP00, CMP01,
20237 DAG.getConstant(x86cc, MVT::i8));
20239 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20240 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20242 if (is64BitFP && !Subtarget->is64Bit()) {
20243 // On a 32-bit target, we cannot bitcast the 64-bit float to a
20244 // 64-bit integer, since that's not a legal type. Since
20245 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20246 // bits, but can do this little dance to extract the lowest 32 bits
20247 // and work with those going forward.
20248 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20250 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20252 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20253 Vector32, DAG.getIntPtrConstant(0));
20257 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20258 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20259 DAG.getConstant(1, IntVT));
20260 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20261 return OneBitOfTruth;
20269 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20270 /// so it can be folded inside ANDNP.
20271 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20272 EVT VT = N->getValueType(0);
20274 // Match direct AllOnes for 128 and 256-bit vectors
20275 if (ISD::isBuildVectorAllOnes(N))
20278 // Look through a bit convert.
20279 if (N->getOpcode() == ISD::BITCAST)
20280 N = N->getOperand(0).getNode();
20282 // Sometimes the operand may come from a insert_subvector building a 256-bit
20284 if (VT.is256BitVector() &&
20285 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20286 SDValue V1 = N->getOperand(0);
20287 SDValue V2 = N->getOperand(1);
20289 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20290 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20291 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20292 ISD::isBuildVectorAllOnes(V2.getNode()))
20299 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20300 // register. In most cases we actually compare or select YMM-sized registers
20301 // and mixing the two types creates horrible code. This method optimizes
20302 // some of the transition sequences.
20303 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20304 TargetLowering::DAGCombinerInfo &DCI,
20305 const X86Subtarget *Subtarget) {
20306 EVT VT = N->getValueType(0);
20307 if (!VT.is256BitVector())
20310 assert((N->getOpcode() == ISD::ANY_EXTEND ||
20311 N->getOpcode() == ISD::ZERO_EXTEND ||
20312 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20314 SDValue Narrow = N->getOperand(0);
20315 EVT NarrowVT = Narrow->getValueType(0);
20316 if (!NarrowVT.is128BitVector())
20319 if (Narrow->getOpcode() != ISD::XOR &&
20320 Narrow->getOpcode() != ISD::AND &&
20321 Narrow->getOpcode() != ISD::OR)
20324 SDValue N0 = Narrow->getOperand(0);
20325 SDValue N1 = Narrow->getOperand(1);
20328 // The Left side has to be a trunc.
20329 if (N0.getOpcode() != ISD::TRUNCATE)
20332 // The type of the truncated inputs.
20333 EVT WideVT = N0->getOperand(0)->getValueType(0);
20337 // The right side has to be a 'trunc' or a constant vector.
20338 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20339 bool RHSConst = (isSplatVector(N1.getNode()) &&
20340 isa<ConstantSDNode>(N1->getOperand(0)));
20341 if (!RHSTrunc && !RHSConst)
20344 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20346 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
20349 // Set N0 and N1 to hold the inputs to the new wide operation.
20350 N0 = N0->getOperand(0);
20352 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
20353 N1->getOperand(0));
20354 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
20355 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
20356 } else if (RHSTrunc) {
20357 N1 = N1->getOperand(0);
20360 // Generate the wide operation.
20361 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
20362 unsigned Opcode = N->getOpcode();
20364 case ISD::ANY_EXTEND:
20366 case ISD::ZERO_EXTEND: {
20367 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
20368 APInt Mask = APInt::getAllOnesValue(InBits);
20369 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
20370 return DAG.getNode(ISD::AND, DL, VT,
20371 Op, DAG.getConstant(Mask, VT));
20373 case ISD::SIGN_EXTEND:
20374 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
20375 Op, DAG.getValueType(NarrowVT));
20377 llvm_unreachable("Unexpected opcode");
20381 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
20382 TargetLowering::DAGCombinerInfo &DCI,
20383 const X86Subtarget *Subtarget) {
20384 EVT VT = N->getValueType(0);
20385 if (DCI.isBeforeLegalizeOps())
20388 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20392 // Create BEXTR instructions
20393 // BEXTR is ((X >> imm) & (2**size-1))
20394 if (VT == MVT::i32 || VT == MVT::i64) {
20395 SDValue N0 = N->getOperand(0);
20396 SDValue N1 = N->getOperand(1);
20399 // Check for BEXTR.
20400 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
20401 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
20402 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
20403 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20404 if (MaskNode && ShiftNode) {
20405 uint64_t Mask = MaskNode->getZExtValue();
20406 uint64_t Shift = ShiftNode->getZExtValue();
20407 if (isMask_64(Mask)) {
20408 uint64_t MaskSize = CountPopulation_64(Mask);
20409 if (Shift + MaskSize <= VT.getSizeInBits())
20410 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
20411 DAG.getConstant(Shift | (MaskSize << 8), VT));
20419 // Want to form ANDNP nodes:
20420 // 1) In the hopes of then easily combining them with OR and AND nodes
20421 // to form PBLEND/PSIGN.
20422 // 2) To match ANDN packed intrinsics
20423 if (VT != MVT::v2i64 && VT != MVT::v4i64)
20426 SDValue N0 = N->getOperand(0);
20427 SDValue N1 = N->getOperand(1);
20430 // Check LHS for vnot
20431 if (N0.getOpcode() == ISD::XOR &&
20432 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
20433 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
20434 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
20436 // Check RHS for vnot
20437 if (N1.getOpcode() == ISD::XOR &&
20438 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
20439 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
20440 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
20445 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
20446 TargetLowering::DAGCombinerInfo &DCI,
20447 const X86Subtarget *Subtarget) {
20448 if (DCI.isBeforeLegalizeOps())
20451 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20455 SDValue N0 = N->getOperand(0);
20456 SDValue N1 = N->getOperand(1);
20457 EVT VT = N->getValueType(0);
20459 // look for psign/blend
20460 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
20461 if (!Subtarget->hasSSSE3() ||
20462 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
20465 // Canonicalize pandn to RHS
20466 if (N0.getOpcode() == X86ISD::ANDNP)
20468 // or (and (m, y), (pandn m, x))
20469 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
20470 SDValue Mask = N1.getOperand(0);
20471 SDValue X = N1.getOperand(1);
20473 if (N0.getOperand(0) == Mask)
20474 Y = N0.getOperand(1);
20475 if (N0.getOperand(1) == Mask)
20476 Y = N0.getOperand(0);
20478 // Check to see if the mask appeared in both the AND and ANDNP and
20482 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
20483 // Look through mask bitcast.
20484 if (Mask.getOpcode() == ISD::BITCAST)
20485 Mask = Mask.getOperand(0);
20486 if (X.getOpcode() == ISD::BITCAST)
20487 X = X.getOperand(0);
20488 if (Y.getOpcode() == ISD::BITCAST)
20489 Y = Y.getOperand(0);
20491 EVT MaskVT = Mask.getValueType();
20493 // Validate that the Mask operand is a vector sra node.
20494 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
20495 // there is no psrai.b
20496 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
20497 unsigned SraAmt = ~0;
20498 if (Mask.getOpcode() == ISD::SRA) {
20499 SDValue Amt = Mask.getOperand(1);
20500 if (isSplatVector(Amt.getNode())) {
20501 SDValue SclrAmt = Amt->getOperand(0);
20502 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
20503 SraAmt = C->getZExtValue();
20505 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
20506 SDValue SraC = Mask.getOperand(1);
20507 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
20509 if ((SraAmt + 1) != EltBits)
20514 // Now we know we at least have a plendvb with the mask val. See if
20515 // we can form a psignb/w/d.
20516 // psign = x.type == y.type == mask.type && y = sub(0, x);
20517 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
20518 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
20519 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
20520 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
20521 "Unsupported VT for PSIGN");
20522 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
20523 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20525 // PBLENDVB only available on SSE 4.1
20526 if (!Subtarget->hasSSE41())
20529 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
20531 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
20532 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
20533 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
20534 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
20535 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20539 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
20542 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
20543 MachineFunction &MF = DAG.getMachineFunction();
20544 bool OptForSize = MF.getFunction()->getAttributes().
20545 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
20547 // SHLD/SHRD instructions have lower register pressure, but on some
20548 // platforms they have higher latency than the equivalent
20549 // series of shifts/or that would otherwise be generated.
20550 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
20551 // have higher latencies and we are not optimizing for size.
20552 if (!OptForSize && Subtarget->isSHLDSlow())
20555 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
20557 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
20559 if (!N0.hasOneUse() || !N1.hasOneUse())
20562 SDValue ShAmt0 = N0.getOperand(1);
20563 if (ShAmt0.getValueType() != MVT::i8)
20565 SDValue ShAmt1 = N1.getOperand(1);
20566 if (ShAmt1.getValueType() != MVT::i8)
20568 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
20569 ShAmt0 = ShAmt0.getOperand(0);
20570 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
20571 ShAmt1 = ShAmt1.getOperand(0);
20574 unsigned Opc = X86ISD::SHLD;
20575 SDValue Op0 = N0.getOperand(0);
20576 SDValue Op1 = N1.getOperand(0);
20577 if (ShAmt0.getOpcode() == ISD::SUB) {
20578 Opc = X86ISD::SHRD;
20579 std::swap(Op0, Op1);
20580 std::swap(ShAmt0, ShAmt1);
20583 unsigned Bits = VT.getSizeInBits();
20584 if (ShAmt1.getOpcode() == ISD::SUB) {
20585 SDValue Sum = ShAmt1.getOperand(0);
20586 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
20587 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
20588 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
20589 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
20590 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
20591 return DAG.getNode(Opc, DL, VT,
20593 DAG.getNode(ISD::TRUNCATE, DL,
20596 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
20597 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
20599 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
20600 return DAG.getNode(Opc, DL, VT,
20601 N0.getOperand(0), N1.getOperand(0),
20602 DAG.getNode(ISD::TRUNCATE, DL,
20609 // Generate NEG and CMOV for integer abs.
20610 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
20611 EVT VT = N->getValueType(0);
20613 // Since X86 does not have CMOV for 8-bit integer, we don't convert
20614 // 8-bit integer abs to NEG and CMOV.
20615 if (VT.isInteger() && VT.getSizeInBits() == 8)
20618 SDValue N0 = N->getOperand(0);
20619 SDValue N1 = N->getOperand(1);
20622 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
20623 // and change it to SUB and CMOV.
20624 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
20625 N0.getOpcode() == ISD::ADD &&
20626 N0.getOperand(1) == N1 &&
20627 N1.getOpcode() == ISD::SRA &&
20628 N1.getOperand(0) == N0.getOperand(0))
20629 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
20630 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
20631 // Generate SUB & CMOV.
20632 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
20633 DAG.getConstant(0, VT), N0.getOperand(0));
20635 SDValue Ops[] = { N0.getOperand(0), Neg,
20636 DAG.getConstant(X86::COND_GE, MVT::i8),
20637 SDValue(Neg.getNode(), 1) };
20638 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
20643 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
20644 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
20645 TargetLowering::DAGCombinerInfo &DCI,
20646 const X86Subtarget *Subtarget) {
20647 if (DCI.isBeforeLegalizeOps())
20650 if (Subtarget->hasCMov()) {
20651 SDValue RV = performIntegerAbsCombine(N, DAG);
20659 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
20660 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
20661 TargetLowering::DAGCombinerInfo &DCI,
20662 const X86Subtarget *Subtarget) {
20663 LoadSDNode *Ld = cast<LoadSDNode>(N);
20664 EVT RegVT = Ld->getValueType(0);
20665 EVT MemVT = Ld->getMemoryVT();
20667 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20668 unsigned RegSz = RegVT.getSizeInBits();
20670 // On Sandybridge unaligned 256bit loads are inefficient.
20671 ISD::LoadExtType Ext = Ld->getExtensionType();
20672 unsigned Alignment = Ld->getAlignment();
20673 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
20674 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
20675 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
20676 unsigned NumElems = RegVT.getVectorNumElements();
20680 SDValue Ptr = Ld->getBasePtr();
20681 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
20683 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20685 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20686 Ld->getPointerInfo(), Ld->isVolatile(),
20687 Ld->isNonTemporal(), Ld->isInvariant(),
20689 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20690 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20691 Ld->getPointerInfo(), Ld->isVolatile(),
20692 Ld->isNonTemporal(), Ld->isInvariant(),
20693 std::min(16U, Alignment));
20694 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20696 Load2.getValue(1));
20698 SDValue NewVec = DAG.getUNDEF(RegVT);
20699 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
20700 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
20701 return DCI.CombineTo(N, NewVec, TF, true);
20704 // If this is a vector EXT Load then attempt to optimize it using a
20705 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
20706 // expansion is still better than scalar code.
20707 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
20708 // emit a shuffle and a arithmetic shift.
20709 // TODO: It is possible to support ZExt by zeroing the undef values
20710 // during the shuffle phase or after the shuffle.
20711 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
20712 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
20713 assert(MemVT != RegVT && "Cannot extend to the same type");
20714 assert(MemVT.isVector() && "Must load a vector from memory");
20716 unsigned NumElems = RegVT.getVectorNumElements();
20717 unsigned MemSz = MemVT.getSizeInBits();
20718 assert(RegSz > MemSz && "Register size must be greater than the mem size");
20720 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
20723 // All sizes must be a power of two.
20724 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
20727 // Attempt to load the original value using scalar loads.
20728 // Find the largest scalar type that divides the total loaded size.
20729 MVT SclrLoadTy = MVT::i8;
20730 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20731 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20732 MVT Tp = (MVT::SimpleValueType)tp;
20733 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20738 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20739 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20741 SclrLoadTy = MVT::f64;
20743 // Calculate the number of scalar loads that we need to perform
20744 // in order to load our vector from memory.
20745 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20746 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
20749 unsigned loadRegZize = RegSz;
20750 if (Ext == ISD::SEXTLOAD && RegSz == 256)
20753 // Represent our vector as a sequence of elements which are the
20754 // largest scalar that we can load.
20755 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
20756 loadRegZize/SclrLoadTy.getSizeInBits());
20758 // Represent the data using the same element type that is stored in
20759 // memory. In practice, we ''widen'' MemVT.
20761 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20762 loadRegZize/MemVT.getScalarType().getSizeInBits());
20764 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20765 "Invalid vector type");
20767 // We can't shuffle using an illegal type.
20768 if (!TLI.isTypeLegal(WideVecVT))
20771 SmallVector<SDValue, 8> Chains;
20772 SDValue Ptr = Ld->getBasePtr();
20773 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20774 TLI.getPointerTy());
20775 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20777 for (unsigned i = 0; i < NumLoads; ++i) {
20778 // Perform a single load.
20779 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20780 Ptr, Ld->getPointerInfo(),
20781 Ld->isVolatile(), Ld->isNonTemporal(),
20782 Ld->isInvariant(), Ld->getAlignment());
20783 Chains.push_back(ScalarLoad.getValue(1));
20784 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20785 // another round of DAGCombining.
20787 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20789 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20790 ScalarLoad, DAG.getIntPtrConstant(i));
20792 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20795 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20797 // Bitcast the loaded value to a vector of the original element type, in
20798 // the size of the target vector type.
20799 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
20800 unsigned SizeRatio = RegSz/MemSz;
20802 if (Ext == ISD::SEXTLOAD) {
20803 // If we have SSE4.1 we can directly emit a VSEXT node.
20804 if (Subtarget->hasSSE41()) {
20805 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
20806 return DCI.CombineTo(N, Sext, TF, true);
20809 // Otherwise we'll shuffle the small elements in the high bits of the
20810 // larger type and perform an arithmetic shift. If the shift is not legal
20811 // it's better to scalarize.
20812 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
20815 // Redistribute the loaded elements into the different locations.
20816 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20817 for (unsigned i = 0; i != NumElems; ++i)
20818 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
20820 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20821 DAG.getUNDEF(WideVecVT),
20824 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20826 // Build the arithmetic shift.
20827 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
20828 MemVT.getVectorElementType().getSizeInBits();
20829 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
20830 DAG.getConstant(Amt, RegVT));
20832 return DCI.CombineTo(N, Shuff, TF, true);
20835 // Redistribute the loaded elements into the different locations.
20836 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20837 for (unsigned i = 0; i != NumElems; ++i)
20838 ShuffleVec[i*SizeRatio] = i;
20840 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20841 DAG.getUNDEF(WideVecVT),
20844 // Bitcast to the requested type.
20845 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20846 // Replace the original load with the new sequence
20847 // and return the new chain.
20848 return DCI.CombineTo(N, Shuff, TF, true);
20854 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
20855 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
20856 const X86Subtarget *Subtarget) {
20857 StoreSDNode *St = cast<StoreSDNode>(N);
20858 EVT VT = St->getValue().getValueType();
20859 EVT StVT = St->getMemoryVT();
20861 SDValue StoredVal = St->getOperand(1);
20862 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20864 // If we are saving a concatenation of two XMM registers, perform two stores.
20865 // On Sandy Bridge, 256-bit memory operations are executed by two
20866 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
20867 // memory operation.
20868 unsigned Alignment = St->getAlignment();
20869 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
20870 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
20871 StVT == VT && !IsAligned) {
20872 unsigned NumElems = VT.getVectorNumElements();
20876 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
20877 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
20879 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
20880 SDValue Ptr0 = St->getBasePtr();
20881 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
20883 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
20884 St->getPointerInfo(), St->isVolatile(),
20885 St->isNonTemporal(), Alignment);
20886 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
20887 St->getPointerInfo(), St->isVolatile(),
20888 St->isNonTemporal(),
20889 std::min(16U, Alignment));
20890 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
20893 // Optimize trunc store (of multiple scalars) to shuffle and store.
20894 // First, pack all of the elements in one place. Next, store to memory
20895 // in fewer chunks.
20896 if (St->isTruncatingStore() && VT.isVector()) {
20897 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20898 unsigned NumElems = VT.getVectorNumElements();
20899 assert(StVT != VT && "Cannot truncate to the same type");
20900 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
20901 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
20903 // From, To sizes and ElemCount must be pow of two
20904 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
20905 // We are going to use the original vector elt for storing.
20906 // Accumulated smaller vector elements must be a multiple of the store size.
20907 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
20909 unsigned SizeRatio = FromSz / ToSz;
20911 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
20913 // Create a type on which we perform the shuffle
20914 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
20915 StVT.getScalarType(), NumElems*SizeRatio);
20917 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
20919 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
20920 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20921 for (unsigned i = 0; i != NumElems; ++i)
20922 ShuffleVec[i] = i * SizeRatio;
20924 // Can't shuffle using an illegal type.
20925 if (!TLI.isTypeLegal(WideVecVT))
20928 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
20929 DAG.getUNDEF(WideVecVT),
20931 // At this point all of the data is stored at the bottom of the
20932 // register. We now need to save it to mem.
20934 // Find the largest store unit
20935 MVT StoreType = MVT::i8;
20936 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20937 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20938 MVT Tp = (MVT::SimpleValueType)tp;
20939 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
20943 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20944 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
20945 (64 <= NumElems * ToSz))
20946 StoreType = MVT::f64;
20948 // Bitcast the original vector into a vector of store-size units
20949 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
20950 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
20951 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
20952 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
20953 SmallVector<SDValue, 8> Chains;
20954 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
20955 TLI.getPointerTy());
20956 SDValue Ptr = St->getBasePtr();
20958 // Perform one or more big stores into memory.
20959 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
20960 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
20961 StoreType, ShuffWide,
20962 DAG.getIntPtrConstant(i));
20963 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
20964 St->getPointerInfo(), St->isVolatile(),
20965 St->isNonTemporal(), St->getAlignment());
20966 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20967 Chains.push_back(Ch);
20970 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20973 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
20974 // the FP state in cases where an emms may be missing.
20975 // A preferable solution to the general problem is to figure out the right
20976 // places to insert EMMS. This qualifies as a quick hack.
20978 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
20979 if (VT.getSizeInBits() != 64)
20982 const Function *F = DAG.getMachineFunction().getFunction();
20983 bool NoImplicitFloatOps = F->getAttributes().
20984 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
20985 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
20986 && Subtarget->hasSSE2();
20987 if ((VT.isVector() ||
20988 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
20989 isa<LoadSDNode>(St->getValue()) &&
20990 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
20991 St->getChain().hasOneUse() && !St->isVolatile()) {
20992 SDNode* LdVal = St->getValue().getNode();
20993 LoadSDNode *Ld = nullptr;
20994 int TokenFactorIndex = -1;
20995 SmallVector<SDValue, 8> Ops;
20996 SDNode* ChainVal = St->getChain().getNode();
20997 // Must be a store of a load. We currently handle two cases: the load
20998 // is a direct child, and it's under an intervening TokenFactor. It is
20999 // possible to dig deeper under nested TokenFactors.
21000 if (ChainVal == LdVal)
21001 Ld = cast<LoadSDNode>(St->getChain());
21002 else if (St->getValue().hasOneUse() &&
21003 ChainVal->getOpcode() == ISD::TokenFactor) {
21004 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21005 if (ChainVal->getOperand(i).getNode() == LdVal) {
21006 TokenFactorIndex = i;
21007 Ld = cast<LoadSDNode>(St->getValue());
21009 Ops.push_back(ChainVal->getOperand(i));
21013 if (!Ld || !ISD::isNormalLoad(Ld))
21016 // If this is not the MMX case, i.e. we are just turning i64 load/store
21017 // into f64 load/store, avoid the transformation if there are multiple
21018 // uses of the loaded value.
21019 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21024 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21025 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21027 if (Subtarget->is64Bit() || F64IsLegal) {
21028 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21029 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21030 Ld->getPointerInfo(), Ld->isVolatile(),
21031 Ld->isNonTemporal(), Ld->isInvariant(),
21032 Ld->getAlignment());
21033 SDValue NewChain = NewLd.getValue(1);
21034 if (TokenFactorIndex != -1) {
21035 Ops.push_back(NewChain);
21036 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21038 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21039 St->getPointerInfo(),
21040 St->isVolatile(), St->isNonTemporal(),
21041 St->getAlignment());
21044 // Otherwise, lower to two pairs of 32-bit loads / stores.
21045 SDValue LoAddr = Ld->getBasePtr();
21046 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21047 DAG.getConstant(4, MVT::i32));
21049 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21050 Ld->getPointerInfo(),
21051 Ld->isVolatile(), Ld->isNonTemporal(),
21052 Ld->isInvariant(), Ld->getAlignment());
21053 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21054 Ld->getPointerInfo().getWithOffset(4),
21055 Ld->isVolatile(), Ld->isNonTemporal(),
21057 MinAlign(Ld->getAlignment(), 4));
21059 SDValue NewChain = LoLd.getValue(1);
21060 if (TokenFactorIndex != -1) {
21061 Ops.push_back(LoLd);
21062 Ops.push_back(HiLd);
21063 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21066 LoAddr = St->getBasePtr();
21067 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21068 DAG.getConstant(4, MVT::i32));
21070 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21071 St->getPointerInfo(),
21072 St->isVolatile(), St->isNonTemporal(),
21073 St->getAlignment());
21074 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21075 St->getPointerInfo().getWithOffset(4),
21077 St->isNonTemporal(),
21078 MinAlign(St->getAlignment(), 4));
21079 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21084 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21085 /// and return the operands for the horizontal operation in LHS and RHS. A
21086 /// horizontal operation performs the binary operation on successive elements
21087 /// of its first operand, then on successive elements of its second operand,
21088 /// returning the resulting values in a vector. For example, if
21089 /// A = < float a0, float a1, float a2, float a3 >
21091 /// B = < float b0, float b1, float b2, float b3 >
21092 /// then the result of doing a horizontal operation on A and B is
21093 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21094 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21095 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21096 /// set to A, RHS to B, and the routine returns 'true'.
21097 /// Note that the binary operation should have the property that if one of the
21098 /// operands is UNDEF then the result is UNDEF.
21099 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21100 // Look for the following pattern: if
21101 // A = < float a0, float a1, float a2, float a3 >
21102 // B = < float b0, float b1, float b2, float b3 >
21104 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21105 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21106 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21107 // which is A horizontal-op B.
21109 // At least one of the operands should be a vector shuffle.
21110 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21111 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21114 MVT VT = LHS.getSimpleValueType();
21116 assert((VT.is128BitVector() || VT.is256BitVector()) &&
21117 "Unsupported vector type for horizontal add/sub");
21119 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21120 // operate independently on 128-bit lanes.
21121 unsigned NumElts = VT.getVectorNumElements();
21122 unsigned NumLanes = VT.getSizeInBits()/128;
21123 unsigned NumLaneElts = NumElts / NumLanes;
21124 assert((NumLaneElts % 2 == 0) &&
21125 "Vector type should have an even number of elements in each lane");
21126 unsigned HalfLaneElts = NumLaneElts/2;
21128 // View LHS in the form
21129 // LHS = VECTOR_SHUFFLE A, B, LMask
21130 // If LHS is not a shuffle then pretend it is the shuffle
21131 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21132 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21135 SmallVector<int, 16> LMask(NumElts);
21136 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21137 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21138 A = LHS.getOperand(0);
21139 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21140 B = LHS.getOperand(1);
21141 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21142 std::copy(Mask.begin(), Mask.end(), LMask.begin());
21144 if (LHS.getOpcode() != ISD::UNDEF)
21146 for (unsigned i = 0; i != NumElts; ++i)
21150 // Likewise, view RHS in the form
21151 // RHS = VECTOR_SHUFFLE C, D, RMask
21153 SmallVector<int, 16> RMask(NumElts);
21154 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21155 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21156 C = RHS.getOperand(0);
21157 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21158 D = RHS.getOperand(1);
21159 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21160 std::copy(Mask.begin(), Mask.end(), RMask.begin());
21162 if (RHS.getOpcode() != ISD::UNDEF)
21164 for (unsigned i = 0; i != NumElts; ++i)
21168 // Check that the shuffles are both shuffling the same vectors.
21169 if (!(A == C && B == D) && !(A == D && B == C))
21172 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21173 if (!A.getNode() && !B.getNode())
21176 // If A and B occur in reverse order in RHS, then "swap" them (which means
21177 // rewriting the mask).
21179 CommuteVectorShuffleMask(RMask, NumElts);
21181 // At this point LHS and RHS are equivalent to
21182 // LHS = VECTOR_SHUFFLE A, B, LMask
21183 // RHS = VECTOR_SHUFFLE A, B, RMask
21184 // Check that the masks correspond to performing a horizontal operation.
21185 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21186 for (unsigned i = 0; i != NumLaneElts; ++i) {
21187 int LIdx = LMask[i+l], RIdx = RMask[i+l];
21189 // Ignore any UNDEF components.
21190 if (LIdx < 0 || RIdx < 0 ||
21191 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21192 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21195 // Check that successive elements are being operated on. If not, this is
21196 // not a horizontal operation.
21197 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21198 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21199 if (!(LIdx == Index && RIdx == Index + 1) &&
21200 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21205 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21206 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21210 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21211 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21212 const X86Subtarget *Subtarget) {
21213 EVT VT = N->getValueType(0);
21214 SDValue LHS = N->getOperand(0);
21215 SDValue RHS = N->getOperand(1);
21217 // Try to synthesize horizontal adds from adds of shuffles.
21218 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21219 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21220 isHorizontalBinOp(LHS, RHS, true))
21221 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21225 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21226 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21227 const X86Subtarget *Subtarget) {
21228 EVT VT = N->getValueType(0);
21229 SDValue LHS = N->getOperand(0);
21230 SDValue RHS = N->getOperand(1);
21232 // Try to synthesize horizontal subs from subs of shuffles.
21233 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21234 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21235 isHorizontalBinOp(LHS, RHS, false))
21236 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21240 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21241 /// X86ISD::FXOR nodes.
21242 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21243 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21244 // F[X]OR(0.0, x) -> x
21245 // F[X]OR(x, 0.0) -> x
21246 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21247 if (C->getValueAPF().isPosZero())
21248 return N->getOperand(1);
21249 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21250 if (C->getValueAPF().isPosZero())
21251 return N->getOperand(0);
21255 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21256 /// X86ISD::FMAX nodes.
21257 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21258 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21260 // Only perform optimizations if UnsafeMath is used.
21261 if (!DAG.getTarget().Options.UnsafeFPMath)
21264 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21265 // into FMINC and FMAXC, which are Commutative operations.
21266 unsigned NewOp = 0;
21267 switch (N->getOpcode()) {
21268 default: llvm_unreachable("unknown opcode");
21269 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
21270 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
21273 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21274 N->getOperand(0), N->getOperand(1));
21277 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21278 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21279 // FAND(0.0, x) -> 0.0
21280 // FAND(x, 0.0) -> 0.0
21281 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21282 if (C->getValueAPF().isPosZero())
21283 return N->getOperand(0);
21284 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21285 if (C->getValueAPF().isPosZero())
21286 return N->getOperand(1);
21290 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21291 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21292 // FANDN(x, 0.0) -> 0.0
21293 // FANDN(0.0, x) -> x
21294 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21295 if (C->getValueAPF().isPosZero())
21296 return N->getOperand(1);
21297 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21298 if (C->getValueAPF().isPosZero())
21299 return N->getOperand(1);
21303 static SDValue PerformBTCombine(SDNode *N,
21305 TargetLowering::DAGCombinerInfo &DCI) {
21306 // BT ignores high bits in the bit index operand.
21307 SDValue Op1 = N->getOperand(1);
21308 if (Op1.hasOneUse()) {
21309 unsigned BitWidth = Op1.getValueSizeInBits();
21310 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21311 APInt KnownZero, KnownOne;
21312 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21313 !DCI.isBeforeLegalizeOps());
21314 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21315 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21316 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21317 DCI.CommitTargetLoweringOpt(TLO);
21322 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21323 SDValue Op = N->getOperand(0);
21324 if (Op.getOpcode() == ISD::BITCAST)
21325 Op = Op.getOperand(0);
21326 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21327 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21328 VT.getVectorElementType().getSizeInBits() ==
21329 OpVT.getVectorElementType().getSizeInBits()) {
21330 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21335 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21336 const X86Subtarget *Subtarget) {
21337 EVT VT = N->getValueType(0);
21338 if (!VT.isVector())
21341 SDValue N0 = N->getOperand(0);
21342 SDValue N1 = N->getOperand(1);
21343 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21346 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21347 // both SSE and AVX2 since there is no sign-extended shift right
21348 // operation on a vector with 64-bit elements.
21349 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21350 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21351 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21352 N0.getOpcode() == ISD::SIGN_EXTEND)) {
21353 SDValue N00 = N0.getOperand(0);
21355 // EXTLOAD has a better solution on AVX2,
21356 // it may be replaced with X86ISD::VSEXT node.
21357 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21358 if (!ISD::isNormalLoad(N00.getNode()))
21361 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21362 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21364 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21370 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21371 TargetLowering::DAGCombinerInfo &DCI,
21372 const X86Subtarget *Subtarget) {
21373 if (!DCI.isBeforeLegalizeOps())
21376 if (!Subtarget->hasFp256())
21379 EVT VT = N->getValueType(0);
21380 if (VT.isVector() && VT.getSizeInBits() == 256) {
21381 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21389 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21390 const X86Subtarget* Subtarget) {
21392 EVT VT = N->getValueType(0);
21394 // Let legalize expand this if it isn't a legal type yet.
21395 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21398 EVT ScalarVT = VT.getScalarType();
21399 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21400 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21403 SDValue A = N->getOperand(0);
21404 SDValue B = N->getOperand(1);
21405 SDValue C = N->getOperand(2);
21407 bool NegA = (A.getOpcode() == ISD::FNEG);
21408 bool NegB = (B.getOpcode() == ISD::FNEG);
21409 bool NegC = (C.getOpcode() == ISD::FNEG);
21411 // Negative multiplication when NegA xor NegB
21412 bool NegMul = (NegA != NegB);
21414 A = A.getOperand(0);
21416 B = B.getOperand(0);
21418 C = C.getOperand(0);
21422 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21424 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21426 return DAG.getNode(Opcode, dl, VT, A, B, C);
21429 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21430 TargetLowering::DAGCombinerInfo &DCI,
21431 const X86Subtarget *Subtarget) {
21432 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
21433 // (and (i32 x86isd::setcc_carry), 1)
21434 // This eliminates the zext. This transformation is necessary because
21435 // ISD::SETCC is always legalized to i8.
21437 SDValue N0 = N->getOperand(0);
21438 EVT VT = N->getValueType(0);
21440 if (N0.getOpcode() == ISD::AND &&
21442 N0.getOperand(0).hasOneUse()) {
21443 SDValue N00 = N0.getOperand(0);
21444 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21445 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21446 if (!C || C->getZExtValue() != 1)
21448 return DAG.getNode(ISD::AND, dl, VT,
21449 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21450 N00.getOperand(0), N00.getOperand(1)),
21451 DAG.getConstant(1, VT));
21455 if (N0.getOpcode() == ISD::TRUNCATE &&
21457 N0.getOperand(0).hasOneUse()) {
21458 SDValue N00 = N0.getOperand(0);
21459 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21460 return DAG.getNode(ISD::AND, dl, VT,
21461 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21462 N00.getOperand(0), N00.getOperand(1)),
21463 DAG.getConstant(1, VT));
21466 if (VT.is256BitVector()) {
21467 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21475 // Optimize x == -y --> x+y == 0
21476 // x != -y --> x+y != 0
21477 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21478 const X86Subtarget* Subtarget) {
21479 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21480 SDValue LHS = N->getOperand(0);
21481 SDValue RHS = N->getOperand(1);
21482 EVT VT = N->getValueType(0);
21485 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21486 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21487 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21488 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21489 LHS.getValueType(), RHS, LHS.getOperand(1));
21490 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21491 addV, DAG.getConstant(0, addV.getValueType()), CC);
21493 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
21494 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
21495 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
21496 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21497 RHS.getValueType(), LHS, RHS.getOperand(1));
21498 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21499 addV, DAG.getConstant(0, addV.getValueType()), CC);
21502 if (VT.getScalarType() == MVT::i1) {
21503 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
21504 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
21505 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
21506 if (!IsSEXT0 && !IsVZero0)
21508 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
21509 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
21510 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
21512 if (!IsSEXT1 && !IsVZero1)
21515 if (IsSEXT0 && IsVZero1) {
21516 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
21517 if (CC == ISD::SETEQ)
21518 return DAG.getNOT(DL, LHS.getOperand(0), VT);
21519 return LHS.getOperand(0);
21521 if (IsSEXT1 && IsVZero0) {
21522 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
21523 if (CC == ISD::SETEQ)
21524 return DAG.getNOT(DL, RHS.getOperand(0), VT);
21525 return RHS.getOperand(0);
21532 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
21533 const X86Subtarget *Subtarget) {
21535 MVT VT = N->getOperand(1)->getSimpleValueType(0);
21536 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
21537 "X86insertps is only defined for v4x32");
21539 SDValue Ld = N->getOperand(1);
21540 if (MayFoldLoad(Ld)) {
21541 // Extract the countS bits from the immediate so we can get the proper
21542 // address when narrowing the vector load to a specific element.
21543 // When the second source op is a memory address, interps doesn't use
21544 // countS and just gets an f32 from that address.
21545 unsigned DestIndex =
21546 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
21547 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
21551 // Create this as a scalar to vector to match the instruction pattern.
21552 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
21553 // countS bits are ignored when loading from memory on insertps, which
21554 // means we don't need to explicitly set them to 0.
21555 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
21556 LoadScalarToVector, N->getOperand(2));
21559 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
21560 // as "sbb reg,reg", since it can be extended without zext and produces
21561 // an all-ones bit which is more useful than 0/1 in some cases.
21562 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
21565 return DAG.getNode(ISD::AND, DL, VT,
21566 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21567 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
21568 DAG.getConstant(1, VT));
21569 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
21570 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
21571 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21572 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
21575 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
21576 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
21577 TargetLowering::DAGCombinerInfo &DCI,
21578 const X86Subtarget *Subtarget) {
21580 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
21581 SDValue EFLAGS = N->getOperand(1);
21583 if (CC == X86::COND_A) {
21584 // Try to convert COND_A into COND_B in an attempt to facilitate
21585 // materializing "setb reg".
21587 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
21588 // cannot take an immediate as its first operand.
21590 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
21591 EFLAGS.getValueType().isInteger() &&
21592 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
21593 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
21594 EFLAGS.getNode()->getVTList(),
21595 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
21596 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
21597 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
21601 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
21602 // a zext and produces an all-ones bit which is more useful than 0/1 in some
21604 if (CC == X86::COND_B)
21605 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
21609 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21610 if (Flags.getNode()) {
21611 SDValue Cond = DAG.getConstant(CC, MVT::i8);
21612 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
21618 // Optimize branch condition evaluation.
21620 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
21621 TargetLowering::DAGCombinerInfo &DCI,
21622 const X86Subtarget *Subtarget) {
21624 SDValue Chain = N->getOperand(0);
21625 SDValue Dest = N->getOperand(1);
21626 SDValue EFLAGS = N->getOperand(3);
21627 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
21631 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21632 if (Flags.getNode()) {
21633 SDValue Cond = DAG.getConstant(CC, MVT::i8);
21634 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
21641 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
21642 const X86TargetLowering *XTLI) {
21643 SDValue Op0 = N->getOperand(0);
21644 EVT InVT = Op0->getValueType(0);
21646 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21647 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21649 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21650 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21651 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21654 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21655 // a 32-bit target where SSE doesn't support i64->FP operations.
21656 if (Op0.getOpcode() == ISD::LOAD) {
21657 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21658 EVT VT = Ld->getValueType(0);
21659 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21660 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21661 !XTLI->getSubtarget()->is64Bit() &&
21663 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21664 Ld->getChain(), Op0, DAG);
21665 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21672 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21673 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21674 X86TargetLowering::DAGCombinerInfo &DCI) {
21675 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21676 // the result is either zero or one (depending on the input carry bit).
21677 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21678 if (X86::isZeroNode(N->getOperand(0)) &&
21679 X86::isZeroNode(N->getOperand(1)) &&
21680 // We don't have a good way to replace an EFLAGS use, so only do this when
21682 SDValue(N, 1).use_empty()) {
21684 EVT VT = N->getValueType(0);
21685 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21686 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21687 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21688 DAG.getConstant(X86::COND_B,MVT::i8),
21690 DAG.getConstant(1, VT));
21691 return DCI.CombineTo(N, Res1, CarryOut);
21697 // fold (add Y, (sete X, 0)) -> adc 0, Y
21698 // (add Y, (setne X, 0)) -> sbb -1, Y
21699 // (sub (sete X, 0), Y) -> sbb 0, Y
21700 // (sub (setne X, 0), Y) -> adc -1, Y
21701 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
21704 // Look through ZExts.
21705 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
21706 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
21709 SDValue SetCC = Ext.getOperand(0);
21710 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
21713 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
21714 if (CC != X86::COND_E && CC != X86::COND_NE)
21717 SDValue Cmp = SetCC.getOperand(1);
21718 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
21719 !X86::isZeroNode(Cmp.getOperand(1)) ||
21720 !Cmp.getOperand(0).getValueType().isInteger())
21723 SDValue CmpOp0 = Cmp.getOperand(0);
21724 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
21725 DAG.getConstant(1, CmpOp0.getValueType()));
21727 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
21728 if (CC == X86::COND_NE)
21729 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
21730 DL, OtherVal.getValueType(), OtherVal,
21731 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
21732 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
21733 DL, OtherVal.getValueType(), OtherVal,
21734 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
21737 /// PerformADDCombine - Do target-specific dag combines on integer adds.
21738 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
21739 const X86Subtarget *Subtarget) {
21740 EVT VT = N->getValueType(0);
21741 SDValue Op0 = N->getOperand(0);
21742 SDValue Op1 = N->getOperand(1);
21744 // Try to synthesize horizontal adds from adds of shuffles.
21745 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21746 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21747 isHorizontalBinOp(Op0, Op1, true))
21748 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
21750 return OptimizeConditionalInDecrement(N, DAG);
21753 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
21754 const X86Subtarget *Subtarget) {
21755 SDValue Op0 = N->getOperand(0);
21756 SDValue Op1 = N->getOperand(1);
21758 // X86 can't encode an immediate LHS of a sub. See if we can push the
21759 // negation into a preceding instruction.
21760 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
21761 // If the RHS of the sub is a XOR with one use and a constant, invert the
21762 // immediate. Then add one to the LHS of the sub so we can turn
21763 // X-Y -> X+~Y+1, saving one register.
21764 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
21765 isa<ConstantSDNode>(Op1.getOperand(1))) {
21766 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
21767 EVT VT = Op0.getValueType();
21768 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
21770 DAG.getConstant(~XorC, VT));
21771 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
21772 DAG.getConstant(C->getAPIntValue()+1, VT));
21776 // Try to synthesize horizontal adds from adds of shuffles.
21777 EVT VT = N->getValueType(0);
21778 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21779 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21780 isHorizontalBinOp(Op0, Op1, true))
21781 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
21783 return OptimizeConditionalInDecrement(N, DAG);
21786 /// performVZEXTCombine - Performs build vector combines
21787 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
21788 TargetLowering::DAGCombinerInfo &DCI,
21789 const X86Subtarget *Subtarget) {
21790 // (vzext (bitcast (vzext (x)) -> (vzext x)
21791 SDValue In = N->getOperand(0);
21792 while (In.getOpcode() == ISD::BITCAST)
21793 In = In.getOperand(0);
21795 if (In.getOpcode() != X86ISD::VZEXT)
21798 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
21802 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
21803 DAGCombinerInfo &DCI) const {
21804 SelectionDAG &DAG = DCI.DAG;
21805 switch (N->getOpcode()) {
21807 case ISD::EXTRACT_VECTOR_ELT:
21808 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
21810 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
21811 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
21812 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
21813 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
21814 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
21815 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
21818 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
21819 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
21820 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
21821 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
21822 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
21823 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
21824 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
21825 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
21826 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
21828 case X86ISD::FOR: return PerformFORCombine(N, DAG);
21830 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
21831 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
21832 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
21833 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
21834 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
21835 case ISD::ANY_EXTEND:
21836 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
21837 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
21838 case ISD::SIGN_EXTEND_INREG:
21839 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
21840 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
21841 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
21842 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
21843 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
21844 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
21845 case X86ISD::SHUFP: // Handle all target specific shuffles
21846 case X86ISD::PALIGNR:
21847 case X86ISD::UNPCKH:
21848 case X86ISD::UNPCKL:
21849 case X86ISD::MOVHLPS:
21850 case X86ISD::MOVLHPS:
21851 case X86ISD::PSHUFD:
21852 case X86ISD::PSHUFHW:
21853 case X86ISD::PSHUFLW:
21854 case X86ISD::MOVSS:
21855 case X86ISD::MOVSD:
21856 case X86ISD::VPERMILP:
21857 case X86ISD::VPERM2X128:
21858 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
21859 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
21860 case ISD::INTRINSIC_WO_CHAIN:
21861 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
21862 case X86ISD::INSERTPS:
21863 return PerformINSERTPSCombine(N, DAG, Subtarget);
21864 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
21870 /// isTypeDesirableForOp - Return true if the target has native support for
21871 /// the specified value type and it is 'desirable' to use the type for the
21872 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
21873 /// instruction encodings are longer and some i16 instructions are slow.
21874 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
21875 if (!isTypeLegal(VT))
21877 if (VT != MVT::i16)
21884 case ISD::SIGN_EXTEND:
21885 case ISD::ZERO_EXTEND:
21886 case ISD::ANY_EXTEND:
21899 /// IsDesirableToPromoteOp - This method query the target whether it is
21900 /// beneficial for dag combiner to promote the specified node. If true, it
21901 /// should return the desired promotion type by reference.
21902 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
21903 EVT VT = Op.getValueType();
21904 if (VT != MVT::i16)
21907 bool Promote = false;
21908 bool Commute = false;
21909 switch (Op.getOpcode()) {
21912 LoadSDNode *LD = cast<LoadSDNode>(Op);
21913 // If the non-extending load has a single use and it's not live out, then it
21914 // might be folded.
21915 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
21916 Op.hasOneUse()*/) {
21917 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
21918 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
21919 // The only case where we'd want to promote LOAD (rather then it being
21920 // promoted as an operand is when it's only use is liveout.
21921 if (UI->getOpcode() != ISD::CopyToReg)
21928 case ISD::SIGN_EXTEND:
21929 case ISD::ZERO_EXTEND:
21930 case ISD::ANY_EXTEND:
21935 SDValue N0 = Op.getOperand(0);
21936 // Look out for (store (shl (load), x)).
21937 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
21950 SDValue N0 = Op.getOperand(0);
21951 SDValue N1 = Op.getOperand(1);
21952 if (!Commute && MayFoldLoad(N1))
21954 // Avoid disabling potential load folding opportunities.
21955 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
21957 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
21967 //===----------------------------------------------------------------------===//
21968 // X86 Inline Assembly Support
21969 //===----------------------------------------------------------------------===//
21972 // Helper to match a string separated by whitespace.
21973 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
21974 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
21976 for (unsigned i = 0, e = args.size(); i != e; ++i) {
21977 StringRef piece(*args[i]);
21978 if (!s.startswith(piece)) // Check if the piece matches.
21981 s = s.substr(piece.size());
21982 StringRef::size_type pos = s.find_first_not_of(" \t");
21983 if (pos == 0) // We matched a prefix.
21991 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
21994 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
21996 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
21997 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
21998 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
21999 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22001 if (AsmPieces.size() == 3)
22003 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22010 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22011 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22013 std::string AsmStr = IA->getAsmString();
22015 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22016 if (!Ty || Ty->getBitWidth() % 16 != 0)
22019 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22020 SmallVector<StringRef, 4> AsmPieces;
22021 SplitString(AsmStr, AsmPieces, ";\n");
22023 switch (AsmPieces.size()) {
22024 default: return false;
22026 // FIXME: this should verify that we are targeting a 486 or better. If not,
22027 // we will turn this bswap into something that will be lowered to logical
22028 // ops instead of emitting the bswap asm. For now, we don't support 486 or
22029 // lower so don't worry about this.
22031 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22032 matchAsm(AsmPieces[0], "bswapl", "$0") ||
22033 matchAsm(AsmPieces[0], "bswapq", "$0") ||
22034 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22035 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22036 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22037 // No need to check constraints, nothing other than the equivalent of
22038 // "=r,0" would be valid here.
22039 return IntrinsicLowering::LowerToByteSwap(CI);
22042 // rorw $$8, ${0:w} --> llvm.bswap.i16
22043 if (CI->getType()->isIntegerTy(16) &&
22044 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22045 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22046 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22048 const std::string &ConstraintsStr = IA->getConstraintString();
22049 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22050 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22051 if (clobbersFlagRegisters(AsmPieces))
22052 return IntrinsicLowering::LowerToByteSwap(CI);
22056 if (CI->getType()->isIntegerTy(32) &&
22057 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22058 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22059 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22060 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22062 const std::string &ConstraintsStr = IA->getConstraintString();
22063 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22064 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22065 if (clobbersFlagRegisters(AsmPieces))
22066 return IntrinsicLowering::LowerToByteSwap(CI);
22069 if (CI->getType()->isIntegerTy(64)) {
22070 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22071 if (Constraints.size() >= 2 &&
22072 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22073 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22074 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
22075 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22076 matchAsm(AsmPieces[1], "bswap", "%edx") &&
22077 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22078 return IntrinsicLowering::LowerToByteSwap(CI);
22086 /// getConstraintType - Given a constraint letter, return the type of
22087 /// constraint it is for this target.
22088 X86TargetLowering::ConstraintType
22089 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22090 if (Constraint.size() == 1) {
22091 switch (Constraint[0]) {
22102 return C_RegisterClass;
22126 return TargetLowering::getConstraintType(Constraint);
22129 /// Examine constraint type and operand type and determine a weight value.
22130 /// This object must already have been set up with the operand type
22131 /// and the current alternative constraint selected.
22132 TargetLowering::ConstraintWeight
22133 X86TargetLowering::getSingleConstraintMatchWeight(
22134 AsmOperandInfo &info, const char *constraint) const {
22135 ConstraintWeight weight = CW_Invalid;
22136 Value *CallOperandVal = info.CallOperandVal;
22137 // If we don't have a value, we can't do a match,
22138 // but allow it at the lowest weight.
22139 if (!CallOperandVal)
22141 Type *type = CallOperandVal->getType();
22142 // Look at the constraint type.
22143 switch (*constraint) {
22145 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22156 if (CallOperandVal->getType()->isIntegerTy())
22157 weight = CW_SpecificReg;
22162 if (type->isFloatingPointTy())
22163 weight = CW_SpecificReg;
22166 if (type->isX86_MMXTy() && Subtarget->hasMMX())
22167 weight = CW_SpecificReg;
22171 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22172 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22173 weight = CW_Register;
22176 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22177 if (C->getZExtValue() <= 31)
22178 weight = CW_Constant;
22182 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22183 if (C->getZExtValue() <= 63)
22184 weight = CW_Constant;
22188 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22189 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22190 weight = CW_Constant;
22194 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22195 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22196 weight = CW_Constant;
22200 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22201 if (C->getZExtValue() <= 3)
22202 weight = CW_Constant;
22206 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22207 if (C->getZExtValue() <= 0xff)
22208 weight = CW_Constant;
22213 if (dyn_cast<ConstantFP>(CallOperandVal)) {
22214 weight = CW_Constant;
22218 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22219 if ((C->getSExtValue() >= -0x80000000LL) &&
22220 (C->getSExtValue() <= 0x7fffffffLL))
22221 weight = CW_Constant;
22225 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22226 if (C->getZExtValue() <= 0xffffffff)
22227 weight = CW_Constant;
22234 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22235 /// with another that has more specific requirements based on the type of the
22236 /// corresponding operand.
22237 const char *X86TargetLowering::
22238 LowerXConstraint(EVT ConstraintVT) const {
22239 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22240 // 'f' like normal targets.
22241 if (ConstraintVT.isFloatingPoint()) {
22242 if (Subtarget->hasSSE2())
22244 if (Subtarget->hasSSE1())
22248 return TargetLowering::LowerXConstraint(ConstraintVT);
22251 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22252 /// vector. If it is invalid, don't add anything to Ops.
22253 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22254 std::string &Constraint,
22255 std::vector<SDValue>&Ops,
22256 SelectionDAG &DAG) const {
22259 // Only support length 1 constraints for now.
22260 if (Constraint.length() > 1) return;
22262 char ConstraintLetter = Constraint[0];
22263 switch (ConstraintLetter) {
22266 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22267 if (C->getZExtValue() <= 31) {
22268 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22274 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22275 if (C->getZExtValue() <= 63) {
22276 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22282 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22283 if (isInt<8>(C->getSExtValue())) {
22284 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22290 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22291 if (C->getZExtValue() <= 255) {
22292 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22298 // 32-bit signed value
22299 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22300 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22301 C->getSExtValue())) {
22302 // Widen to 64 bits here to get it sign extended.
22303 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22306 // FIXME gcc accepts some relocatable values here too, but only in certain
22307 // memory models; it's complicated.
22312 // 32-bit unsigned value
22313 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22314 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22315 C->getZExtValue())) {
22316 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22320 // FIXME gcc accepts some relocatable values here too, but only in certain
22321 // memory models; it's complicated.
22325 // Literal immediates are always ok.
22326 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22327 // Widen to 64 bits here to get it sign extended.
22328 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22332 // In any sort of PIC mode addresses need to be computed at runtime by
22333 // adding in a register or some sort of table lookup. These can't
22334 // be used as immediates.
22335 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22338 // If we are in non-pic codegen mode, we allow the address of a global (with
22339 // an optional displacement) to be used with 'i'.
22340 GlobalAddressSDNode *GA = nullptr;
22341 int64_t Offset = 0;
22343 // Match either (GA), (GA+C), (GA+C1+C2), etc.
22345 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22346 Offset += GA->getOffset();
22348 } else if (Op.getOpcode() == ISD::ADD) {
22349 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22350 Offset += C->getZExtValue();
22351 Op = Op.getOperand(0);
22354 } else if (Op.getOpcode() == ISD::SUB) {
22355 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22356 Offset += -C->getZExtValue();
22357 Op = Op.getOperand(0);
22362 // Otherwise, this isn't something we can handle, reject it.
22366 const GlobalValue *GV = GA->getGlobal();
22367 // If we require an extra load to get this address, as in PIC mode, we
22368 // can't accept it.
22369 if (isGlobalStubReference(
22370 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22373 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22374 GA->getValueType(0), Offset);
22379 if (Result.getNode()) {
22380 Ops.push_back(Result);
22383 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22386 std::pair<unsigned, const TargetRegisterClass*>
22387 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22389 // First, see if this is a constraint that directly corresponds to an LLVM
22391 if (Constraint.size() == 1) {
22392 // GCC Constraint Letters
22393 switch (Constraint[0]) {
22395 // TODO: Slight differences here in allocation order and leaving
22396 // RIP in the class. Do they matter any more here than they do
22397 // in the normal allocation?
22398 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22399 if (Subtarget->is64Bit()) {
22400 if (VT == MVT::i32 || VT == MVT::f32)
22401 return std::make_pair(0U, &X86::GR32RegClass);
22402 if (VT == MVT::i16)
22403 return std::make_pair(0U, &X86::GR16RegClass);
22404 if (VT == MVT::i8 || VT == MVT::i1)
22405 return std::make_pair(0U, &X86::GR8RegClass);
22406 if (VT == MVT::i64 || VT == MVT::f64)
22407 return std::make_pair(0U, &X86::GR64RegClass);
22410 // 32-bit fallthrough
22411 case 'Q': // Q_REGS
22412 if (VT == MVT::i32 || VT == MVT::f32)
22413 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22414 if (VT == MVT::i16)
22415 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22416 if (VT == MVT::i8 || VT == MVT::i1)
22417 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22418 if (VT == MVT::i64)
22419 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22421 case 'r': // GENERAL_REGS
22422 case 'l': // INDEX_REGS
22423 if (VT == MVT::i8 || VT == MVT::i1)
22424 return std::make_pair(0U, &X86::GR8RegClass);
22425 if (VT == MVT::i16)
22426 return std::make_pair(0U, &X86::GR16RegClass);
22427 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22428 return std::make_pair(0U, &X86::GR32RegClass);
22429 return std::make_pair(0U, &X86::GR64RegClass);
22430 case 'R': // LEGACY_REGS
22431 if (VT == MVT::i8 || VT == MVT::i1)
22432 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22433 if (VT == MVT::i16)
22434 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22435 if (VT == MVT::i32 || !Subtarget->is64Bit())
22436 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
22437 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
22438 case 'f': // FP Stack registers.
22439 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
22440 // value to the correct fpstack register class.
22441 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
22442 return std::make_pair(0U, &X86::RFP32RegClass);
22443 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
22444 return std::make_pair(0U, &X86::RFP64RegClass);
22445 return std::make_pair(0U, &X86::RFP80RegClass);
22446 case 'y': // MMX_REGS if MMX allowed.
22447 if (!Subtarget->hasMMX()) break;
22448 return std::make_pair(0U, &X86::VR64RegClass);
22449 case 'Y': // SSE_REGS if SSE2 allowed
22450 if (!Subtarget->hasSSE2()) break;
22452 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
22453 if (!Subtarget->hasSSE1()) break;
22455 switch (VT.SimpleTy) {
22457 // Scalar SSE types.
22460 return std::make_pair(0U, &X86::FR32RegClass);
22463 return std::make_pair(0U, &X86::FR64RegClass);
22471 return std::make_pair(0U, &X86::VR128RegClass);
22479 return std::make_pair(0U, &X86::VR256RegClass);
22484 return std::make_pair(0U, &X86::VR512RegClass);
22490 // Use the default implementation in TargetLowering to convert the register
22491 // constraint into a member of a register class.
22492 std::pair<unsigned, const TargetRegisterClass*> Res;
22493 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
22495 // Not found as a standard register?
22497 // Map st(0) -> st(7) -> ST0
22498 if (Constraint.size() == 7 && Constraint[0] == '{' &&
22499 tolower(Constraint[1]) == 's' &&
22500 tolower(Constraint[2]) == 't' &&
22501 Constraint[3] == '(' &&
22502 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
22503 Constraint[5] == ')' &&
22504 Constraint[6] == '}') {
22506 Res.first = X86::ST0+Constraint[4]-'0';
22507 Res.second = &X86::RFP80RegClass;
22511 // GCC allows "st(0)" to be called just plain "st".
22512 if (StringRef("{st}").equals_lower(Constraint)) {
22513 Res.first = X86::ST0;
22514 Res.second = &X86::RFP80RegClass;
22519 if (StringRef("{flags}").equals_lower(Constraint)) {
22520 Res.first = X86::EFLAGS;
22521 Res.second = &X86::CCRRegClass;
22525 // 'A' means EAX + EDX.
22526 if (Constraint == "A") {
22527 Res.first = X86::EAX;
22528 Res.second = &X86::GR32_ADRegClass;
22534 // Otherwise, check to see if this is a register class of the wrong value
22535 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
22536 // turn into {ax},{dx}.
22537 if (Res.second->hasType(VT))
22538 return Res; // Correct type already, nothing to do.
22540 // All of the single-register GCC register classes map their values onto
22541 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
22542 // really want an 8-bit or 32-bit register, map to the appropriate register
22543 // class and return the appropriate register.
22544 if (Res.second == &X86::GR16RegClass) {
22545 if (VT == MVT::i8 || VT == MVT::i1) {
22546 unsigned DestReg = 0;
22547 switch (Res.first) {
22549 case X86::AX: DestReg = X86::AL; break;
22550 case X86::DX: DestReg = X86::DL; break;
22551 case X86::CX: DestReg = X86::CL; break;
22552 case X86::BX: DestReg = X86::BL; break;
22555 Res.first = DestReg;
22556 Res.second = &X86::GR8RegClass;
22558 } else if (VT == MVT::i32 || VT == MVT::f32) {
22559 unsigned DestReg = 0;
22560 switch (Res.first) {
22562 case X86::AX: DestReg = X86::EAX; break;
22563 case X86::DX: DestReg = X86::EDX; break;
22564 case X86::CX: DestReg = X86::ECX; break;
22565 case X86::BX: DestReg = X86::EBX; break;
22566 case X86::SI: DestReg = X86::ESI; break;
22567 case X86::DI: DestReg = X86::EDI; break;
22568 case X86::BP: DestReg = X86::EBP; break;
22569 case X86::SP: DestReg = X86::ESP; break;
22572 Res.first = DestReg;
22573 Res.second = &X86::GR32RegClass;
22575 } else if (VT == MVT::i64 || VT == MVT::f64) {
22576 unsigned DestReg = 0;
22577 switch (Res.first) {
22579 case X86::AX: DestReg = X86::RAX; break;
22580 case X86::DX: DestReg = X86::RDX; break;
22581 case X86::CX: DestReg = X86::RCX; break;
22582 case X86::BX: DestReg = X86::RBX; break;
22583 case X86::SI: DestReg = X86::RSI; break;
22584 case X86::DI: DestReg = X86::RDI; break;
22585 case X86::BP: DestReg = X86::RBP; break;
22586 case X86::SP: DestReg = X86::RSP; break;
22589 Res.first = DestReg;
22590 Res.second = &X86::GR64RegClass;
22593 } else if (Res.second == &X86::FR32RegClass ||
22594 Res.second == &X86::FR64RegClass ||
22595 Res.second == &X86::VR128RegClass ||
22596 Res.second == &X86::VR256RegClass ||
22597 Res.second == &X86::FR32XRegClass ||
22598 Res.second == &X86::FR64XRegClass ||
22599 Res.second == &X86::VR128XRegClass ||
22600 Res.second == &X86::VR256XRegClass ||
22601 Res.second == &X86::VR512RegClass) {
22602 // Handle references to XMM physical registers that got mapped into the
22603 // wrong class. This can happen with constraints like {xmm0} where the
22604 // target independent register mapper will just pick the first match it can
22605 // find, ignoring the required type.
22607 if (VT == MVT::f32 || VT == MVT::i32)
22608 Res.second = &X86::FR32RegClass;
22609 else if (VT == MVT::f64 || VT == MVT::i64)
22610 Res.second = &X86::FR64RegClass;
22611 else if (X86::VR128RegClass.hasType(VT))
22612 Res.second = &X86::VR128RegClass;
22613 else if (X86::VR256RegClass.hasType(VT))
22614 Res.second = &X86::VR256RegClass;
22615 else if (X86::VR512RegClass.hasType(VT))
22616 Res.second = &X86::VR512RegClass;
22622 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
22624 // Scaling factors are not free at all.
22625 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
22626 // will take 2 allocations in the out of order engine instead of 1
22627 // for plain addressing mode, i.e. inst (reg1).
22629 // vaddps (%rsi,%drx), %ymm0, %ymm1
22630 // Requires two allocations (one for the load, one for the computation)
22632 // vaddps (%rsi), %ymm0, %ymm1
22633 // Requires just 1 allocation, i.e., freeing allocations for other operations
22634 // and having less micro operations to execute.
22636 // For some X86 architectures, this is even worse because for instance for
22637 // stores, the complex addressing mode forces the instruction to use the
22638 // "load" ports instead of the dedicated "store" port.
22639 // E.g., on Haswell:
22640 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
22641 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
22642 if (isLegalAddressingMode(AM, Ty))
22643 // Scale represents reg2 * scale, thus account for 1
22644 // as soon as we use a second register.
22645 return AM.Scale != 0;
22649 bool X86TargetLowering::isTargetFTOL() const {
22650 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();