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->is64Bit()) {
596 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
597 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
598 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
599 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
600 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
601 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
602 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
603 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
604 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
605 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
606 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
607 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
610 if (Subtarget->hasCmpxchg16b()) {
611 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
614 // FIXME - use subtarget debug flags
615 if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
616 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
617 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
620 if (Subtarget->is64Bit()) {
621 setExceptionPointerRegister(X86::RAX);
622 setExceptionSelectorRegister(X86::RDX);
624 setExceptionPointerRegister(X86::EAX);
625 setExceptionSelectorRegister(X86::EDX);
627 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
628 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
630 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
631 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
633 setOperationAction(ISD::TRAP, MVT::Other, Legal);
634 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
636 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
637 setOperationAction(ISD::VASTART , MVT::Other, Custom);
638 setOperationAction(ISD::VAEND , MVT::Other, Expand);
639 if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
640 // TargetInfo::X86_64ABIBuiltinVaList
641 setOperationAction(ISD::VAARG , MVT::Other, Custom);
642 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
644 // TargetInfo::CharPtrBuiltinVaList
645 setOperationAction(ISD::VAARG , MVT::Other, Expand);
646 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
649 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
650 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
652 setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
653 MVT::i64 : MVT::i32, Custom);
655 if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
656 // f32 and f64 use SSE.
657 // Set up the FP register classes.
658 addRegisterClass(MVT::f32, &X86::FR32RegClass);
659 addRegisterClass(MVT::f64, &X86::FR64RegClass);
661 // Use ANDPD to simulate FABS.
662 setOperationAction(ISD::FABS , MVT::f64, Custom);
663 setOperationAction(ISD::FABS , MVT::f32, Custom);
665 // Use XORP to simulate FNEG.
666 setOperationAction(ISD::FNEG , MVT::f64, Custom);
667 setOperationAction(ISD::FNEG , MVT::f32, Custom);
669 // Use ANDPD and ORPD to simulate FCOPYSIGN.
670 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
671 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
673 // Lower this to FGETSIGNx86 plus an AND.
674 setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
675 setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
677 // We don't support sin/cos/fmod
678 setOperationAction(ISD::FSIN , MVT::f64, Expand);
679 setOperationAction(ISD::FCOS , MVT::f64, Expand);
680 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
681 setOperationAction(ISD::FSIN , MVT::f32, Expand);
682 setOperationAction(ISD::FCOS , MVT::f32, Expand);
683 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
685 // Expand FP immediates into loads from the stack, except for the special
687 addLegalFPImmediate(APFloat(+0.0)); // xorpd
688 addLegalFPImmediate(APFloat(+0.0f)); // xorps
689 } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
690 // Use SSE for f32, x87 for f64.
691 // Set up the FP register classes.
692 addRegisterClass(MVT::f32, &X86::FR32RegClass);
693 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
695 // Use ANDPS to simulate FABS.
696 setOperationAction(ISD::FABS , MVT::f32, Custom);
698 // Use XORP to simulate FNEG.
699 setOperationAction(ISD::FNEG , MVT::f32, Custom);
701 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
703 // Use ANDPS and ORPS to simulate FCOPYSIGN.
704 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
705 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
707 // We don't support sin/cos/fmod
708 setOperationAction(ISD::FSIN , MVT::f32, Expand);
709 setOperationAction(ISD::FCOS , MVT::f32, Expand);
710 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
712 // Special cases we handle for FP constants.
713 addLegalFPImmediate(APFloat(+0.0f)); // xorps
714 addLegalFPImmediate(APFloat(+0.0)); // FLD0
715 addLegalFPImmediate(APFloat(+1.0)); // FLD1
716 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
717 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
719 if (!TM.Options.UnsafeFPMath) {
720 setOperationAction(ISD::FSIN , MVT::f64, Expand);
721 setOperationAction(ISD::FCOS , MVT::f64, Expand);
722 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
724 } else if (!TM.Options.UseSoftFloat) {
725 // f32 and f64 in x87.
726 // Set up the FP register classes.
727 addRegisterClass(MVT::f64, &X86::RFP64RegClass);
728 addRegisterClass(MVT::f32, &X86::RFP32RegClass);
730 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
731 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
732 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
733 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
735 if (!TM.Options.UnsafeFPMath) {
736 setOperationAction(ISD::FSIN , MVT::f64, Expand);
737 setOperationAction(ISD::FSIN , MVT::f32, Expand);
738 setOperationAction(ISD::FCOS , MVT::f64, Expand);
739 setOperationAction(ISD::FCOS , MVT::f32, Expand);
740 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
741 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
743 addLegalFPImmediate(APFloat(+0.0)); // FLD0
744 addLegalFPImmediate(APFloat(+1.0)); // FLD1
745 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
746 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
747 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
748 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
749 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
750 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
753 // We don't support FMA.
754 setOperationAction(ISD::FMA, MVT::f64, Expand);
755 setOperationAction(ISD::FMA, MVT::f32, Expand);
757 // Long double always uses X87.
758 if (!TM.Options.UseSoftFloat) {
759 addRegisterClass(MVT::f80, &X86::RFP80RegClass);
760 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
761 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
763 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
764 addLegalFPImmediate(TmpFlt); // FLD0
766 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
769 APFloat TmpFlt2(+1.0);
770 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
772 addLegalFPImmediate(TmpFlt2); // FLD1
773 TmpFlt2.changeSign();
774 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
777 if (!TM.Options.UnsafeFPMath) {
778 setOperationAction(ISD::FSIN , MVT::f80, Expand);
779 setOperationAction(ISD::FCOS , MVT::f80, Expand);
780 setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
783 setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
784 setOperationAction(ISD::FCEIL, MVT::f80, Expand);
785 setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
786 setOperationAction(ISD::FRINT, MVT::f80, Expand);
787 setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
788 setOperationAction(ISD::FMA, MVT::f80, Expand);
791 // Always use a library call for pow.
792 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
793 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
794 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
796 setOperationAction(ISD::FLOG, MVT::f80, Expand);
797 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
798 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
799 setOperationAction(ISD::FEXP, MVT::f80, Expand);
800 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
802 // First set operation action for all vector types to either promote
803 // (for widening) or expand (for scalarization). Then we will selectively
804 // turn on ones that can be effectively codegen'd.
805 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
806 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
807 MVT VT = (MVT::SimpleValueType)i;
808 setOperationAction(ISD::ADD , VT, Expand);
809 setOperationAction(ISD::SUB , VT, Expand);
810 setOperationAction(ISD::FADD, VT, Expand);
811 setOperationAction(ISD::FNEG, VT, Expand);
812 setOperationAction(ISD::FSUB, VT, Expand);
813 setOperationAction(ISD::MUL , VT, Expand);
814 setOperationAction(ISD::FMUL, VT, Expand);
815 setOperationAction(ISD::SDIV, VT, Expand);
816 setOperationAction(ISD::UDIV, VT, Expand);
817 setOperationAction(ISD::FDIV, VT, Expand);
818 setOperationAction(ISD::SREM, VT, Expand);
819 setOperationAction(ISD::UREM, VT, Expand);
820 setOperationAction(ISD::LOAD, VT, Expand);
821 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
822 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
823 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
824 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
825 setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
826 setOperationAction(ISD::FABS, VT, Expand);
827 setOperationAction(ISD::FSIN, VT, Expand);
828 setOperationAction(ISD::FSINCOS, VT, Expand);
829 setOperationAction(ISD::FCOS, VT, Expand);
830 setOperationAction(ISD::FSINCOS, VT, Expand);
831 setOperationAction(ISD::FREM, VT, Expand);
832 setOperationAction(ISD::FMA, VT, Expand);
833 setOperationAction(ISD::FPOWI, VT, Expand);
834 setOperationAction(ISD::FSQRT, VT, Expand);
835 setOperationAction(ISD::FCOPYSIGN, VT, Expand);
836 setOperationAction(ISD::FFLOOR, VT, Expand);
837 setOperationAction(ISD::FCEIL, VT, Expand);
838 setOperationAction(ISD::FTRUNC, VT, Expand);
839 setOperationAction(ISD::FRINT, VT, Expand);
840 setOperationAction(ISD::FNEARBYINT, VT, Expand);
841 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
842 setOperationAction(ISD::MULHS, VT, Expand);
843 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
844 setOperationAction(ISD::MULHU, VT, Expand);
845 setOperationAction(ISD::SDIVREM, VT, Expand);
846 setOperationAction(ISD::UDIVREM, VT, Expand);
847 setOperationAction(ISD::FPOW, VT, Expand);
848 setOperationAction(ISD::CTPOP, VT, Expand);
849 setOperationAction(ISD::CTTZ, VT, Expand);
850 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
851 setOperationAction(ISD::CTLZ, VT, Expand);
852 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
853 setOperationAction(ISD::SHL, VT, Expand);
854 setOperationAction(ISD::SRA, VT, Expand);
855 setOperationAction(ISD::SRL, VT, Expand);
856 setOperationAction(ISD::ROTL, VT, Expand);
857 setOperationAction(ISD::ROTR, VT, Expand);
858 setOperationAction(ISD::BSWAP, VT, Expand);
859 setOperationAction(ISD::SETCC, VT, Expand);
860 setOperationAction(ISD::FLOG, VT, Expand);
861 setOperationAction(ISD::FLOG2, VT, Expand);
862 setOperationAction(ISD::FLOG10, VT, Expand);
863 setOperationAction(ISD::FEXP, VT, Expand);
864 setOperationAction(ISD::FEXP2, VT, Expand);
865 setOperationAction(ISD::FP_TO_UINT, VT, Expand);
866 setOperationAction(ISD::FP_TO_SINT, VT, Expand);
867 setOperationAction(ISD::UINT_TO_FP, VT, Expand);
868 setOperationAction(ISD::SINT_TO_FP, VT, Expand);
869 setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
870 setOperationAction(ISD::TRUNCATE, VT, Expand);
871 setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
872 setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
873 setOperationAction(ISD::ANY_EXTEND, VT, Expand);
874 setOperationAction(ISD::VSELECT, VT, Expand);
875 setOperationAction(ISD::SELECT_CC, VT, Expand);
876 for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
877 InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
878 setTruncStoreAction(VT,
879 (MVT::SimpleValueType)InnerVT, Expand);
880 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
881 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
882 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
885 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
886 // with -msoft-float, disable use of MMX as well.
887 if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
888 addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
889 // No operations on x86mmx supported, everything uses intrinsics.
892 // MMX-sized vectors (other than x86mmx) are expected to be expanded
893 // into smaller operations.
894 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
895 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
896 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
897 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
898 setOperationAction(ISD::AND, MVT::v8i8, Expand);
899 setOperationAction(ISD::AND, MVT::v4i16, Expand);
900 setOperationAction(ISD::AND, MVT::v2i32, Expand);
901 setOperationAction(ISD::AND, MVT::v1i64, Expand);
902 setOperationAction(ISD::OR, MVT::v8i8, Expand);
903 setOperationAction(ISD::OR, MVT::v4i16, Expand);
904 setOperationAction(ISD::OR, MVT::v2i32, Expand);
905 setOperationAction(ISD::OR, MVT::v1i64, Expand);
906 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
907 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
908 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
909 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
910 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
911 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
912 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
913 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
914 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
915 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
916 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
917 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
918 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
919 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
920 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
921 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
922 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
924 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
925 addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
927 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
928 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
929 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
930 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
931 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
932 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
933 setOperationAction(ISD::FABS, MVT::v4f32, Custom);
934 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
935 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
936 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
937 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
938 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
941 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
942 addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
944 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
945 // registers cannot be used even for integer operations.
946 addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
947 addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
948 addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
949 addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
951 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
952 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
953 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
954 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
955 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
956 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
957 setOperationAction(ISD::UMUL_LOHI, MVT::v4i32, Custom);
958 setOperationAction(ISD::SMUL_LOHI, MVT::v4i32, Custom);
959 setOperationAction(ISD::MULHU, MVT::v8i16, Legal);
960 setOperationAction(ISD::MULHS, MVT::v8i16, Legal);
961 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
962 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
963 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
964 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
965 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
966 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
967 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
968 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
969 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
970 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
971 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
972 setOperationAction(ISD::FABS, MVT::v2f64, Custom);
974 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
975 setOperationAction(ISD::SETCC, MVT::v16i8, Custom);
976 setOperationAction(ISD::SETCC, MVT::v8i16, Custom);
977 setOperationAction(ISD::SETCC, MVT::v4i32, Custom);
979 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
980 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
981 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
982 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
983 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
985 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
986 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
987 MVT VT = (MVT::SimpleValueType)i;
988 // Do not attempt to custom lower non-power-of-2 vectors
989 if (!isPowerOf2_32(VT.getVectorNumElements()))
991 // Do not attempt to custom lower non-128-bit vectors
992 if (!VT.is128BitVector())
994 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
995 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
996 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
999 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1000 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1001 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
1002 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
1003 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
1004 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1006 if (Subtarget->is64Bit()) {
1007 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1008 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1011 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1012 for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1013 MVT VT = (MVT::SimpleValueType)i;
1015 // Do not attempt to promote non-128-bit vectors
1016 if (!VT.is128BitVector())
1019 setOperationAction(ISD::AND, VT, Promote);
1020 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
1021 setOperationAction(ISD::OR, VT, Promote);
1022 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
1023 setOperationAction(ISD::XOR, VT, Promote);
1024 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
1025 setOperationAction(ISD::LOAD, VT, Promote);
1026 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
1027 setOperationAction(ISD::SELECT, VT, Promote);
1028 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1031 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1033 // Custom lower v2i64 and v2f64 selects.
1034 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
1035 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
1036 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
1037 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
1039 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
1040 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
1042 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
1043 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
1044 // As there is no 64-bit GPR available, we need build a special custom
1045 // sequence to convert from v2i32 to v2f32.
1046 if (!Subtarget->is64Bit())
1047 setOperationAction(ISD::UINT_TO_FP, MVT::v2f32, Custom);
1049 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1050 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Custom);
1052 setLoadExtAction(ISD::EXTLOAD, MVT::v2f32, Legal);
1054 setOperationAction(ISD::BITCAST, MVT::v2i32, Custom);
1055 setOperationAction(ISD::BITCAST, MVT::v4i16, Custom);
1056 setOperationAction(ISD::BITCAST, MVT::v8i8, Custom);
1059 if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1060 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1061 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1062 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1063 setOperationAction(ISD::FRINT, MVT::f32, Legal);
1064 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1065 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1066 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1067 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1068 setOperationAction(ISD::FRINT, MVT::f64, Legal);
1069 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1071 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1072 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
1073 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1074 setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
1075 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
1076 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
1077 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
1078 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
1079 setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
1080 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
1082 // FIXME: Do we need to handle scalar-to-vector here?
1083 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
1085 setOperationAction(ISD::VSELECT, MVT::v2f64, Custom);
1086 setOperationAction(ISD::VSELECT, MVT::v2i64, Custom);
1087 setOperationAction(ISD::VSELECT, MVT::v4i32, Custom);
1088 setOperationAction(ISD::VSELECT, MVT::v4f32, Custom);
1089 setOperationAction(ISD::VSELECT, MVT::v8i16, Custom);
1090 // There is no BLENDI for byte vectors. We don't need to custom lower
1091 // some vselects for now.
1092 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
1094 // i8 and i16 vectors are custom , because the source register and source
1095 // source memory operand types are not the same width. f32 vectors are
1096 // custom since the immediate controlling the insert encodes additional
1098 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1099 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1100 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1101 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1103 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1104 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1105 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1106 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1108 // FIXME: these should be Legal but thats only for the case where
1109 // the index is constant. For now custom expand to deal with that.
1110 if (Subtarget->is64Bit()) {
1111 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
1112 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1116 if (Subtarget->hasSSE2()) {
1117 setOperationAction(ISD::SRL, MVT::v8i16, Custom);
1118 setOperationAction(ISD::SRL, MVT::v16i8, Custom);
1120 setOperationAction(ISD::SHL, MVT::v8i16, Custom);
1121 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
1123 setOperationAction(ISD::SRA, MVT::v8i16, Custom);
1124 setOperationAction(ISD::SRA, MVT::v16i8, Custom);
1126 // In the customized shift lowering, the legal cases in AVX2 will be
1128 setOperationAction(ISD::SRL, MVT::v2i64, Custom);
1129 setOperationAction(ISD::SRL, MVT::v4i32, Custom);
1131 setOperationAction(ISD::SHL, MVT::v2i64, Custom);
1132 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
1134 setOperationAction(ISD::SRA, MVT::v4i32, Custom);
1137 if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1138 addRegisterClass(MVT::v32i8, &X86::VR256RegClass);
1139 addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1140 addRegisterClass(MVT::v8i32, &X86::VR256RegClass);
1141 addRegisterClass(MVT::v8f32, &X86::VR256RegClass);
1142 addRegisterClass(MVT::v4i64, &X86::VR256RegClass);
1143 addRegisterClass(MVT::v4f64, &X86::VR256RegClass);
1145 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
1146 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
1147 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
1149 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
1150 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
1151 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
1152 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
1153 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
1154 setOperationAction(ISD::FFLOOR, MVT::v8f32, Legal);
1155 setOperationAction(ISD::FCEIL, MVT::v8f32, Legal);
1156 setOperationAction(ISD::FTRUNC, MVT::v8f32, Legal);
1157 setOperationAction(ISD::FRINT, MVT::v8f32, Legal);
1158 setOperationAction(ISD::FNEARBYINT, MVT::v8f32, Legal);
1159 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
1160 setOperationAction(ISD::FABS, MVT::v8f32, Custom);
1162 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
1163 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
1164 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
1165 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1166 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1167 setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1168 setOperationAction(ISD::FCEIL, MVT::v4f64, Legal);
1169 setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1170 setOperationAction(ISD::FRINT, MVT::v4f64, Legal);
1171 setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Legal);
1172 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
1173 setOperationAction(ISD::FABS, MVT::v4f64, Custom);
1175 // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1176 // even though v8i16 is a legal type.
1177 setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Promote);
1178 setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Promote);
1179 setOperationAction(ISD::FP_TO_SINT, MVT::v8i32, Legal);
1181 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
1182 setOperationAction(ISD::SINT_TO_FP, MVT::v8i32, Legal);
1183 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Legal);
1185 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
1186 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
1188 setLoadExtAction(ISD::EXTLOAD, MVT::v4f32, Legal);
1190 setOperationAction(ISD::SRL, MVT::v16i16, Custom);
1191 setOperationAction(ISD::SRL, MVT::v32i8, Custom);
1193 setOperationAction(ISD::SHL, MVT::v16i16, Custom);
1194 setOperationAction(ISD::SHL, MVT::v32i8, Custom);
1196 setOperationAction(ISD::SRA, MVT::v16i16, Custom);
1197 setOperationAction(ISD::SRA, MVT::v32i8, Custom);
1199 setOperationAction(ISD::SETCC, MVT::v32i8, Custom);
1200 setOperationAction(ISD::SETCC, MVT::v16i16, Custom);
1201 setOperationAction(ISD::SETCC, MVT::v8i32, Custom);
1202 setOperationAction(ISD::SETCC, MVT::v4i64, Custom);
1204 setOperationAction(ISD::SELECT, MVT::v4f64, Custom);
1205 setOperationAction(ISD::SELECT, MVT::v4i64, Custom);
1206 setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
1208 setOperationAction(ISD::VSELECT, MVT::v4f64, Custom);
1209 setOperationAction(ISD::VSELECT, MVT::v4i64, Custom);
1210 setOperationAction(ISD::VSELECT, MVT::v8i32, Custom);
1211 setOperationAction(ISD::VSELECT, MVT::v8f32, Custom);
1213 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i64, Custom);
1214 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i32, Custom);
1215 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1216 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i64, Custom);
1217 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i32, Custom);
1218 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i16, Custom);
1219 setOperationAction(ISD::ANY_EXTEND, MVT::v4i64, Custom);
1220 setOperationAction(ISD::ANY_EXTEND, MVT::v8i32, Custom);
1221 setOperationAction(ISD::ANY_EXTEND, MVT::v16i16, Custom);
1222 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1223 setOperationAction(ISD::TRUNCATE, MVT::v8i16, Custom);
1224 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Custom);
1226 if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1227 setOperationAction(ISD::FMA, MVT::v8f32, Legal);
1228 setOperationAction(ISD::FMA, MVT::v4f64, Legal);
1229 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
1230 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
1231 setOperationAction(ISD::FMA, MVT::f32, Legal);
1232 setOperationAction(ISD::FMA, MVT::f64, Legal);
1235 if (Subtarget->hasInt256()) {
1236 setOperationAction(ISD::ADD, MVT::v4i64, Legal);
1237 setOperationAction(ISD::ADD, MVT::v8i32, Legal);
1238 setOperationAction(ISD::ADD, MVT::v16i16, Legal);
1239 setOperationAction(ISD::ADD, MVT::v32i8, Legal);
1241 setOperationAction(ISD::SUB, MVT::v4i64, Legal);
1242 setOperationAction(ISD::SUB, MVT::v8i32, Legal);
1243 setOperationAction(ISD::SUB, MVT::v16i16, Legal);
1244 setOperationAction(ISD::SUB, MVT::v32i8, Legal);
1246 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1247 setOperationAction(ISD::MUL, MVT::v8i32, Legal);
1248 setOperationAction(ISD::MUL, MVT::v16i16, Legal);
1249 // Don't lower v32i8 because there is no 128-bit byte mul
1251 setOperationAction(ISD::UMUL_LOHI, MVT::v8i32, Custom);
1252 setOperationAction(ISD::SMUL_LOHI, MVT::v8i32, Custom);
1253 setOperationAction(ISD::MULHU, MVT::v16i16, Legal);
1254 setOperationAction(ISD::MULHS, MVT::v16i16, Legal);
1256 setOperationAction(ISD::VSELECT, MVT::v16i16, Custom);
1257 setOperationAction(ISD::VSELECT, MVT::v32i8, Legal);
1259 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
1260 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
1261 setOperationAction(ISD::ADD, MVT::v16i16, Custom);
1262 setOperationAction(ISD::ADD, MVT::v32i8, Custom);
1264 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
1265 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
1266 setOperationAction(ISD::SUB, MVT::v16i16, Custom);
1267 setOperationAction(ISD::SUB, MVT::v32i8, Custom);
1269 setOperationAction(ISD::MUL, MVT::v4i64, Custom);
1270 setOperationAction(ISD::MUL, MVT::v8i32, Custom);
1271 setOperationAction(ISD::MUL, MVT::v16i16, Custom);
1272 // Don't lower v32i8 because there is no 128-bit byte mul
1275 // In the customized shift lowering, the legal cases in AVX2 will be
1277 setOperationAction(ISD::SRL, MVT::v4i64, Custom);
1278 setOperationAction(ISD::SRL, MVT::v8i32, Custom);
1280 setOperationAction(ISD::SHL, MVT::v4i64, Custom);
1281 setOperationAction(ISD::SHL, MVT::v8i32, Custom);
1283 setOperationAction(ISD::SRA, MVT::v8i32, Custom);
1285 // Custom lower several nodes for 256-bit types.
1286 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1287 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1288 MVT VT = (MVT::SimpleValueType)i;
1290 // Extract subvector is special because the value type
1291 // (result) is 128-bit but the source is 256-bit wide.
1292 if (VT.is128BitVector())
1293 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1295 // Do not attempt to custom lower other non-256-bit vectors
1296 if (!VT.is256BitVector())
1299 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1300 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1301 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1302 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1303 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1304 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1305 setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
1308 // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1309 for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1310 MVT VT = (MVT::SimpleValueType)i;
1312 // Do not attempt to promote non-256-bit vectors
1313 if (!VT.is256BitVector())
1316 setOperationAction(ISD::AND, VT, Promote);
1317 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1318 setOperationAction(ISD::OR, VT, Promote);
1319 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1320 setOperationAction(ISD::XOR, VT, Promote);
1321 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1322 setOperationAction(ISD::LOAD, VT, Promote);
1323 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1324 setOperationAction(ISD::SELECT, VT, Promote);
1325 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1329 if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1330 addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1331 addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1332 addRegisterClass(MVT::v8i64, &X86::VR512RegClass);
1333 addRegisterClass(MVT::v8f64, &X86::VR512RegClass);
1335 addRegisterClass(MVT::i1, &X86::VK1RegClass);
1336 addRegisterClass(MVT::v8i1, &X86::VK8RegClass);
1337 addRegisterClass(MVT::v16i1, &X86::VK16RegClass);
1339 setOperationAction(ISD::BR_CC, MVT::i1, Expand);
1340 setOperationAction(ISD::SETCC, MVT::i1, Custom);
1341 setOperationAction(ISD::XOR, MVT::i1, Legal);
1342 setOperationAction(ISD::OR, MVT::i1, Legal);
1343 setOperationAction(ISD::AND, MVT::i1, Legal);
1344 setLoadExtAction(ISD::EXTLOAD, MVT::v8f32, Legal);
1345 setOperationAction(ISD::LOAD, MVT::v16f32, Legal);
1346 setOperationAction(ISD::LOAD, MVT::v8f64, Legal);
1347 setOperationAction(ISD::LOAD, MVT::v8i64, Legal);
1348 setOperationAction(ISD::LOAD, MVT::v16i32, Legal);
1349 setOperationAction(ISD::LOAD, MVT::v16i1, Legal);
1351 setOperationAction(ISD::FADD, MVT::v16f32, Legal);
1352 setOperationAction(ISD::FSUB, MVT::v16f32, Legal);
1353 setOperationAction(ISD::FMUL, MVT::v16f32, Legal);
1354 setOperationAction(ISD::FDIV, MVT::v16f32, Legal);
1355 setOperationAction(ISD::FSQRT, MVT::v16f32, Legal);
1356 setOperationAction(ISD::FNEG, MVT::v16f32, Custom);
1358 setOperationAction(ISD::FADD, MVT::v8f64, Legal);
1359 setOperationAction(ISD::FSUB, MVT::v8f64, Legal);
1360 setOperationAction(ISD::FMUL, MVT::v8f64, Legal);
1361 setOperationAction(ISD::FDIV, MVT::v8f64, Legal);
1362 setOperationAction(ISD::FSQRT, MVT::v8f64, Legal);
1363 setOperationAction(ISD::FNEG, MVT::v8f64, Custom);
1364 setOperationAction(ISD::FMA, MVT::v8f64, Legal);
1365 setOperationAction(ISD::FMA, MVT::v16f32, Legal);
1367 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
1368 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
1369 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
1370 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
1371 if (Subtarget->is64Bit()) {
1372 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Legal);
1373 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Legal);
1374 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Legal);
1375 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Legal);
1377 setOperationAction(ISD::FP_TO_SINT, MVT::v16i32, Legal);
1378 setOperationAction(ISD::FP_TO_UINT, MVT::v16i32, Legal);
1379 setOperationAction(ISD::FP_TO_UINT, MVT::v8i32, Legal);
1380 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
1381 setOperationAction(ISD::SINT_TO_FP, MVT::v16i32, Legal);
1382 setOperationAction(ISD::UINT_TO_FP, MVT::v16i32, Legal);
1383 setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Legal);
1384 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
1385 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Legal);
1386 setOperationAction(ISD::FP_EXTEND, MVT::v8f32, Legal);
1388 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
1389 setOperationAction(ISD::TRUNCATE, MVT::v16i8, Custom);
1390 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Custom);
1391 setOperationAction(ISD::TRUNCATE, MVT::v8i1, Custom);
1392 setOperationAction(ISD::TRUNCATE, MVT::v16i1, Custom);
1393 setOperationAction(ISD::TRUNCATE, MVT::v16i16, Custom);
1394 setOperationAction(ISD::ZERO_EXTEND, MVT::v16i32, Custom);
1395 setOperationAction(ISD::ZERO_EXTEND, MVT::v8i64, Custom);
1396 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i32, Custom);
1397 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i64, Custom);
1398 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i8, Custom);
1399 setOperationAction(ISD::SIGN_EXTEND, MVT::v8i16, Custom);
1400 setOperationAction(ISD::SIGN_EXTEND, MVT::v16i16, Custom);
1402 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8f64, Custom);
1403 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i64, Custom);
1404 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16f32, Custom);
1405 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i32, Custom);
1406 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i1, Custom);
1407 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i1, Legal);
1409 setOperationAction(ISD::SETCC, MVT::v16i1, Custom);
1410 setOperationAction(ISD::SETCC, MVT::v8i1, Custom);
1412 setOperationAction(ISD::MUL, MVT::v8i64, Custom);
1414 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1, Custom);
1415 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1416 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i1, Custom);
1417 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i1, Custom);
1418 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i1, Custom);
1419 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i1, Custom);
1420 setOperationAction(ISD::SELECT, MVT::v8f64, Custom);
1421 setOperationAction(ISD::SELECT, MVT::v8i64, Custom);
1422 setOperationAction(ISD::SELECT, MVT::v16f32, Custom);
1424 setOperationAction(ISD::ADD, MVT::v8i64, Legal);
1425 setOperationAction(ISD::ADD, MVT::v16i32, Legal);
1427 setOperationAction(ISD::SUB, MVT::v8i64, Legal);
1428 setOperationAction(ISD::SUB, MVT::v16i32, Legal);
1430 setOperationAction(ISD::MUL, MVT::v16i32, Legal);
1432 setOperationAction(ISD::SRL, MVT::v8i64, Custom);
1433 setOperationAction(ISD::SRL, MVT::v16i32, Custom);
1435 setOperationAction(ISD::SHL, MVT::v8i64, Custom);
1436 setOperationAction(ISD::SHL, MVT::v16i32, Custom);
1438 setOperationAction(ISD::SRA, MVT::v8i64, Custom);
1439 setOperationAction(ISD::SRA, MVT::v16i32, Custom);
1441 setOperationAction(ISD::AND, MVT::v8i64, Legal);
1442 setOperationAction(ISD::OR, MVT::v8i64, Legal);
1443 setOperationAction(ISD::XOR, MVT::v8i64, Legal);
1444 setOperationAction(ISD::AND, MVT::v16i32, Legal);
1445 setOperationAction(ISD::OR, MVT::v16i32, Legal);
1446 setOperationAction(ISD::XOR, MVT::v16i32, Legal);
1448 if (Subtarget->hasCDI()) {
1449 setOperationAction(ISD::CTLZ, MVT::v8i64, Legal);
1450 setOperationAction(ISD::CTLZ, MVT::v16i32, Legal);
1453 // Custom lower several nodes.
1454 for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1455 i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1456 MVT VT = (MVT::SimpleValueType)i;
1458 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1459 // Extract subvector is special because the value type
1460 // (result) is 256/128-bit but the source is 512-bit wide.
1461 if (VT.is128BitVector() || VT.is256BitVector())
1462 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1464 if (VT.getVectorElementType() == MVT::i1)
1465 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1467 // Do not attempt to custom lower other non-512-bit vectors
1468 if (!VT.is512BitVector())
1471 if ( EltSize >= 32) {
1472 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
1473 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
1474 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
1475 setOperationAction(ISD::VSELECT, VT, Legal);
1476 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1477 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Custom);
1478 setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
1481 for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1482 MVT VT = (MVT::SimpleValueType)i;
1484 // Do not attempt to promote non-256-bit vectors
1485 if (!VT.is512BitVector())
1488 setOperationAction(ISD::SELECT, VT, Promote);
1489 AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1493 // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1494 // of this type with custom code.
1495 for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1496 VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1497 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1501 // We want to custom lower some of our intrinsics.
1502 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1503 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1504 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1505 if (!Subtarget->is64Bit())
1506 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1508 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1509 // handle type legalization for these operations here.
1511 // FIXME: We really should do custom legalization for addition and
1512 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
1513 // than generic legalization for 64-bit multiplication-with-overflow, though.
1514 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1515 // Add/Sub/Mul with overflow operations are custom lowered.
1517 setOperationAction(ISD::SADDO, VT, Custom);
1518 setOperationAction(ISD::UADDO, VT, Custom);
1519 setOperationAction(ISD::SSUBO, VT, Custom);
1520 setOperationAction(ISD::USUBO, VT, Custom);
1521 setOperationAction(ISD::SMULO, VT, Custom);
1522 setOperationAction(ISD::UMULO, VT, Custom);
1525 // There are no 8-bit 3-address imul/mul instructions
1526 setOperationAction(ISD::SMULO, MVT::i8, Expand);
1527 setOperationAction(ISD::UMULO, MVT::i8, Expand);
1529 if (!Subtarget->is64Bit()) {
1530 // These libcalls are not available in 32-bit.
1531 setLibcallName(RTLIB::SHL_I128, nullptr);
1532 setLibcallName(RTLIB::SRL_I128, nullptr);
1533 setLibcallName(RTLIB::SRA_I128, nullptr);
1536 // Combine sin / cos into one node or libcall if possible.
1537 if (Subtarget->hasSinCos()) {
1538 setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1539 setLibcallName(RTLIB::SINCOS_F64, "sincos");
1540 if (Subtarget->isTargetDarwin()) {
1541 // For MacOSX, we don't want to the normal expansion of a libcall to
1542 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1544 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1545 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1549 if (Subtarget->isTargetWin64()) {
1550 setOperationAction(ISD::SDIV, MVT::i128, Custom);
1551 setOperationAction(ISD::UDIV, MVT::i128, Custom);
1552 setOperationAction(ISD::SREM, MVT::i128, Custom);
1553 setOperationAction(ISD::UREM, MVT::i128, Custom);
1554 setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1555 setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1558 // We have target-specific dag combine patterns for the following nodes:
1559 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1560 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1561 setTargetDAGCombine(ISD::VSELECT);
1562 setTargetDAGCombine(ISD::SELECT);
1563 setTargetDAGCombine(ISD::SHL);
1564 setTargetDAGCombine(ISD::SRA);
1565 setTargetDAGCombine(ISD::SRL);
1566 setTargetDAGCombine(ISD::OR);
1567 setTargetDAGCombine(ISD::AND);
1568 setTargetDAGCombine(ISD::ADD);
1569 setTargetDAGCombine(ISD::FADD);
1570 setTargetDAGCombine(ISD::FSUB);
1571 setTargetDAGCombine(ISD::FMA);
1572 setTargetDAGCombine(ISD::SUB);
1573 setTargetDAGCombine(ISD::LOAD);
1574 setTargetDAGCombine(ISD::STORE);
1575 setTargetDAGCombine(ISD::ZERO_EXTEND);
1576 setTargetDAGCombine(ISD::ANY_EXTEND);
1577 setTargetDAGCombine(ISD::SIGN_EXTEND);
1578 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1579 setTargetDAGCombine(ISD::TRUNCATE);
1580 setTargetDAGCombine(ISD::SINT_TO_FP);
1581 setTargetDAGCombine(ISD::SETCC);
1582 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1583 setTargetDAGCombine(ISD::BUILD_VECTOR);
1584 if (Subtarget->is64Bit())
1585 setTargetDAGCombine(ISD::MUL);
1586 setTargetDAGCombine(ISD::XOR);
1588 computeRegisterProperties();
1590 // On Darwin, -Os means optimize for size without hurting performance,
1591 // do not reduce the limit.
1592 MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1593 MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1594 MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1595 MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1596 MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1597 MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1598 setPrefLoopAlignment(4); // 2^4 bytes.
1600 // Predictable cmov don't hurt on atom because it's in-order.
1601 PredictableSelectIsExpensive = !Subtarget->isAtom();
1603 setPrefFunctionAlignment(4); // 2^4 bytes.
1606 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1608 return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1610 if (Subtarget->hasAVX512())
1611 switch(VT.getVectorNumElements()) {
1612 case 8: return MVT::v8i1;
1613 case 16: return MVT::v16i1;
1616 return VT.changeVectorElementTypeToInteger();
1619 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1620 /// the desired ByVal argument alignment.
1621 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1624 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1625 if (VTy->getBitWidth() == 128)
1627 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1628 unsigned EltAlign = 0;
1629 getMaxByValAlign(ATy->getElementType(), EltAlign);
1630 if (EltAlign > MaxAlign)
1631 MaxAlign = EltAlign;
1632 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1633 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1634 unsigned EltAlign = 0;
1635 getMaxByValAlign(STy->getElementType(i), EltAlign);
1636 if (EltAlign > MaxAlign)
1637 MaxAlign = EltAlign;
1644 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1645 /// function arguments in the caller parameter area. For X86, aggregates
1646 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1647 /// are at 4-byte boundaries.
1648 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1649 if (Subtarget->is64Bit()) {
1650 // Max of 8 and alignment of type.
1651 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1658 if (Subtarget->hasSSE1())
1659 getMaxByValAlign(Ty, Align);
1663 /// getOptimalMemOpType - Returns the target specific optimal type for load
1664 /// and store operations as a result of memset, memcpy, and memmove
1665 /// lowering. If DstAlign is zero that means it's safe to destination
1666 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1667 /// means there isn't a need to check it against alignment requirement,
1668 /// probably because the source does not need to be loaded. If 'IsMemset' is
1669 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1670 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1671 /// source is constant so it does not need to be loaded.
1672 /// It returns EVT::Other if the type should be determined using generic
1673 /// target-independent logic.
1675 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1676 unsigned DstAlign, unsigned SrcAlign,
1677 bool IsMemset, bool ZeroMemset,
1679 MachineFunction &MF) const {
1680 const Function *F = MF.getFunction();
1681 if ((!IsMemset || ZeroMemset) &&
1682 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1683 Attribute::NoImplicitFloat)) {
1685 (Subtarget->isUnalignedMemAccessFast() ||
1686 ((DstAlign == 0 || DstAlign >= 16) &&
1687 (SrcAlign == 0 || SrcAlign >= 16)))) {
1689 if (Subtarget->hasInt256())
1691 if (Subtarget->hasFp256())
1694 if (Subtarget->hasSSE2())
1696 if (Subtarget->hasSSE1())
1698 } else if (!MemcpyStrSrc && Size >= 8 &&
1699 !Subtarget->is64Bit() &&
1700 Subtarget->hasSSE2()) {
1701 // Do not use f64 to lower memcpy if source is string constant. It's
1702 // better to use i32 to avoid the loads.
1706 if (Subtarget->is64Bit() && Size >= 8)
1711 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1713 return X86ScalarSSEf32;
1714 else if (VT == MVT::f64)
1715 return X86ScalarSSEf64;
1720 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1724 *Fast = Subtarget->isUnalignedMemAccessFast();
1728 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1729 /// current function. The returned value is a member of the
1730 /// MachineJumpTableInfo::JTEntryKind enum.
1731 unsigned X86TargetLowering::getJumpTableEncoding() const {
1732 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1734 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1735 Subtarget->isPICStyleGOT())
1736 return MachineJumpTableInfo::EK_Custom32;
1738 // Otherwise, use the normal jump table encoding heuristics.
1739 return TargetLowering::getJumpTableEncoding();
1743 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1744 const MachineBasicBlock *MBB,
1745 unsigned uid,MCContext &Ctx) const{
1746 assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1747 Subtarget->isPICStyleGOT());
1748 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1750 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1751 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1754 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1756 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1757 SelectionDAG &DAG) const {
1758 if (!Subtarget->is64Bit())
1759 // This doesn't have SDLoc associated with it, but is not really the
1760 // same as a Register.
1761 return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1765 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1766 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1768 const MCExpr *X86TargetLowering::
1769 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1770 MCContext &Ctx) const {
1771 // X86-64 uses RIP relative addressing based on the jump table label.
1772 if (Subtarget->isPICStyleRIPRel())
1773 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1775 // Otherwise, the reference is relative to the PIC base.
1776 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1779 // FIXME: Why this routine is here? Move to RegInfo!
1780 std::pair<const TargetRegisterClass*, uint8_t>
1781 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1782 const TargetRegisterClass *RRC = nullptr;
1784 switch (VT.SimpleTy) {
1786 return TargetLowering::findRepresentativeClass(VT);
1787 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1788 RRC = Subtarget->is64Bit() ?
1789 (const TargetRegisterClass*)&X86::GR64RegClass :
1790 (const TargetRegisterClass*)&X86::GR32RegClass;
1793 RRC = &X86::VR64RegClass;
1795 case MVT::f32: case MVT::f64:
1796 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1797 case MVT::v4f32: case MVT::v2f64:
1798 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1800 RRC = &X86::VR128RegClass;
1803 return std::make_pair(RRC, Cost);
1806 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1807 unsigned &Offset) const {
1808 if (!Subtarget->isTargetLinux())
1811 if (Subtarget->is64Bit()) {
1812 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1814 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1826 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1827 unsigned DestAS) const {
1828 assert(SrcAS != DestAS && "Expected different address spaces!");
1830 return SrcAS < 256 && DestAS < 256;
1833 //===----------------------------------------------------------------------===//
1834 // Return Value Calling Convention Implementation
1835 //===----------------------------------------------------------------------===//
1837 #include "X86GenCallingConv.inc"
1840 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1841 MachineFunction &MF, bool isVarArg,
1842 const SmallVectorImpl<ISD::OutputArg> &Outs,
1843 LLVMContext &Context) const {
1844 SmallVector<CCValAssign, 16> RVLocs;
1845 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1847 return CCInfo.CheckReturn(Outs, RetCC_X86);
1850 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1851 static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1856 X86TargetLowering::LowerReturn(SDValue Chain,
1857 CallingConv::ID CallConv, bool isVarArg,
1858 const SmallVectorImpl<ISD::OutputArg> &Outs,
1859 const SmallVectorImpl<SDValue> &OutVals,
1860 SDLoc dl, SelectionDAG &DAG) const {
1861 MachineFunction &MF = DAG.getMachineFunction();
1862 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1864 SmallVector<CCValAssign, 16> RVLocs;
1865 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1866 RVLocs, *DAG.getContext());
1867 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1870 SmallVector<SDValue, 6> RetOps;
1871 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1872 // Operand #1 = Bytes To Pop
1873 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1876 // Copy the result values into the output registers.
1877 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1878 CCValAssign &VA = RVLocs[i];
1879 assert(VA.isRegLoc() && "Can only return in registers!");
1880 SDValue ValToCopy = OutVals[i];
1881 EVT ValVT = ValToCopy.getValueType();
1883 // Promote values to the appropriate types
1884 if (VA.getLocInfo() == CCValAssign::SExt)
1885 ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1886 else if (VA.getLocInfo() == CCValAssign::ZExt)
1887 ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1888 else if (VA.getLocInfo() == CCValAssign::AExt)
1889 ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1890 else if (VA.getLocInfo() == CCValAssign::BCvt)
1891 ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1893 assert(VA.getLocInfo() != CCValAssign::FPExt &&
1894 "Unexpected FP-extend for return value.");
1896 // If this is x86-64, and we disabled SSE, we can't return FP values,
1897 // or SSE or MMX vectors.
1898 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1899 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1900 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1901 report_fatal_error("SSE register return with SSE disabled");
1903 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1904 // llvm-gcc has never done it right and no one has noticed, so this
1905 // should be OK for now.
1906 if (ValVT == MVT::f64 &&
1907 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1908 report_fatal_error("SSE2 register return with SSE2 disabled");
1910 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1911 // the RET instruction and handled by the FP Stackifier.
1912 if (VA.getLocReg() == X86::ST0 ||
1913 VA.getLocReg() == X86::ST1) {
1914 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1915 // change the value to the FP stack register class.
1916 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1917 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1918 RetOps.push_back(ValToCopy);
1919 // Don't emit a copytoreg.
1923 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1924 // which is returned in RAX / RDX.
1925 if (Subtarget->is64Bit()) {
1926 if (ValVT == MVT::x86mmx) {
1927 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1928 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1929 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1931 // If we don't have SSE2 available, convert to v4f32 so the generated
1932 // register is legal.
1933 if (!Subtarget->hasSSE2())
1934 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1939 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1940 Flag = Chain.getValue(1);
1941 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1944 // The x86-64 ABIs require that for returning structs by value we copy
1945 // the sret argument into %rax/%eax (depending on ABI) for the return.
1946 // Win32 requires us to put the sret argument to %eax as well.
1947 // We saved the argument into a virtual register in the entry block,
1948 // so now we copy the value out and into %rax/%eax.
1949 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1950 (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1951 MachineFunction &MF = DAG.getMachineFunction();
1952 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1953 unsigned Reg = FuncInfo->getSRetReturnReg();
1955 "SRetReturnReg should have been set in LowerFormalArguments().");
1956 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1959 = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1960 X86::RAX : X86::EAX;
1961 Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1962 Flag = Chain.getValue(1);
1964 // RAX/EAX now acts like a return value.
1965 RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1968 RetOps[0] = Chain; // Update chain.
1970 // Add the flag if we have it.
1972 RetOps.push_back(Flag);
1974 return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1977 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1978 if (N->getNumValues() != 1)
1980 if (!N->hasNUsesOfValue(1, 0))
1983 SDValue TCChain = Chain;
1984 SDNode *Copy = *N->use_begin();
1985 if (Copy->getOpcode() == ISD::CopyToReg) {
1986 // If the copy has a glue operand, we conservatively assume it isn't safe to
1987 // perform a tail call.
1988 if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1990 TCChain = Copy->getOperand(0);
1991 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1994 bool HasRet = false;
1995 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1997 if (UI->getOpcode() != X86ISD::RET_FLAG)
2010 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2011 ISD::NodeType ExtendKind) const {
2013 // TODO: Is this also valid on 32-bit?
2014 if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2015 ReturnMVT = MVT::i8;
2017 ReturnMVT = MVT::i32;
2019 MVT MinVT = getRegisterType(ReturnMVT);
2020 return VT.bitsLT(MinVT) ? MinVT : VT;
2023 /// LowerCallResult - Lower the result values of a call into the
2024 /// appropriate copies out of appropriate physical registers.
2027 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2028 CallingConv::ID CallConv, bool isVarArg,
2029 const SmallVectorImpl<ISD::InputArg> &Ins,
2030 SDLoc dl, SelectionDAG &DAG,
2031 SmallVectorImpl<SDValue> &InVals) const {
2033 // Assign locations to each value returned by this call.
2034 SmallVector<CCValAssign, 16> RVLocs;
2035 bool Is64Bit = Subtarget->is64Bit();
2036 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2037 DAG.getTarget(), RVLocs, *DAG.getContext());
2038 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2040 // Copy all of the result registers out of their specified physreg.
2041 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2042 CCValAssign &VA = RVLocs[i];
2043 EVT CopyVT = VA.getValVT();
2045 // If this is x86-64, and we disabled SSE, we can't return FP values
2046 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2047 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2048 report_fatal_error("SSE register return with SSE disabled");
2053 // If this is a call to a function that returns an fp value on the floating
2054 // point stack, we must guarantee the value is popped from the stack, so
2055 // a CopyFromReg is not good enough - the copy instruction may be eliminated
2056 // if the return value is not used. We use the FpPOP_RETVAL instruction
2058 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2059 // If we prefer to use the value in xmm registers, copy it out as f80 and
2060 // use a truncate to move it from fp stack reg to xmm reg.
2061 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2062 SDValue Ops[] = { Chain, InFlag };
2063 Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2064 MVT::Other, MVT::Glue, Ops), 1);
2065 Val = Chain.getValue(0);
2067 // Round the f80 to the right size, which also moves it to the appropriate
2069 if (CopyVT != VA.getValVT())
2070 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2071 // This truncation won't change the value.
2072 DAG.getIntPtrConstant(1));
2074 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2075 CopyVT, InFlag).getValue(1);
2076 Val = Chain.getValue(0);
2078 InFlag = Chain.getValue(2);
2079 InVals.push_back(Val);
2085 //===----------------------------------------------------------------------===//
2086 // C & StdCall & Fast Calling Convention implementation
2087 //===----------------------------------------------------------------------===//
2088 // StdCall calling convention seems to be standard for many Windows' API
2089 // routines and around. It differs from C calling convention just a little:
2090 // callee should clean up the stack, not caller. Symbols should be also
2091 // decorated in some fancy way :) It doesn't support any vector arguments.
2092 // For info on fast calling convention see Fast Calling Convention (tail call)
2093 // implementation LowerX86_32FastCCCallTo.
2095 /// CallIsStructReturn - Determines whether a call uses struct return
2097 enum StructReturnType {
2102 static StructReturnType
2103 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2105 return NotStructReturn;
2107 const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2108 if (!Flags.isSRet())
2109 return NotStructReturn;
2110 if (Flags.isInReg())
2111 return RegStructReturn;
2112 return StackStructReturn;
2115 /// ArgsAreStructReturn - Determines whether a function uses struct
2116 /// return semantics.
2117 static StructReturnType
2118 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2120 return NotStructReturn;
2122 const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2123 if (!Flags.isSRet())
2124 return NotStructReturn;
2125 if (Flags.isInReg())
2126 return RegStructReturn;
2127 return StackStructReturn;
2130 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2131 /// by "Src" to address "Dst" with size and alignment information specified by
2132 /// the specific parameter attribute. The copy will be passed as a byval
2133 /// function parameter.
2135 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2136 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2138 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2140 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2141 /*isVolatile*/false, /*AlwaysInline=*/true,
2142 MachinePointerInfo(), MachinePointerInfo());
2145 /// IsTailCallConvention - Return true if the calling convention is one that
2146 /// supports tail call optimization.
2147 static bool IsTailCallConvention(CallingConv::ID CC) {
2148 return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2149 CC == CallingConv::HiPE);
2152 /// \brief Return true if the calling convention is a C calling convention.
2153 static bool IsCCallConvention(CallingConv::ID CC) {
2154 return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2155 CC == CallingConv::X86_64_SysV);
2158 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2159 if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2163 CallingConv::ID CalleeCC = CS.getCallingConv();
2164 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2170 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2171 /// a tailcall target by changing its ABI.
2172 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2173 bool GuaranteedTailCallOpt) {
2174 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2178 X86TargetLowering::LowerMemArgument(SDValue Chain,
2179 CallingConv::ID CallConv,
2180 const SmallVectorImpl<ISD::InputArg> &Ins,
2181 SDLoc dl, SelectionDAG &DAG,
2182 const CCValAssign &VA,
2183 MachineFrameInfo *MFI,
2185 // Create the nodes corresponding to a load from this parameter slot.
2186 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2187 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2188 CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2189 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2192 // If value is passed by pointer we have address passed instead of the value
2194 if (VA.getLocInfo() == CCValAssign::Indirect)
2195 ValVT = VA.getLocVT();
2197 ValVT = VA.getValVT();
2199 // FIXME: For now, all byval parameter objects are marked mutable. This can be
2200 // changed with more analysis.
2201 // In case of tail call optimization mark all arguments mutable. Since they
2202 // could be overwritten by lowering of arguments in case of a tail call.
2203 if (Flags.isByVal()) {
2204 unsigned Bytes = Flags.getByValSize();
2205 if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2206 int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2207 return DAG.getFrameIndex(FI, getPointerTy());
2209 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2210 VA.getLocMemOffset(), isImmutable);
2211 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2212 return DAG.getLoad(ValVT, dl, Chain, FIN,
2213 MachinePointerInfo::getFixedStack(FI),
2214 false, false, false, 0);
2219 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2220 CallingConv::ID CallConv,
2222 const SmallVectorImpl<ISD::InputArg> &Ins,
2225 SmallVectorImpl<SDValue> &InVals)
2227 MachineFunction &MF = DAG.getMachineFunction();
2228 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2230 const Function* Fn = MF.getFunction();
2231 if (Fn->hasExternalLinkage() &&
2232 Subtarget->isTargetCygMing() &&
2233 Fn->getName() == "main")
2234 FuncInfo->setForceFramePointer(true);
2236 MachineFrameInfo *MFI = MF.getFrameInfo();
2237 bool Is64Bit = Subtarget->is64Bit();
2238 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2240 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2241 "Var args not supported with calling convention fastcc, ghc or hipe");
2243 // Assign locations to all of the incoming arguments.
2244 SmallVector<CCValAssign, 16> ArgLocs;
2245 CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2246 ArgLocs, *DAG.getContext());
2248 // Allocate shadow area for Win64
2250 CCInfo.AllocateStack(32, 8);
2252 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2254 unsigned LastVal = ~0U;
2256 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2257 CCValAssign &VA = ArgLocs[i];
2258 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2260 assert(VA.getValNo() != LastVal &&
2261 "Don't support value assigned to multiple locs yet");
2263 LastVal = VA.getValNo();
2265 if (VA.isRegLoc()) {
2266 EVT RegVT = VA.getLocVT();
2267 const TargetRegisterClass *RC;
2268 if (RegVT == MVT::i32)
2269 RC = &X86::GR32RegClass;
2270 else if (Is64Bit && RegVT == MVT::i64)
2271 RC = &X86::GR64RegClass;
2272 else if (RegVT == MVT::f32)
2273 RC = &X86::FR32RegClass;
2274 else if (RegVT == MVT::f64)
2275 RC = &X86::FR64RegClass;
2276 else if (RegVT.is512BitVector())
2277 RC = &X86::VR512RegClass;
2278 else if (RegVT.is256BitVector())
2279 RC = &X86::VR256RegClass;
2280 else if (RegVT.is128BitVector())
2281 RC = &X86::VR128RegClass;
2282 else if (RegVT == MVT::x86mmx)
2283 RC = &X86::VR64RegClass;
2284 else if (RegVT == MVT::i1)
2285 RC = &X86::VK1RegClass;
2286 else if (RegVT == MVT::v8i1)
2287 RC = &X86::VK8RegClass;
2288 else if (RegVT == MVT::v16i1)
2289 RC = &X86::VK16RegClass;
2291 llvm_unreachable("Unknown argument type!");
2293 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2294 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2296 // If this is an 8 or 16-bit value, it is really passed promoted to 32
2297 // bits. Insert an assert[sz]ext to capture this, then truncate to the
2299 if (VA.getLocInfo() == CCValAssign::SExt)
2300 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2301 DAG.getValueType(VA.getValVT()));
2302 else if (VA.getLocInfo() == CCValAssign::ZExt)
2303 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2304 DAG.getValueType(VA.getValVT()));
2305 else if (VA.getLocInfo() == CCValAssign::BCvt)
2306 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2308 if (VA.isExtInLoc()) {
2309 // Handle MMX values passed in XMM regs.
2310 if (RegVT.isVector())
2311 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2313 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2316 assert(VA.isMemLoc());
2317 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2320 // If value is passed via pointer - do a load.
2321 if (VA.getLocInfo() == CCValAssign::Indirect)
2322 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2323 MachinePointerInfo(), false, false, false, 0);
2325 InVals.push_back(ArgValue);
2328 if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2329 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2330 // The x86-64 ABIs require that for returning structs by value we copy
2331 // the sret argument into %rax/%eax (depending on ABI) for the return.
2332 // Win32 requires us to put the sret argument to %eax as well.
2333 // Save the argument into a virtual register so that we can access it
2334 // from the return points.
2335 if (Ins[i].Flags.isSRet()) {
2336 unsigned Reg = FuncInfo->getSRetReturnReg();
2338 MVT PtrTy = getPointerTy();
2339 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2340 FuncInfo->setSRetReturnReg(Reg);
2342 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2343 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2349 unsigned StackSize = CCInfo.getNextStackOffset();
2350 // Align stack specially for tail calls.
2351 if (FuncIsMadeTailCallSafe(CallConv,
2352 MF.getTarget().Options.GuaranteedTailCallOpt))
2353 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2355 // If the function takes variable number of arguments, make a frame index for
2356 // the start of the first vararg value... for expansion of llvm.va_start.
2358 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2359 CallConv != CallingConv::X86_ThisCall)) {
2360 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2363 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2365 // FIXME: We should really autogenerate these arrays
2366 static const MCPhysReg GPR64ArgRegsWin64[] = {
2367 X86::RCX, X86::RDX, X86::R8, X86::R9
2369 static const MCPhysReg GPR64ArgRegs64Bit[] = {
2370 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2372 static const MCPhysReg XMMArgRegs64Bit[] = {
2373 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2374 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2376 const MCPhysReg *GPR64ArgRegs;
2377 unsigned NumXMMRegs = 0;
2380 // The XMM registers which might contain var arg parameters are shadowed
2381 // in their paired GPR. So we only need to save the GPR to their home
2383 TotalNumIntRegs = 4;
2384 GPR64ArgRegs = GPR64ArgRegsWin64;
2386 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2387 GPR64ArgRegs = GPR64ArgRegs64Bit;
2389 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2392 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2395 bool NoImplicitFloatOps = Fn->getAttributes().
2396 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2397 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2398 "SSE register cannot be used when SSE is disabled!");
2399 assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2400 NoImplicitFloatOps) &&
2401 "SSE register cannot be used when SSE is disabled!");
2402 if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2403 !Subtarget->hasSSE1())
2404 // Kernel mode asks for SSE to be disabled, so don't push them
2406 TotalNumXMMRegs = 0;
2409 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2410 // Get to the caller-allocated home save location. Add 8 to account
2411 // for the return address.
2412 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2413 FuncInfo->setRegSaveFrameIndex(
2414 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2415 // Fixup to set vararg frame on shadow area (4 x i64).
2417 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2419 // For X86-64, if there are vararg parameters that are passed via
2420 // registers, then we must store them to their spots on the stack so
2421 // they may be loaded by deferencing the result of va_next.
2422 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2423 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2424 FuncInfo->setRegSaveFrameIndex(
2425 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2429 // Store the integer parameter registers.
2430 SmallVector<SDValue, 8> MemOps;
2431 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2433 unsigned Offset = FuncInfo->getVarArgsGPOffset();
2434 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2435 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2436 DAG.getIntPtrConstant(Offset));
2437 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2438 &X86::GR64RegClass);
2439 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2441 DAG.getStore(Val.getValue(1), dl, Val, FIN,
2442 MachinePointerInfo::getFixedStack(
2443 FuncInfo->getRegSaveFrameIndex(), Offset),
2445 MemOps.push_back(Store);
2449 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2450 // Now store the XMM (fp + vector) parameter registers.
2451 SmallVector<SDValue, 11> SaveXMMOps;
2452 SaveXMMOps.push_back(Chain);
2454 unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2455 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2456 SaveXMMOps.push_back(ALVal);
2458 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2459 FuncInfo->getRegSaveFrameIndex()));
2460 SaveXMMOps.push_back(DAG.getIntPtrConstant(
2461 FuncInfo->getVarArgsFPOffset()));
2463 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2464 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2465 &X86::VR128RegClass);
2466 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2467 SaveXMMOps.push_back(Val);
2469 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2470 MVT::Other, SaveXMMOps));
2473 if (!MemOps.empty())
2474 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2478 // Some CCs need callee pop.
2479 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2480 MF.getTarget().Options.GuaranteedTailCallOpt)) {
2481 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2483 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2484 // If this is an sret function, the return should pop the hidden pointer.
2485 if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2486 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2487 argsAreStructReturn(Ins) == StackStructReturn)
2488 FuncInfo->setBytesToPopOnReturn(4);
2492 // RegSaveFrameIndex is X86-64 only.
2493 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2494 if (CallConv == CallingConv::X86_FastCall ||
2495 CallConv == CallingConv::X86_ThisCall)
2496 // fastcc functions can't have varargs.
2497 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2500 FuncInfo->setArgumentStackSize(StackSize);
2506 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2507 SDValue StackPtr, SDValue Arg,
2508 SDLoc dl, SelectionDAG &DAG,
2509 const CCValAssign &VA,
2510 ISD::ArgFlagsTy Flags) const {
2511 unsigned LocMemOffset = VA.getLocMemOffset();
2512 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2513 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2514 if (Flags.isByVal())
2515 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2517 return DAG.getStore(Chain, dl, Arg, PtrOff,
2518 MachinePointerInfo::getStack(LocMemOffset),
2522 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2523 /// optimization is performed and it is required.
2525 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2526 SDValue &OutRetAddr, SDValue Chain,
2527 bool IsTailCall, bool Is64Bit,
2528 int FPDiff, SDLoc dl) const {
2529 // Adjust the Return address stack slot.
2530 EVT VT = getPointerTy();
2531 OutRetAddr = getReturnAddressFrameIndex(DAG);
2533 // Load the "old" Return address.
2534 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2535 false, false, false, 0);
2536 return SDValue(OutRetAddr.getNode(), 1);
2539 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2540 /// optimization is performed and it is required (FPDiff!=0).
2541 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2542 SDValue Chain, SDValue RetAddrFrIdx,
2543 EVT PtrVT, unsigned SlotSize,
2544 int FPDiff, SDLoc dl) {
2545 // Store the return address to the appropriate stack slot.
2546 if (!FPDiff) return Chain;
2547 // Calculate the new stack slot for the return address.
2548 int NewReturnAddrFI =
2549 MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2551 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2552 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2553 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2559 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2560 SmallVectorImpl<SDValue> &InVals) const {
2561 SelectionDAG &DAG = CLI.DAG;
2563 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2564 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2565 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2566 SDValue Chain = CLI.Chain;
2567 SDValue Callee = CLI.Callee;
2568 CallingConv::ID CallConv = CLI.CallConv;
2569 bool &isTailCall = CLI.IsTailCall;
2570 bool isVarArg = CLI.IsVarArg;
2572 MachineFunction &MF = DAG.getMachineFunction();
2573 bool Is64Bit = Subtarget->is64Bit();
2574 bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2575 StructReturnType SR = callIsStructReturn(Outs);
2576 bool IsSibcall = false;
2578 if (MF.getTarget().Options.DisableTailCalls)
2581 bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2583 // Force this to be a tail call. The verifier rules are enough to ensure
2584 // that we can lower this successfully without moving the return address
2587 } else if (isTailCall) {
2588 // Check if it's really possible to do a tail call.
2589 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2590 isVarArg, SR != NotStructReturn,
2591 MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2592 Outs, OutVals, Ins, DAG);
2594 // Sibcalls are automatically detected tailcalls which do not require
2596 if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2603 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2604 "Var args not supported with calling convention fastcc, ghc or hipe");
2606 // Analyze operands of the call, assigning locations to each operand.
2607 SmallVector<CCValAssign, 16> ArgLocs;
2608 CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2609 ArgLocs, *DAG.getContext());
2611 // Allocate shadow area for Win64
2613 CCInfo.AllocateStack(32, 8);
2615 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2617 // Get a count of how many bytes are to be pushed on the stack.
2618 unsigned NumBytes = CCInfo.getNextStackOffset();
2620 // This is a sibcall. The memory operands are available in caller's
2621 // own caller's stack.
2623 else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2624 IsTailCallConvention(CallConv))
2625 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2628 if (isTailCall && !IsSibcall && !IsMustTail) {
2629 // Lower arguments at fp - stackoffset + fpdiff.
2630 X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2631 unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2633 FPDiff = NumBytesCallerPushed - NumBytes;
2635 // Set the delta of movement of the returnaddr stackslot.
2636 // But only set if delta is greater than previous delta.
2637 if (FPDiff < X86Info->getTCReturnAddrDelta())
2638 X86Info->setTCReturnAddrDelta(FPDiff);
2641 unsigned NumBytesToPush = NumBytes;
2642 unsigned NumBytesToPop = NumBytes;
2644 // If we have an inalloca argument, all stack space has already been allocated
2645 // for us and be right at the top of the stack. We don't support multiple
2646 // arguments passed in memory when using inalloca.
2647 if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2649 assert(ArgLocs.back().getLocMemOffset() == 0 &&
2650 "an inalloca argument must be the only memory argument");
2654 Chain = DAG.getCALLSEQ_START(
2655 Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2657 SDValue RetAddrFrIdx;
2658 // Load return address for tail calls.
2659 if (isTailCall && FPDiff)
2660 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2661 Is64Bit, FPDiff, dl);
2663 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2664 SmallVector<SDValue, 8> MemOpChains;
2667 // Walk the register/memloc assignments, inserting copies/loads. In the case
2668 // of tail call optimization arguments are handle later.
2669 const X86RegisterInfo *RegInfo =
2670 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2671 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2672 // Skip inalloca arguments, they have already been written.
2673 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2674 if (Flags.isInAlloca())
2677 CCValAssign &VA = ArgLocs[i];
2678 EVT RegVT = VA.getLocVT();
2679 SDValue Arg = OutVals[i];
2680 bool isByVal = Flags.isByVal();
2682 // Promote the value if needed.
2683 switch (VA.getLocInfo()) {
2684 default: llvm_unreachable("Unknown loc info!");
2685 case CCValAssign::Full: break;
2686 case CCValAssign::SExt:
2687 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2689 case CCValAssign::ZExt:
2690 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2692 case CCValAssign::AExt:
2693 if (RegVT.is128BitVector()) {
2694 // Special case: passing MMX values in XMM registers.
2695 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2696 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2697 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2699 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2701 case CCValAssign::BCvt:
2702 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2704 case CCValAssign::Indirect: {
2705 // Store the argument.
2706 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2707 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2708 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2709 MachinePointerInfo::getFixedStack(FI),
2716 if (VA.isRegLoc()) {
2717 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2718 if (isVarArg && IsWin64) {
2719 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2720 // shadow reg if callee is a varargs function.
2721 unsigned ShadowReg = 0;
2722 switch (VA.getLocReg()) {
2723 case X86::XMM0: ShadowReg = X86::RCX; break;
2724 case X86::XMM1: ShadowReg = X86::RDX; break;
2725 case X86::XMM2: ShadowReg = X86::R8; break;
2726 case X86::XMM3: ShadowReg = X86::R9; break;
2729 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2731 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2732 assert(VA.isMemLoc());
2733 if (!StackPtr.getNode())
2734 StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2736 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2737 dl, DAG, VA, Flags));
2741 if (!MemOpChains.empty())
2742 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2744 if (Subtarget->isPICStyleGOT()) {
2745 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2748 RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2749 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2751 // If we are tail calling and generating PIC/GOT style code load the
2752 // address of the callee into ECX. The value in ecx is used as target of
2753 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2754 // for tail calls on PIC/GOT architectures. Normally we would just put the
2755 // address of GOT into ebx and then call target@PLT. But for tail calls
2756 // ebx would be restored (since ebx is callee saved) before jumping to the
2759 // Note: The actual moving to ECX is done further down.
2760 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2761 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2762 !G->getGlobal()->hasProtectedVisibility())
2763 Callee = LowerGlobalAddress(Callee, DAG);
2764 else if (isa<ExternalSymbolSDNode>(Callee))
2765 Callee = LowerExternalSymbol(Callee, DAG);
2769 if (Is64Bit && isVarArg && !IsWin64) {
2770 // From AMD64 ABI document:
2771 // For calls that may call functions that use varargs or stdargs
2772 // (prototype-less calls or calls to functions containing ellipsis (...) in
2773 // the declaration) %al is used as hidden argument to specify the number
2774 // of SSE registers used. The contents of %al do not need to match exactly
2775 // the number of registers, but must be an ubound on the number of SSE
2776 // registers used and is in the range 0 - 8 inclusive.
2778 // Count the number of XMM registers allocated.
2779 static const MCPhysReg XMMArgRegs[] = {
2780 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2781 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2783 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2784 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2785 && "SSE registers cannot be used when SSE is disabled");
2787 RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2788 DAG.getConstant(NumXMMRegs, MVT::i8)));
2791 // For tail calls lower the arguments to the 'real' stack slots. Sibcalls
2792 // don't need this because the eligibility check rejects calls that require
2793 // shuffling arguments passed in memory.
2794 if (!IsSibcall && isTailCall) {
2795 // Force all the incoming stack arguments to be loaded from the stack
2796 // before any new outgoing arguments are stored to the stack, because the
2797 // outgoing stack slots may alias the incoming argument stack slots, and
2798 // the alias isn't otherwise explicit. This is slightly more conservative
2799 // than necessary, because it means that each store effectively depends
2800 // on every argument instead of just those arguments it would clobber.
2801 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2803 SmallVector<SDValue, 8> MemOpChains2;
2806 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2807 CCValAssign &VA = ArgLocs[i];
2810 assert(VA.isMemLoc());
2811 SDValue Arg = OutVals[i];
2812 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2813 // Skip inalloca arguments. They don't require any work.
2814 if (Flags.isInAlloca())
2816 // Create frame index.
2817 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2818 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2819 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2820 FIN = DAG.getFrameIndex(FI, getPointerTy());
2822 if (Flags.isByVal()) {
2823 // Copy relative to framepointer.
2824 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2825 if (!StackPtr.getNode())
2826 StackPtr = DAG.getCopyFromReg(Chain, dl,
2827 RegInfo->getStackRegister(),
2829 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2831 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2835 // Store relative to framepointer.
2836 MemOpChains2.push_back(
2837 DAG.getStore(ArgChain, dl, Arg, FIN,
2838 MachinePointerInfo::getFixedStack(FI),
2843 if (!MemOpChains2.empty())
2844 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2846 // Store the return address to the appropriate stack slot.
2847 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2848 getPointerTy(), RegInfo->getSlotSize(),
2852 // Build a sequence of copy-to-reg nodes chained together with token chain
2853 // and flag operands which copy the outgoing args into registers.
2855 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2856 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2857 RegsToPass[i].second, InFlag);
2858 InFlag = Chain.getValue(1);
2861 if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2862 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2863 // In the 64-bit large code model, we have to make all calls
2864 // through a register, since the call instruction's 32-bit
2865 // pc-relative offset may not be large enough to hold the whole
2867 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2868 // If the callee is a GlobalAddress node (quite common, every direct call
2869 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2872 // We should use extra load for direct calls to dllimported functions in
2874 const GlobalValue *GV = G->getGlobal();
2875 if (!GV->hasDLLImportStorageClass()) {
2876 unsigned char OpFlags = 0;
2877 bool ExtraLoad = false;
2878 unsigned WrapperKind = ISD::DELETED_NODE;
2880 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2881 // external symbols most go through the PLT in PIC mode. If the symbol
2882 // has hidden or protected visibility, or if it is static or local, then
2883 // we don't need to use the PLT - we can directly call it.
2884 if (Subtarget->isTargetELF() &&
2885 DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2886 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2887 OpFlags = X86II::MO_PLT;
2888 } else if (Subtarget->isPICStyleStubAny() &&
2889 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2890 (!Subtarget->getTargetTriple().isMacOSX() ||
2891 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2892 // PC-relative references to external symbols should go through $stub,
2893 // unless we're building with the leopard linker or later, which
2894 // automatically synthesizes these stubs.
2895 OpFlags = X86II::MO_DARWIN_STUB;
2896 } else if (Subtarget->isPICStyleRIPRel() &&
2897 isa<Function>(GV) &&
2898 cast<Function>(GV)->getAttributes().
2899 hasAttribute(AttributeSet::FunctionIndex,
2900 Attribute::NonLazyBind)) {
2901 // If the function is marked as non-lazy, generate an indirect call
2902 // which loads from the GOT directly. This avoids runtime overhead
2903 // at the cost of eager binding (and one extra byte of encoding).
2904 OpFlags = X86II::MO_GOTPCREL;
2905 WrapperKind = X86ISD::WrapperRIP;
2909 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2910 G->getOffset(), OpFlags);
2912 // Add a wrapper if needed.
2913 if (WrapperKind != ISD::DELETED_NODE)
2914 Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2915 // Add extra indirection if needed.
2917 Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2918 MachinePointerInfo::getGOT(),
2919 false, false, false, 0);
2921 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2922 unsigned char OpFlags = 0;
2924 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2925 // external symbols should go through the PLT.
2926 if (Subtarget->isTargetELF() &&
2927 DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2928 OpFlags = X86II::MO_PLT;
2929 } else if (Subtarget->isPICStyleStubAny() &&
2930 (!Subtarget->getTargetTriple().isMacOSX() ||
2931 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2932 // PC-relative references to external symbols should go through $stub,
2933 // unless we're building with the leopard linker or later, which
2934 // automatically synthesizes these stubs.
2935 OpFlags = X86II::MO_DARWIN_STUB;
2938 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2942 // Returns a chain & a flag for retval copy to use.
2943 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2944 SmallVector<SDValue, 8> Ops;
2946 if (!IsSibcall && isTailCall) {
2947 Chain = DAG.getCALLSEQ_END(Chain,
2948 DAG.getIntPtrConstant(NumBytesToPop, true),
2949 DAG.getIntPtrConstant(0, true), InFlag, dl);
2950 InFlag = Chain.getValue(1);
2953 Ops.push_back(Chain);
2954 Ops.push_back(Callee);
2957 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2959 // Add argument registers to the end of the list so that they are known live
2961 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2962 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2963 RegsToPass[i].second.getValueType()));
2965 // Add a register mask operand representing the call-preserved registers.
2966 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2967 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2968 assert(Mask && "Missing call preserved mask for calling convention");
2969 Ops.push_back(DAG.getRegisterMask(Mask));
2971 if (InFlag.getNode())
2972 Ops.push_back(InFlag);
2976 //// If this is the first return lowered for this function, add the regs
2977 //// to the liveout set for the function.
2978 // This isn't right, although it's probably harmless on x86; liveouts
2979 // should be computed from returns not tail calls. Consider a void
2980 // function making a tail call to a function returning int.
2981 return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2984 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2985 InFlag = Chain.getValue(1);
2987 // Create the CALLSEQ_END node.
2988 unsigned NumBytesForCalleeToPop;
2989 if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2990 DAG.getTarget().Options.GuaranteedTailCallOpt))
2991 NumBytesForCalleeToPop = NumBytes; // Callee pops everything
2992 else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2993 !Subtarget->getTargetTriple().isOSMSVCRT() &&
2994 SR == StackStructReturn)
2995 // If this is a call to a struct-return function, the callee
2996 // pops the hidden struct pointer, so we have to push it back.
2997 // This is common for Darwin/X86, Linux & Mingw32 targets.
2998 // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2999 NumBytesForCalleeToPop = 4;
3001 NumBytesForCalleeToPop = 0; // Callee pops nothing.
3003 // Returns a flag for retval copy to use.
3005 Chain = DAG.getCALLSEQ_END(Chain,
3006 DAG.getIntPtrConstant(NumBytesToPop, true),
3007 DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3010 InFlag = Chain.getValue(1);
3013 // Handle result values, copying them out of physregs into vregs that we
3015 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3016 Ins, dl, DAG, InVals);
3019 //===----------------------------------------------------------------------===//
3020 // Fast Calling Convention (tail call) implementation
3021 //===----------------------------------------------------------------------===//
3023 // Like std call, callee cleans arguments, convention except that ECX is
3024 // reserved for storing the tail called function address. Only 2 registers are
3025 // free for argument passing (inreg). Tail call optimization is performed
3027 // * tailcallopt is enabled
3028 // * caller/callee are fastcc
3029 // On X86_64 architecture with GOT-style position independent code only local
3030 // (within module) calls are supported at the moment.
3031 // To keep the stack aligned according to platform abi the function
3032 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
3033 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3034 // If a tail called function callee has more arguments than the caller the
3035 // caller needs to make sure that there is room to move the RETADDR to. This is
3036 // achieved by reserving an area the size of the argument delta right after the
3037 // original REtADDR, but before the saved framepointer or the spilled registers
3038 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3050 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3051 /// for a 16 byte align requirement.
3053 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3054 SelectionDAG& DAG) const {
3055 MachineFunction &MF = DAG.getMachineFunction();
3056 const TargetMachine &TM = MF.getTarget();
3057 const X86RegisterInfo *RegInfo =
3058 static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3059 const TargetFrameLowering &TFI = *TM.getFrameLowering();
3060 unsigned StackAlignment = TFI.getStackAlignment();
3061 uint64_t AlignMask = StackAlignment - 1;
3062 int64_t Offset = StackSize;
3063 unsigned SlotSize = RegInfo->getSlotSize();
3064 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3065 // Number smaller than 12 so just add the difference.
3066 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3068 // Mask out lower bits, add stackalignment once plus the 12 bytes.
3069 Offset = ((~AlignMask) & Offset) + StackAlignment +
3070 (StackAlignment-SlotSize);
3075 /// MatchingStackOffset - Return true if the given stack call argument is
3076 /// already available in the same position (relatively) of the caller's
3077 /// incoming argument stack.
3079 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3080 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3081 const X86InstrInfo *TII) {
3082 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3084 if (Arg.getOpcode() == ISD::CopyFromReg) {
3085 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3086 if (!TargetRegisterInfo::isVirtualRegister(VR))
3088 MachineInstr *Def = MRI->getVRegDef(VR);
3091 if (!Flags.isByVal()) {
3092 if (!TII->isLoadFromStackSlot(Def, FI))
3095 unsigned Opcode = Def->getOpcode();
3096 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3097 Def->getOperand(1).isFI()) {
3098 FI = Def->getOperand(1).getIndex();
3099 Bytes = Flags.getByValSize();
3103 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3104 if (Flags.isByVal())
3105 // ByVal argument is passed in as a pointer but it's now being
3106 // dereferenced. e.g.
3107 // define @foo(%struct.X* %A) {
3108 // tail call @bar(%struct.X* byval %A)
3111 SDValue Ptr = Ld->getBasePtr();
3112 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3115 FI = FINode->getIndex();
3116 } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3117 FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3118 FI = FINode->getIndex();
3119 Bytes = Flags.getByValSize();
3123 assert(FI != INT_MAX);
3124 if (!MFI->isFixedObjectIndex(FI))
3126 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3129 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3130 /// for tail call optimization. Targets which want to do tail call
3131 /// optimization should implement this function.
3133 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3134 CallingConv::ID CalleeCC,
3136 bool isCalleeStructRet,
3137 bool isCallerStructRet,
3139 const SmallVectorImpl<ISD::OutputArg> &Outs,
3140 const SmallVectorImpl<SDValue> &OutVals,
3141 const SmallVectorImpl<ISD::InputArg> &Ins,
3142 SelectionDAG &DAG) const {
3143 if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3146 // If -tailcallopt is specified, make fastcc functions tail-callable.
3147 const MachineFunction &MF = DAG.getMachineFunction();
3148 const Function *CallerF = MF.getFunction();
3150 // If the function return type is x86_fp80 and the callee return type is not,
3151 // then the FP_EXTEND of the call result is not a nop. It's not safe to
3152 // perform a tailcall optimization here.
3153 if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3156 CallingConv::ID CallerCC = CallerF->getCallingConv();
3157 bool CCMatch = CallerCC == CalleeCC;
3158 bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3159 bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3161 if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3162 if (IsTailCallConvention(CalleeCC) && CCMatch)
3167 // Look for obvious safe cases to perform tail call optimization that do not
3168 // require ABI changes. This is what gcc calls sibcall.
3170 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3171 // emit a special epilogue.
3172 const X86RegisterInfo *RegInfo =
3173 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3174 if (RegInfo->needsStackRealignment(MF))
3177 // Also avoid sibcall optimization if either caller or callee uses struct
3178 // return semantics.
3179 if (isCalleeStructRet || isCallerStructRet)
3182 // An stdcall/thiscall caller is expected to clean up its arguments; the
3183 // callee isn't going to do that.
3184 // FIXME: this is more restrictive than needed. We could produce a tailcall
3185 // when the stack adjustment matches. For example, with a thiscall that takes
3186 // only one argument.
3187 if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3188 CallerCC == CallingConv::X86_ThisCall))
3191 // Do not sibcall optimize vararg calls unless all arguments are passed via
3193 if (isVarArg && !Outs.empty()) {
3195 // Optimizing for varargs on Win64 is unlikely to be safe without
3196 // additional testing.
3197 if (IsCalleeWin64 || IsCallerWin64)
3200 SmallVector<CCValAssign, 16> ArgLocs;
3201 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3202 DAG.getTarget(), ArgLocs, *DAG.getContext());
3204 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3205 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3206 if (!ArgLocs[i].isRegLoc())
3210 // If the call result is in ST0 / ST1, it needs to be popped off the x87
3211 // stack. Therefore, if it's not used by the call it is not safe to optimize
3212 // this into a sibcall.
3213 bool Unused = false;
3214 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3221 SmallVector<CCValAssign, 16> RVLocs;
3222 CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3223 DAG.getTarget(), RVLocs, *DAG.getContext());
3224 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3225 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3226 CCValAssign &VA = RVLocs[i];
3227 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3232 // If the calling conventions do not match, then we'd better make sure the
3233 // results are returned in the same way as what the caller expects.
3235 SmallVector<CCValAssign, 16> RVLocs1;
3236 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3237 DAG.getTarget(), RVLocs1, *DAG.getContext());
3238 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3240 SmallVector<CCValAssign, 16> RVLocs2;
3241 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3242 DAG.getTarget(), RVLocs2, *DAG.getContext());
3243 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3245 if (RVLocs1.size() != RVLocs2.size())
3247 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3248 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3250 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3252 if (RVLocs1[i].isRegLoc()) {
3253 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3256 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3262 // If the callee takes no arguments then go on to check the results of the
3264 if (!Outs.empty()) {
3265 // Check if stack adjustment is needed. For now, do not do this if any
3266 // argument is passed on the stack.
3267 SmallVector<CCValAssign, 16> ArgLocs;
3268 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3269 DAG.getTarget(), ArgLocs, *DAG.getContext());
3271 // Allocate shadow area for Win64
3273 CCInfo.AllocateStack(32, 8);
3275 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3276 if (CCInfo.getNextStackOffset()) {
3277 MachineFunction &MF = DAG.getMachineFunction();
3278 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3281 // Check if the arguments are already laid out in the right way as
3282 // the caller's fixed stack objects.
3283 MachineFrameInfo *MFI = MF.getFrameInfo();
3284 const MachineRegisterInfo *MRI = &MF.getRegInfo();
3285 const X86InstrInfo *TII =
3286 static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3287 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3288 CCValAssign &VA = ArgLocs[i];
3289 SDValue Arg = OutVals[i];
3290 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3291 if (VA.getLocInfo() == CCValAssign::Indirect)
3293 if (!VA.isRegLoc()) {
3294 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3301 // If the tailcall address may be in a register, then make sure it's
3302 // possible to register allocate for it. In 32-bit, the call address can
3303 // only target EAX, EDX, or ECX since the tail call must be scheduled after
3304 // callee-saved registers are restored. These happen to be the same
3305 // registers used to pass 'inreg' arguments so watch out for those.
3306 if (!Subtarget->is64Bit() &&
3307 ((!isa<GlobalAddressSDNode>(Callee) &&
3308 !isa<ExternalSymbolSDNode>(Callee)) ||
3309 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3310 unsigned NumInRegs = 0;
3311 // In PIC we need an extra register to formulate the address computation
3313 unsigned MaxInRegs =
3314 (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3316 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3317 CCValAssign &VA = ArgLocs[i];
3320 unsigned Reg = VA.getLocReg();
3323 case X86::EAX: case X86::EDX: case X86::ECX:
3324 if (++NumInRegs == MaxInRegs)
3336 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3337 const TargetLibraryInfo *libInfo) const {
3338 return X86::createFastISel(funcInfo, libInfo);
3341 //===----------------------------------------------------------------------===//
3342 // Other Lowering Hooks
3343 //===----------------------------------------------------------------------===//
3345 static bool MayFoldLoad(SDValue Op) {
3346 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3349 static bool MayFoldIntoStore(SDValue Op) {
3350 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3353 static bool isTargetShuffle(unsigned Opcode) {
3355 default: return false;
3356 case X86ISD::PSHUFD:
3357 case X86ISD::PSHUFHW:
3358 case X86ISD::PSHUFLW:
3360 case X86ISD::PALIGNR:
3361 case X86ISD::MOVLHPS:
3362 case X86ISD::MOVLHPD:
3363 case X86ISD::MOVHLPS:
3364 case X86ISD::MOVLPS:
3365 case X86ISD::MOVLPD:
3366 case X86ISD::MOVSHDUP:
3367 case X86ISD::MOVSLDUP:
3368 case X86ISD::MOVDDUP:
3371 case X86ISD::UNPCKL:
3372 case X86ISD::UNPCKH:
3373 case X86ISD::VPERMILP:
3374 case X86ISD::VPERM2X128:
3375 case X86ISD::VPERMI:
3380 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3381 SDValue V1, SelectionDAG &DAG) {
3383 default: llvm_unreachable("Unknown x86 shuffle node");
3384 case X86ISD::MOVSHDUP:
3385 case X86ISD::MOVSLDUP:
3386 case X86ISD::MOVDDUP:
3387 return DAG.getNode(Opc, dl, VT, V1);
3391 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3392 SDValue V1, unsigned TargetMask,
3393 SelectionDAG &DAG) {
3395 default: llvm_unreachable("Unknown x86 shuffle node");
3396 case X86ISD::PSHUFD:
3397 case X86ISD::PSHUFHW:
3398 case X86ISD::PSHUFLW:
3399 case X86ISD::VPERMILP:
3400 case X86ISD::VPERMI:
3401 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3405 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3406 SDValue V1, SDValue V2, unsigned TargetMask,
3407 SelectionDAG &DAG) {
3409 default: llvm_unreachable("Unknown x86 shuffle node");
3410 case X86ISD::PALIGNR:
3412 case X86ISD::VPERM2X128:
3413 return DAG.getNode(Opc, dl, VT, V1, V2,
3414 DAG.getConstant(TargetMask, MVT::i8));
3418 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3419 SDValue V1, SDValue V2, SelectionDAG &DAG) {
3421 default: llvm_unreachable("Unknown x86 shuffle node");
3422 case X86ISD::MOVLHPS:
3423 case X86ISD::MOVLHPD:
3424 case X86ISD::MOVHLPS:
3425 case X86ISD::MOVLPS:
3426 case X86ISD::MOVLPD:
3429 case X86ISD::UNPCKL:
3430 case X86ISD::UNPCKH:
3431 return DAG.getNode(Opc, dl, VT, V1, V2);
3435 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3436 MachineFunction &MF = DAG.getMachineFunction();
3437 const X86RegisterInfo *RegInfo =
3438 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3439 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3440 int ReturnAddrIndex = FuncInfo->getRAIndex();
3442 if (ReturnAddrIndex == 0) {
3443 // Set up a frame object for the return address.
3444 unsigned SlotSize = RegInfo->getSlotSize();
3445 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3448 FuncInfo->setRAIndex(ReturnAddrIndex);
3451 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3454 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3455 bool hasSymbolicDisplacement) {
3456 // Offset should fit into 32 bit immediate field.
3457 if (!isInt<32>(Offset))
3460 // If we don't have a symbolic displacement - we don't have any extra
3462 if (!hasSymbolicDisplacement)
3465 // FIXME: Some tweaks might be needed for medium code model.
3466 if (M != CodeModel::Small && M != CodeModel::Kernel)
3469 // For small code model we assume that latest object is 16MB before end of 31
3470 // bits boundary. We may also accept pretty large negative constants knowing
3471 // that all objects are in the positive half of address space.
3472 if (M == CodeModel::Small && Offset < 16*1024*1024)
3475 // For kernel code model we know that all object resist in the negative half
3476 // of 32bits address space. We may not accept negative offsets, since they may
3477 // be just off and we may accept pretty large positive ones.
3478 if (M == CodeModel::Kernel && Offset > 0)
3484 /// isCalleePop - Determines whether the callee is required to pop its
3485 /// own arguments. Callee pop is necessary to support tail calls.
3486 bool X86::isCalleePop(CallingConv::ID CallingConv,
3487 bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3491 switch (CallingConv) {
3494 case CallingConv::X86_StdCall:
3496 case CallingConv::X86_FastCall:
3498 case CallingConv::X86_ThisCall:
3500 case CallingConv::Fast:
3502 case CallingConv::GHC:
3504 case CallingConv::HiPE:
3509 /// \brief Return true if the condition is an unsigned comparison operation.
3510 static bool isX86CCUnsigned(unsigned X86CC) {
3512 default: llvm_unreachable("Invalid integer condition!");
3513 case X86::COND_E: return true;
3514 case X86::COND_G: return false;
3515 case X86::COND_GE: return false;
3516 case X86::COND_L: return false;
3517 case X86::COND_LE: return false;
3518 case X86::COND_NE: return true;
3519 case X86::COND_B: return true;
3520 case X86::COND_A: return true;
3521 case X86::COND_BE: return true;
3522 case X86::COND_AE: return true;
3524 llvm_unreachable("covered switch fell through?!");
3527 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3528 /// specific condition code, returning the condition code and the LHS/RHS of the
3529 /// comparison to make.
3530 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3531 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3533 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3534 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3535 // X > -1 -> X == 0, jump !sign.
3536 RHS = DAG.getConstant(0, RHS.getValueType());
3537 return X86::COND_NS;
3539 if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3540 // X < 0 -> X == 0, jump on sign.
3543 if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3545 RHS = DAG.getConstant(0, RHS.getValueType());
3546 return X86::COND_LE;
3550 switch (SetCCOpcode) {
3551 default: llvm_unreachable("Invalid integer condition!");
3552 case ISD::SETEQ: return X86::COND_E;
3553 case ISD::SETGT: return X86::COND_G;
3554 case ISD::SETGE: return X86::COND_GE;
3555 case ISD::SETLT: return X86::COND_L;
3556 case ISD::SETLE: return X86::COND_LE;
3557 case ISD::SETNE: return X86::COND_NE;
3558 case ISD::SETULT: return X86::COND_B;
3559 case ISD::SETUGT: return X86::COND_A;
3560 case ISD::SETULE: return X86::COND_BE;
3561 case ISD::SETUGE: return X86::COND_AE;
3565 // First determine if it is required or is profitable to flip the operands.
3567 // If LHS is a foldable load, but RHS is not, flip the condition.
3568 if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3569 !ISD::isNON_EXTLoad(RHS.getNode())) {
3570 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3571 std::swap(LHS, RHS);
3574 switch (SetCCOpcode) {
3580 std::swap(LHS, RHS);
3584 // On a floating point condition, the flags are set as follows:
3586 // 0 | 0 | 0 | X > Y
3587 // 0 | 0 | 1 | X < Y
3588 // 1 | 0 | 0 | X == Y
3589 // 1 | 1 | 1 | unordered
3590 switch (SetCCOpcode) {
3591 default: llvm_unreachable("Condcode should be pre-legalized away");
3593 case ISD::SETEQ: return X86::COND_E;
3594 case ISD::SETOLT: // flipped
3596 case ISD::SETGT: return X86::COND_A;
3597 case ISD::SETOLE: // flipped
3599 case ISD::SETGE: return X86::COND_AE;
3600 case ISD::SETUGT: // flipped
3602 case ISD::SETLT: return X86::COND_B;
3603 case ISD::SETUGE: // flipped
3605 case ISD::SETLE: return X86::COND_BE;
3607 case ISD::SETNE: return X86::COND_NE;
3608 case ISD::SETUO: return X86::COND_P;
3609 case ISD::SETO: return X86::COND_NP;
3611 case ISD::SETUNE: return X86::COND_INVALID;
3615 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3616 /// code. Current x86 isa includes the following FP cmov instructions:
3617 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3618 static bool hasFPCMov(unsigned X86CC) {
3634 /// isFPImmLegal - Returns true if the target can instruction select the
3635 /// specified FP immediate natively. If false, the legalizer will
3636 /// materialize the FP immediate as a load from a constant pool.
3637 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3638 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3639 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3645 /// \brief Returns true if it is beneficial to convert a load of a constant
3646 /// to just the constant itself.
3647 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3649 assert(Ty->isIntegerTy());
3651 unsigned BitSize = Ty->getPrimitiveSizeInBits();
3652 if (BitSize == 0 || BitSize > 64)
3657 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3658 /// the specified range (L, H].
3659 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3660 return (Val < 0) || (Val >= Low && Val < Hi);
3663 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3664 /// specified value.
3665 static bool isUndefOrEqual(int Val, int CmpVal) {
3666 return (Val < 0 || Val == CmpVal);
3669 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3670 /// from position Pos and ending in Pos+Size, falls within the specified
3671 /// sequential range (L, L+Pos]. or is undef.
3672 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3673 unsigned Pos, unsigned Size, int Low) {
3674 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3675 if (!isUndefOrEqual(Mask[i], Low))
3680 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3681 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
3682 /// the second operand.
3683 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3684 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3685 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3686 if (VT == MVT::v2f64 || VT == MVT::v2i64)
3687 return (Mask[0] < 2 && Mask[1] < 2);
3691 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3692 /// is suitable for input to PSHUFHW.
3693 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3694 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3697 // Lower quadword copied in order or undef.
3698 if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3701 // Upper quadword shuffled.
3702 for (unsigned i = 4; i != 8; ++i)
3703 if (!isUndefOrInRange(Mask[i], 4, 8))
3706 if (VT == MVT::v16i16) {
3707 // Lower quadword copied in order or undef.
3708 if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3711 // Upper quadword shuffled.
3712 for (unsigned i = 12; i != 16; ++i)
3713 if (!isUndefOrInRange(Mask[i], 12, 16))
3720 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3721 /// is suitable for input to PSHUFLW.
3722 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3723 if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3726 // Upper quadword copied in order.
3727 if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3730 // Lower quadword shuffled.
3731 for (unsigned i = 0; i != 4; ++i)
3732 if (!isUndefOrInRange(Mask[i], 0, 4))
3735 if (VT == MVT::v16i16) {
3736 // Upper quadword copied in order.
3737 if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3740 // Lower quadword shuffled.
3741 for (unsigned i = 8; i != 12; ++i)
3742 if (!isUndefOrInRange(Mask[i], 8, 12))
3749 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3750 /// is suitable for input to PALIGNR.
3751 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3752 const X86Subtarget *Subtarget) {
3753 if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3754 (VT.is256BitVector() && !Subtarget->hasInt256()))
3757 unsigned NumElts = VT.getVectorNumElements();
3758 unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3759 unsigned NumLaneElts = NumElts/NumLanes;
3761 // Do not handle 64-bit element shuffles with palignr.
3762 if (NumLaneElts == 2)
3765 for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3767 for (i = 0; i != NumLaneElts; ++i) {
3772 // Lane is all undef, go to next lane
3773 if (i == NumLaneElts)
3776 int Start = Mask[i+l];
3778 // Make sure its in this lane in one of the sources
3779 if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3780 !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3783 // If not lane 0, then we must match lane 0
3784 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3787 // Correct second source to be contiguous with first source
3788 if (Start >= (int)NumElts)
3789 Start -= NumElts - NumLaneElts;
3791 // Make sure we're shifting in the right direction.
3792 if (Start <= (int)(i+l))
3797 // Check the rest of the elements to see if they are consecutive.
3798 for (++i; i != NumLaneElts; ++i) {
3799 int Idx = Mask[i+l];
3801 // Make sure its in this lane
3802 if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3803 !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3806 // If not lane 0, then we must match lane 0
3807 if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3810 if (Idx >= (int)NumElts)
3811 Idx -= NumElts - NumLaneElts;
3813 if (!isUndefOrEqual(Idx, Start+i))
3822 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3823 /// the two vector operands have swapped position.
3824 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3825 unsigned NumElems) {
3826 for (unsigned i = 0; i != NumElems; ++i) {
3830 else if (idx < (int)NumElems)
3831 Mask[i] = idx + NumElems;
3833 Mask[i] = idx - NumElems;
3837 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3838 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3839 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3840 /// reverse of what x86 shuffles want.
3841 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3843 unsigned NumElems = VT.getVectorNumElements();
3844 unsigned NumLanes = VT.getSizeInBits()/128;
3845 unsigned NumLaneElems = NumElems/NumLanes;
3847 if (NumLaneElems != 2 && NumLaneElems != 4)
3850 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3851 bool symetricMaskRequired =
3852 (VT.getSizeInBits() >= 256) && (EltSize == 32);
3854 // VSHUFPSY divides the resulting vector into 4 chunks.
3855 // The sources are also splitted into 4 chunks, and each destination
3856 // chunk must come from a different source chunk.
3858 // SRC1 => X7 X6 X5 X4 X3 X2 X1 X0
3859 // SRC2 => Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y9
3861 // DST => Y7..Y4, Y7..Y4, X7..X4, X7..X4,
3862 // Y3..Y0, Y3..Y0, X3..X0, X3..X0
3864 // VSHUFPDY divides the resulting vector into 4 chunks.
3865 // The sources are also splitted into 4 chunks, and each destination
3866 // chunk must come from a different source chunk.
3868 // SRC1 => X3 X2 X1 X0
3869 // SRC2 => Y3 Y2 Y1 Y0
3871 // DST => Y3..Y2, X3..X2, Y1..Y0, X1..X0
3873 SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3874 unsigned HalfLaneElems = NumLaneElems/2;
3875 for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3876 for (unsigned i = 0; i != NumLaneElems; ++i) {
3877 int Idx = Mask[i+l];
3878 unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3879 if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3881 // For VSHUFPSY, the mask of the second half must be the same as the
3882 // first but with the appropriate offsets. This works in the same way as
3883 // VPERMILPS works with masks.
3884 if (!symetricMaskRequired || Idx < 0)
3886 if (MaskVal[i] < 0) {
3887 MaskVal[i] = Idx - l;
3890 if ((signed)(Idx - l) != MaskVal[i])
3898 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3899 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3900 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3901 if (!VT.is128BitVector())
3904 unsigned NumElems = VT.getVectorNumElements();
3909 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3910 return isUndefOrEqual(Mask[0], 6) &&
3911 isUndefOrEqual(Mask[1], 7) &&
3912 isUndefOrEqual(Mask[2], 2) &&
3913 isUndefOrEqual(Mask[3], 3);
3916 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3917 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3919 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3920 if (!VT.is128BitVector())
3923 unsigned NumElems = VT.getVectorNumElements();
3928 return isUndefOrEqual(Mask[0], 2) &&
3929 isUndefOrEqual(Mask[1], 3) &&
3930 isUndefOrEqual(Mask[2], 2) &&
3931 isUndefOrEqual(Mask[3], 3);
3934 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3935 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3936 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3937 if (!VT.is128BitVector())
3940 unsigned NumElems = VT.getVectorNumElements();
3942 if (NumElems != 2 && NumElems != 4)
3945 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3946 if (!isUndefOrEqual(Mask[i], i + NumElems))
3949 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3950 if (!isUndefOrEqual(Mask[i], i))
3956 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3957 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3958 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3959 if (!VT.is128BitVector())
3962 unsigned NumElems = VT.getVectorNumElements();
3964 if (NumElems != 2 && NumElems != 4)
3967 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3968 if (!isUndefOrEqual(Mask[i], i))
3971 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3972 if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3978 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3979 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3980 /// i. e: If all but one element come from the same vector.
3981 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3982 // TODO: Deal with AVX's VINSERTPS
3983 if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3986 unsigned CorrectPosV1 = 0;
3987 unsigned CorrectPosV2 = 0;
3988 for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3989 if (Mask[i] == -1) {
3997 else if (Mask[i] == i + 4)
4001 if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4002 // We have 3 elements (undefs count as elements from any vector) from one
4003 // vector, and one from another.
4010 // Some special combinations that can be optimized.
4013 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4014 SelectionDAG &DAG) {
4015 MVT VT = SVOp->getSimpleValueType(0);
4018 if (VT != MVT::v8i32 && VT != MVT::v8f32)
4021 ArrayRef<int> Mask = SVOp->getMask();
4023 // These are the special masks that may be optimized.
4024 static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4025 static const int MaskToOptimizeOdd[] = {1, 9, 3, 11, 5, 13, 7, 15};
4026 bool MatchEvenMask = true;
4027 bool MatchOddMask = true;
4028 for (int i=0; i<8; ++i) {
4029 if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4030 MatchEvenMask = false;
4031 if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4032 MatchOddMask = false;
4035 if (!MatchEvenMask && !MatchOddMask)
4038 SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4040 SDValue Op0 = SVOp->getOperand(0);
4041 SDValue Op1 = SVOp->getOperand(1);
4043 if (MatchEvenMask) {
4044 // Shift the second operand right to 32 bits.
4045 static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4046 Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4048 // Shift the first operand left to 32 bits.
4049 static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4050 Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4052 static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4053 return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4056 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4057 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4058 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4059 bool HasInt256, bool V2IsSplat = false) {
4061 assert(VT.getSizeInBits() >= 128 &&
4062 "Unsupported vector type for unpckl");
4064 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4066 unsigned NumOf256BitLanes;
4067 unsigned NumElts = VT.getVectorNumElements();
4068 if (VT.is256BitVector()) {
4069 if (NumElts != 4 && NumElts != 8 &&
4070 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4073 NumOf256BitLanes = 1;
4074 } else if (VT.is512BitVector()) {
4075 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4076 "Unsupported vector type for unpckh");
4078 NumOf256BitLanes = 2;
4081 NumOf256BitLanes = 1;
4084 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4085 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4087 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4088 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4089 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4090 int BitI = Mask[l256*NumEltsInStride+l+i];
4091 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4092 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4094 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4096 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4104 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4105 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4106 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4107 bool HasInt256, bool V2IsSplat = false) {
4108 assert(VT.getSizeInBits() >= 128 &&
4109 "Unsupported vector type for unpckh");
4111 // AVX defines UNPCK* to operate independently on 128-bit lanes.
4113 unsigned NumOf256BitLanes;
4114 unsigned NumElts = VT.getVectorNumElements();
4115 if (VT.is256BitVector()) {
4116 if (NumElts != 4 && NumElts != 8 &&
4117 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4120 NumOf256BitLanes = 1;
4121 } else if (VT.is512BitVector()) {
4122 assert(VT.getScalarType().getSizeInBits() >= 32 &&
4123 "Unsupported vector type for unpckh");
4125 NumOf256BitLanes = 2;
4128 NumOf256BitLanes = 1;
4131 unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4132 unsigned NumLaneElts = NumEltsInStride/NumLanes;
4134 for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4135 for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4136 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4137 int BitI = Mask[l256*NumEltsInStride+l+i];
4138 int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4139 if (!isUndefOrEqual(BitI, j+l256*NumElts))
4141 if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4143 if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4151 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4152 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4154 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4155 unsigned NumElts = VT.getVectorNumElements();
4156 bool Is256BitVec = VT.is256BitVector();
4158 if (VT.is512BitVector())
4160 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4161 "Unsupported vector type for unpckh");
4163 if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4164 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4167 // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4168 // FIXME: Need a better way to get rid of this, there's no latency difference
4169 // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4170 // the former later. We should also remove the "_undef" special mask.
4171 if (NumElts == 4 && Is256BitVec)
4174 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4175 // independently on 128-bit lanes.
4176 unsigned NumLanes = VT.getSizeInBits()/128;
4177 unsigned NumLaneElts = NumElts/NumLanes;
4179 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4180 for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4181 int BitI = Mask[l+i];
4182 int BitI1 = Mask[l+i+1];
4184 if (!isUndefOrEqual(BitI, j))
4186 if (!isUndefOrEqual(BitI1, j))
4194 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4195 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4197 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4198 unsigned NumElts = VT.getVectorNumElements();
4200 if (VT.is512BitVector())
4203 assert((VT.is128BitVector() || VT.is256BitVector()) &&
4204 "Unsupported vector type for unpckh");
4206 if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4207 (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4210 // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4211 // independently on 128-bit lanes.
4212 unsigned NumLanes = VT.getSizeInBits()/128;
4213 unsigned NumLaneElts = NumElts/NumLanes;
4215 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4216 for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4217 int BitI = Mask[l+i];
4218 int BitI1 = Mask[l+i+1];
4219 if (!isUndefOrEqual(BitI, j))
4221 if (!isUndefOrEqual(BitI1, j))
4228 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4229 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4230 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4231 if (!VT.is512BitVector())
4234 unsigned NumElts = VT.getVectorNumElements();
4235 unsigned HalfSize = NumElts/2;
4236 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4237 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4242 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4243 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4251 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4252 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4253 /// MOVSD, and MOVD, i.e. setting the lowest element.
4254 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4255 if (VT.getVectorElementType().getSizeInBits() < 32)
4257 if (!VT.is128BitVector())
4260 unsigned NumElts = VT.getVectorNumElements();
4262 if (!isUndefOrEqual(Mask[0], NumElts))
4265 for (unsigned i = 1; i != NumElts; ++i)
4266 if (!isUndefOrEqual(Mask[i], i))
4272 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4273 /// as permutations between 128-bit chunks or halves. As an example: this
4275 /// vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4276 /// The first half comes from the second half of V1 and the second half from the
4277 /// the second half of V2.
4278 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4279 if (!HasFp256 || !VT.is256BitVector())
4282 // The shuffle result is divided into half A and half B. In total the two
4283 // sources have 4 halves, namely: C, D, E, F. The final values of A and
4284 // B must come from C, D, E or F.
4285 unsigned HalfSize = VT.getVectorNumElements()/2;
4286 bool MatchA = false, MatchB = false;
4288 // Check if A comes from one of C, D, E, F.
4289 for (unsigned Half = 0; Half != 4; ++Half) {
4290 if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4296 // Check if B comes from one of C, D, E, F.
4297 for (unsigned Half = 0; Half != 4; ++Half) {
4298 if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4304 return MatchA && MatchB;
4307 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4308 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4309 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4310 MVT VT = SVOp->getSimpleValueType(0);
4312 unsigned HalfSize = VT.getVectorNumElements()/2;
4314 unsigned FstHalf = 0, SndHalf = 0;
4315 for (unsigned i = 0; i < HalfSize; ++i) {
4316 if (SVOp->getMaskElt(i) > 0) {
4317 FstHalf = SVOp->getMaskElt(i)/HalfSize;
4321 for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4322 if (SVOp->getMaskElt(i) > 0) {
4323 SndHalf = SVOp->getMaskElt(i)/HalfSize;
4328 return (FstHalf | (SndHalf << 4));
4331 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4332 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4333 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4337 unsigned NumElts = VT.getVectorNumElements();
4339 if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4340 for (unsigned i = 0; i != NumElts; ++i) {
4343 Imm8 |= Mask[i] << (i*2);
4348 unsigned LaneSize = 4;
4349 SmallVector<int, 4> MaskVal(LaneSize, -1);
4351 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4352 for (unsigned i = 0; i != LaneSize; ++i) {
4353 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4357 if (MaskVal[i] < 0) {
4358 MaskVal[i] = Mask[i+l] - l;
4359 Imm8 |= MaskVal[i] << (i*2);
4362 if (Mask[i+l] != (signed)(MaskVal[i]+l))
4369 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4370 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4371 /// Note that VPERMIL mask matching is different depending whether theunderlying
4372 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4373 /// to the same elements of the low, but to the higher half of the source.
4374 /// In VPERMILPD the two lanes could be shuffled independently of each other
4375 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4376 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4377 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4378 if (VT.getSizeInBits() < 256 || EltSize < 32)
4380 bool symetricMaskRequired = (EltSize == 32);
4381 unsigned NumElts = VT.getVectorNumElements();
4383 unsigned NumLanes = VT.getSizeInBits()/128;
4384 unsigned LaneSize = NumElts/NumLanes;
4385 // 2 or 4 elements in one lane
4387 SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4388 for (unsigned l = 0; l != NumElts; l += LaneSize) {
4389 for (unsigned i = 0; i != LaneSize; ++i) {
4390 if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4392 if (symetricMaskRequired) {
4393 if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4394 ExpectedMaskVal[i] = Mask[i+l] - l;
4397 if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4405 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4406 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
4407 /// element of vector 2 and the other elements to come from vector 1 in order.
4408 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4409 bool V2IsSplat = false, bool V2IsUndef = false) {
4410 if (!VT.is128BitVector())
4413 unsigned NumOps = VT.getVectorNumElements();
4414 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4417 if (!isUndefOrEqual(Mask[0], 0))
4420 for (unsigned i = 1; i != NumOps; ++i)
4421 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4422 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4423 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4429 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4430 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4431 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4432 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4433 const X86Subtarget *Subtarget) {
4434 if (!Subtarget->hasSSE3())
4437 unsigned NumElems = VT.getVectorNumElements();
4439 if ((VT.is128BitVector() && NumElems != 4) ||
4440 (VT.is256BitVector() && NumElems != 8) ||
4441 (VT.is512BitVector() && NumElems != 16))
4444 // "i+1" is the value the indexed mask element must have
4445 for (unsigned i = 0; i != NumElems; i += 2)
4446 if (!isUndefOrEqual(Mask[i], i+1) ||
4447 !isUndefOrEqual(Mask[i+1], i+1))
4453 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4454 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4455 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4456 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4457 const X86Subtarget *Subtarget) {
4458 if (!Subtarget->hasSSE3())
4461 unsigned NumElems = VT.getVectorNumElements();
4463 if ((VT.is128BitVector() && NumElems != 4) ||
4464 (VT.is256BitVector() && NumElems != 8) ||
4465 (VT.is512BitVector() && NumElems != 16))
4468 // "i" is the value the indexed mask element must have
4469 for (unsigned i = 0; i != NumElems; i += 2)
4470 if (!isUndefOrEqual(Mask[i], i) ||
4471 !isUndefOrEqual(Mask[i+1], i))
4477 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4478 /// specifies a shuffle of elements that is suitable for input to 256-bit
4479 /// version of MOVDDUP.
4480 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4481 if (!HasFp256 || !VT.is256BitVector())
4484 unsigned NumElts = VT.getVectorNumElements();
4488 for (unsigned i = 0; i != NumElts/2; ++i)
4489 if (!isUndefOrEqual(Mask[i], 0))
4491 for (unsigned i = NumElts/2; i != NumElts; ++i)
4492 if (!isUndefOrEqual(Mask[i], NumElts/2))
4497 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4498 /// specifies a shuffle of elements that is suitable for input to 128-bit
4499 /// version of MOVDDUP.
4500 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4501 if (!VT.is128BitVector())
4504 unsigned e = VT.getVectorNumElements() / 2;
4505 for (unsigned i = 0; i != e; ++i)
4506 if (!isUndefOrEqual(Mask[i], i))
4508 for (unsigned i = 0; i != e; ++i)
4509 if (!isUndefOrEqual(Mask[e+i], i))
4514 /// isVEXTRACTIndex - Return true if the specified
4515 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4516 /// suitable for instruction that extract 128 or 256 bit vectors
4517 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4518 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4519 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4522 // The index should be aligned on a vecWidth-bit boundary.
4524 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4526 MVT VT = N->getSimpleValueType(0);
4527 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4528 bool Result = (Index * ElSize) % vecWidth == 0;
4533 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4534 /// operand specifies a subvector insert that is suitable for input to
4535 /// insertion of 128 or 256-bit subvectors
4536 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4537 assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4538 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4540 // The index should be aligned on a vecWidth-bit boundary.
4542 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4544 MVT VT = N->getSimpleValueType(0);
4545 unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4546 bool Result = (Index * ElSize) % vecWidth == 0;
4551 bool X86::isVINSERT128Index(SDNode *N) {
4552 return isVINSERTIndex(N, 128);
4555 bool X86::isVINSERT256Index(SDNode *N) {
4556 return isVINSERTIndex(N, 256);
4559 bool X86::isVEXTRACT128Index(SDNode *N) {
4560 return isVEXTRACTIndex(N, 128);
4563 bool X86::isVEXTRACT256Index(SDNode *N) {
4564 return isVEXTRACTIndex(N, 256);
4567 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4568 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4569 /// Handles 128-bit and 256-bit.
4570 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4571 MVT VT = N->getSimpleValueType(0);
4573 assert((VT.getSizeInBits() >= 128) &&
4574 "Unsupported vector type for PSHUF/SHUFP");
4576 // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4577 // independently on 128-bit lanes.
4578 unsigned NumElts = VT.getVectorNumElements();
4579 unsigned NumLanes = VT.getSizeInBits()/128;
4580 unsigned NumLaneElts = NumElts/NumLanes;
4582 assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4583 "Only supports 2, 4 or 8 elements per lane");
4585 unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4587 for (unsigned i = 0; i != NumElts; ++i) {
4588 int Elt = N->getMaskElt(i);
4589 if (Elt < 0) continue;
4590 Elt &= NumLaneElts - 1;
4591 unsigned ShAmt = (i << Shift) % 8;
4592 Mask |= Elt << ShAmt;
4598 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4599 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4600 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4601 MVT VT = N->getSimpleValueType(0);
4603 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4604 "Unsupported vector type for PSHUFHW");
4606 unsigned NumElts = VT.getVectorNumElements();
4609 for (unsigned l = 0; l != NumElts; l += 8) {
4610 // 8 nodes per lane, but we only care about the last 4.
4611 for (unsigned i = 0; i < 4; ++i) {
4612 int Elt = N->getMaskElt(l+i+4);
4613 if (Elt < 0) continue;
4614 Elt &= 0x3; // only 2-bits.
4615 Mask |= Elt << (i * 2);
4622 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4623 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4624 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4625 MVT VT = N->getSimpleValueType(0);
4627 assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4628 "Unsupported vector type for PSHUFHW");
4630 unsigned NumElts = VT.getVectorNumElements();
4633 for (unsigned l = 0; l != NumElts; l += 8) {
4634 // 8 nodes per lane, but we only care about the first 4.
4635 for (unsigned i = 0; i < 4; ++i) {
4636 int Elt = N->getMaskElt(l+i);
4637 if (Elt < 0) continue;
4638 Elt &= 0x3; // only 2-bits
4639 Mask |= Elt << (i * 2);
4646 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4647 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4648 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4649 MVT VT = SVOp->getSimpleValueType(0);
4650 unsigned EltSize = VT.is512BitVector() ? 1 :
4651 VT.getVectorElementType().getSizeInBits() >> 3;
4653 unsigned NumElts = VT.getVectorNumElements();
4654 unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4655 unsigned NumLaneElts = NumElts/NumLanes;
4659 for (i = 0; i != NumElts; ++i) {
4660 Val = SVOp->getMaskElt(i);
4664 if (Val >= (int)NumElts)
4665 Val -= NumElts - NumLaneElts;
4667 assert(Val - i > 0 && "PALIGNR imm should be positive");
4668 return (Val - i) * EltSize;
4671 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4672 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4673 if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4674 llvm_unreachable("Illegal extract subvector for VEXTRACT");
4677 cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4679 MVT VecVT = N->getOperand(0).getSimpleValueType();
4680 MVT ElVT = VecVT.getVectorElementType();
4682 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4683 return Index / NumElemsPerChunk;
4686 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4687 assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4688 if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4689 llvm_unreachable("Illegal insert subvector for VINSERT");
4692 cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4694 MVT VecVT = N->getSimpleValueType(0);
4695 MVT ElVT = VecVT.getVectorElementType();
4697 unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4698 return Index / NumElemsPerChunk;
4701 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4702 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4703 /// and VINSERTI128 instructions.
4704 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4705 return getExtractVEXTRACTImmediate(N, 128);
4708 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4709 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4710 /// and VINSERTI64x4 instructions.
4711 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4712 return getExtractVEXTRACTImmediate(N, 256);
4715 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4716 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4717 /// and VINSERTI128 instructions.
4718 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4719 return getInsertVINSERTImmediate(N, 128);
4722 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4723 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4724 /// and VINSERTI64x4 instructions.
4725 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4726 return getInsertVINSERTImmediate(N, 256);
4729 /// isZero - Returns true if Elt is a constant integer zero
4730 static bool isZero(SDValue V) {
4731 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4732 return C && C->isNullValue();
4735 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4737 bool X86::isZeroNode(SDValue Elt) {
4740 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4741 return CFP->getValueAPF().isPosZero();
4745 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4746 /// their permute mask.
4747 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4748 SelectionDAG &DAG) {
4749 MVT VT = SVOp->getSimpleValueType(0);
4750 unsigned NumElems = VT.getVectorNumElements();
4751 SmallVector<int, 8> MaskVec;
4753 for (unsigned i = 0; i != NumElems; ++i) {
4754 int Idx = SVOp->getMaskElt(i);
4756 if (Idx < (int)NumElems)
4761 MaskVec.push_back(Idx);
4763 return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4764 SVOp->getOperand(0), &MaskVec[0]);
4767 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4768 /// match movhlps. The lower half elements should come from upper half of
4769 /// V1 (and in order), and the upper half elements should come from the upper
4770 /// half of V2 (and in order).
4771 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4772 if (!VT.is128BitVector())
4774 if (VT.getVectorNumElements() != 4)
4776 for (unsigned i = 0, e = 2; i != e; ++i)
4777 if (!isUndefOrEqual(Mask[i], i+2))
4779 for (unsigned i = 2; i != 4; ++i)
4780 if (!isUndefOrEqual(Mask[i], i+4))
4785 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4786 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4788 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4789 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4791 N = N->getOperand(0).getNode();
4792 if (!ISD::isNON_EXTLoad(N))
4795 *LD = cast<LoadSDNode>(N);
4799 // Test whether the given value is a vector value which will be legalized
4801 static bool WillBeConstantPoolLoad(SDNode *N) {
4802 if (N->getOpcode() != ISD::BUILD_VECTOR)
4805 // Check for any non-constant elements.
4806 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4807 switch (N->getOperand(i).getNode()->getOpcode()) {
4809 case ISD::ConstantFP:
4816 // Vectors of all-zeros and all-ones are materialized with special
4817 // instructions rather than being loaded.
4818 return !ISD::isBuildVectorAllZeros(N) &&
4819 !ISD::isBuildVectorAllOnes(N);
4822 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4823 /// match movlp{s|d}. The lower half elements should come from lower half of
4824 /// V1 (and in order), and the upper half elements should come from the upper
4825 /// half of V2 (and in order). And since V1 will become the source of the
4826 /// MOVLP, it must be either a vector load or a scalar load to vector.
4827 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4828 ArrayRef<int> Mask, MVT VT) {
4829 if (!VT.is128BitVector())
4832 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4834 // Is V2 is a vector load, don't do this transformation. We will try to use
4835 // load folding shufps op.
4836 if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4839 unsigned NumElems = VT.getVectorNumElements();
4841 if (NumElems != 2 && NumElems != 4)
4843 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4844 if (!isUndefOrEqual(Mask[i], i))
4846 for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4847 if (!isUndefOrEqual(Mask[i], i+NumElems))
4852 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4854 static bool isSplatVector(SDNode *N) {
4855 if (N->getOpcode() != ISD::BUILD_VECTOR)
4858 SDValue SplatValue = N->getOperand(0);
4859 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4860 if (N->getOperand(i) != SplatValue)
4865 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4866 /// to an zero vector.
4867 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4868 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4869 SDValue V1 = N->getOperand(0);
4870 SDValue V2 = N->getOperand(1);
4871 unsigned NumElems = N->getValueType(0).getVectorNumElements();
4872 for (unsigned i = 0; i != NumElems; ++i) {
4873 int Idx = N->getMaskElt(i);
4874 if (Idx >= (int)NumElems) {
4875 unsigned Opc = V2.getOpcode();
4876 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4878 if (Opc != ISD::BUILD_VECTOR ||
4879 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4881 } else if (Idx >= 0) {
4882 unsigned Opc = V1.getOpcode();
4883 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4885 if (Opc != ISD::BUILD_VECTOR ||
4886 !X86::isZeroNode(V1.getOperand(Idx)))
4893 /// getZeroVector - Returns a vector of specified type with all zero elements.
4895 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4896 SelectionDAG &DAG, SDLoc dl) {
4897 assert(VT.isVector() && "Expected a vector type");
4899 // Always build SSE zero vectors as <4 x i32> bitcasted
4900 // to their dest type. This ensures they get CSE'd.
4902 if (VT.is128BitVector()) { // SSE
4903 if (Subtarget->hasSSE2()) { // SSE2
4904 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4905 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4907 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4908 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4910 } else if (VT.is256BitVector()) { // AVX
4911 if (Subtarget->hasInt256()) { // AVX2
4912 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4913 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4914 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4916 // 256-bit logic and arithmetic instructions in AVX are all
4917 // floating-point, no support for integer ops. Emit fp zeroed vectors.
4918 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4919 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4920 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4922 } else if (VT.is512BitVector()) { // AVX-512
4923 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4924 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4925 Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4926 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4927 } else if (VT.getScalarType() == MVT::i1) {
4928 assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4929 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4930 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4931 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4933 llvm_unreachable("Unexpected vector type");
4935 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4938 /// getOnesVector - Returns a vector of specified type with all bits set.
4939 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4940 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4941 /// Then bitcast to their original type, ensuring they get CSE'd.
4942 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4944 assert(VT.isVector() && "Expected a vector type");
4946 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4948 if (VT.is256BitVector()) {
4949 if (HasInt256) { // AVX2
4950 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4951 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4953 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4954 Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4956 } else if (VT.is128BitVector()) {
4957 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4959 llvm_unreachable("Unexpected vector type");
4961 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4964 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4965 /// that point to V2 points to its first element.
4966 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4967 for (unsigned i = 0; i != NumElems; ++i) {
4968 if (Mask[i] > (int)NumElems) {
4974 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4975 /// operation of specified width.
4976 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4978 unsigned NumElems = VT.getVectorNumElements();
4979 SmallVector<int, 8> Mask;
4980 Mask.push_back(NumElems);
4981 for (unsigned i = 1; i != NumElems; ++i)
4983 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4986 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4987 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4989 unsigned NumElems = VT.getVectorNumElements();
4990 SmallVector<int, 8> Mask;
4991 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4993 Mask.push_back(i + NumElems);
4995 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4998 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4999 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5001 unsigned NumElems = VT.getVectorNumElements();
5002 SmallVector<int, 8> Mask;
5003 for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5004 Mask.push_back(i + Half);
5005 Mask.push_back(i + NumElems + Half);
5007 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5010 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5011 // a generic shuffle instruction because the target has no such instructions.
5012 // Generate shuffles which repeat i16 and i8 several times until they can be
5013 // represented by v4f32 and then be manipulated by target suported shuffles.
5014 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5015 MVT VT = V.getSimpleValueType();
5016 int NumElems = VT.getVectorNumElements();
5019 while (NumElems > 4) {
5020 if (EltNo < NumElems/2) {
5021 V = getUnpackl(DAG, dl, VT, V, V);
5023 V = getUnpackh(DAG, dl, VT, V, V);
5024 EltNo -= NumElems/2;
5031 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5032 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5033 MVT VT = V.getSimpleValueType();
5036 if (VT.is128BitVector()) {
5037 V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5038 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5039 V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5041 } else if (VT.is256BitVector()) {
5042 // To use VPERMILPS to splat scalars, the second half of indicies must
5043 // refer to the higher part, which is a duplication of the lower one,
5044 // because VPERMILPS can only handle in-lane permutations.
5045 int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5046 EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5048 V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5049 V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5052 llvm_unreachable("Vector size not supported");
5054 return DAG.getNode(ISD::BITCAST, dl, VT, V);
5057 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5058 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5059 MVT SrcVT = SV->getSimpleValueType(0);
5060 SDValue V1 = SV->getOperand(0);
5063 int EltNo = SV->getSplatIndex();
5064 int NumElems = SrcVT.getVectorNumElements();
5065 bool Is256BitVec = SrcVT.is256BitVector();
5067 assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5068 "Unknown how to promote splat for type");
5070 // Extract the 128-bit part containing the splat element and update
5071 // the splat element index when it refers to the higher register.
5073 V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5074 if (EltNo >= NumElems/2)
5075 EltNo -= NumElems/2;
5078 // All i16 and i8 vector types can't be used directly by a generic shuffle
5079 // instruction because the target has no such instruction. Generate shuffles
5080 // which repeat i16 and i8 several times until they fit in i32, and then can
5081 // be manipulated by target suported shuffles.
5082 MVT EltVT = SrcVT.getVectorElementType();
5083 if (EltVT == MVT::i8 || EltVT == MVT::i16)
5084 V1 = PromoteSplati8i16(V1, DAG, EltNo);
5086 // Recreate the 256-bit vector and place the same 128-bit vector
5087 // into the low and high part. This is necessary because we want
5088 // to use VPERM* to shuffle the vectors
5090 V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5093 return getLegalSplat(DAG, V1, EltNo);
5096 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5097 /// vector of zero or undef vector. This produces a shuffle where the low
5098 /// element of V2 is swizzled into the zero/undef vector, landing at element
5099 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
5100 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5102 const X86Subtarget *Subtarget,
5103 SelectionDAG &DAG) {
5104 MVT VT = V2.getSimpleValueType();
5106 ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5107 unsigned NumElems = VT.getVectorNumElements();
5108 SmallVector<int, 16> MaskVec;
5109 for (unsigned i = 0; i != NumElems; ++i)
5110 // If this is the insertion idx, put the low elt of V2 here.
5111 MaskVec.push_back(i == Idx ? NumElems : i);
5112 return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5115 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5116 /// target specific opcode. Returns true if the Mask could be calculated.
5117 /// Sets IsUnary to true if only uses one source.
5118 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5119 SmallVectorImpl<int> &Mask, bool &IsUnary) {
5120 unsigned NumElems = VT.getVectorNumElements();
5124 switch(N->getOpcode()) {
5126 ImmN = N->getOperand(N->getNumOperands()-1);
5127 DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5129 case X86ISD::UNPCKH:
5130 DecodeUNPCKHMask(VT, Mask);
5132 case X86ISD::UNPCKL:
5133 DecodeUNPCKLMask(VT, Mask);
5135 case X86ISD::MOVHLPS:
5136 DecodeMOVHLPSMask(NumElems, Mask);
5138 case X86ISD::MOVLHPS:
5139 DecodeMOVLHPSMask(NumElems, Mask);
5141 case X86ISD::PALIGNR:
5142 ImmN = N->getOperand(N->getNumOperands()-1);
5143 DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5145 case X86ISD::PSHUFD:
5146 case X86ISD::VPERMILP:
5147 ImmN = N->getOperand(N->getNumOperands()-1);
5148 DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5151 case X86ISD::PSHUFHW:
5152 ImmN = N->getOperand(N->getNumOperands()-1);
5153 DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5156 case X86ISD::PSHUFLW:
5157 ImmN = N->getOperand(N->getNumOperands()-1);
5158 DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5161 case X86ISD::VPERMI:
5162 ImmN = N->getOperand(N->getNumOperands()-1);
5163 DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5167 case X86ISD::MOVSD: {
5168 // The index 0 always comes from the first element of the second source,
5169 // this is why MOVSS and MOVSD are used in the first place. The other
5170 // elements come from the other positions of the first source vector
5171 Mask.push_back(NumElems);
5172 for (unsigned i = 1; i != NumElems; ++i) {
5177 case X86ISD::VPERM2X128:
5178 ImmN = N->getOperand(N->getNumOperands()-1);
5179 DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5180 if (Mask.empty()) return false;
5182 case X86ISD::MOVDDUP:
5183 case X86ISD::MOVLHPD:
5184 case X86ISD::MOVLPD:
5185 case X86ISD::MOVLPS:
5186 case X86ISD::MOVSHDUP:
5187 case X86ISD::MOVSLDUP:
5188 // Not yet implemented
5190 default: llvm_unreachable("unknown target shuffle node");
5196 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5197 /// element of the result of the vector shuffle.
5198 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5201 return SDValue(); // Limit search depth.
5203 SDValue V = SDValue(N, 0);
5204 EVT VT = V.getValueType();
5205 unsigned Opcode = V.getOpcode();
5207 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5208 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5209 int Elt = SV->getMaskElt(Index);
5212 return DAG.getUNDEF(VT.getVectorElementType());
5214 unsigned NumElems = VT.getVectorNumElements();
5215 SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5216 : SV->getOperand(1);
5217 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5220 // Recurse into target specific vector shuffles to find scalars.
5221 if (isTargetShuffle(Opcode)) {
5222 MVT ShufVT = V.getSimpleValueType();
5223 unsigned NumElems = ShufVT.getVectorNumElements();
5224 SmallVector<int, 16> ShuffleMask;
5227 if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5230 int Elt = ShuffleMask[Index];
5232 return DAG.getUNDEF(ShufVT.getVectorElementType());
5234 SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5236 return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5240 // Actual nodes that may contain scalar elements
5241 if (Opcode == ISD::BITCAST) {
5242 V = V.getOperand(0);
5243 EVT SrcVT = V.getValueType();
5244 unsigned NumElems = VT.getVectorNumElements();
5246 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5250 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5251 return (Index == 0) ? V.getOperand(0)
5252 : DAG.getUNDEF(VT.getVectorElementType());
5254 if (V.getOpcode() == ISD::BUILD_VECTOR)
5255 return V.getOperand(Index);
5260 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5261 /// shuffle operation which come from a consecutively from a zero. The
5262 /// search can start in two different directions, from left or right.
5263 /// We count undefs as zeros until PreferredNum is reached.
5264 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5265 unsigned NumElems, bool ZerosFromLeft,
5267 unsigned PreferredNum = -1U) {
5268 unsigned NumZeros = 0;
5269 for (unsigned i = 0; i != NumElems; ++i) {
5270 unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5271 SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5275 if (X86::isZeroNode(Elt))
5277 else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5278 NumZeros = std::min(NumZeros + 1, PreferredNum);
5286 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5287 /// correspond consecutively to elements from one of the vector operands,
5288 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5290 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5291 unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5292 unsigned NumElems, unsigned &OpNum) {
5293 bool SeenV1 = false;
5294 bool SeenV2 = false;
5296 for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5297 int Idx = SVOp->getMaskElt(i);
5298 // Ignore undef indicies
5302 if (Idx < (int)NumElems)
5307 // Only accept consecutive elements from the same vector
5308 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5312 OpNum = SeenV1 ? 0 : 1;
5316 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5317 /// logical left shift of a vector.
5318 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5319 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5321 SVOp->getSimpleValueType(0).getVectorNumElements();
5322 unsigned NumZeros = getNumOfConsecutiveZeros(
5323 SVOp, NumElems, false /* check zeros from right */, DAG,
5324 SVOp->getMaskElt(0));
5330 // Considering the elements in the mask that are not consecutive zeros,
5331 // check if they consecutively come from only one of the source vectors.
5333 // V1 = {X, A, B, C} 0
5335 // vector_shuffle V1, V2 <1, 2, 3, X>
5337 if (!isShuffleMaskConsecutive(SVOp,
5338 0, // Mask Start Index
5339 NumElems-NumZeros, // Mask End Index(exclusive)
5340 NumZeros, // Where to start looking in the src vector
5341 NumElems, // Number of elements in vector
5342 OpSrc)) // Which source operand ?
5347 ShVal = SVOp->getOperand(OpSrc);
5351 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5352 /// logical left shift of a vector.
5353 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5354 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5356 SVOp->getSimpleValueType(0).getVectorNumElements();
5357 unsigned NumZeros = getNumOfConsecutiveZeros(
5358 SVOp, NumElems, true /* check zeros from left */, DAG,
5359 NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5365 // Considering the elements in the mask that are not consecutive zeros,
5366 // check if they consecutively come from only one of the source vectors.
5368 // 0 { A, B, X, X } = V2
5370 // vector_shuffle V1, V2 <X, X, 4, 5>
5372 if (!isShuffleMaskConsecutive(SVOp,
5373 NumZeros, // Mask Start Index
5374 NumElems, // Mask End Index(exclusive)
5375 0, // Where to start looking in the src vector
5376 NumElems, // Number of elements in vector
5377 OpSrc)) // Which source operand ?
5382 ShVal = SVOp->getOperand(OpSrc);
5386 /// isVectorShift - Returns true if the shuffle can be implemented as a
5387 /// logical left or right shift of a vector.
5388 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5389 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5390 // Although the logic below support any bitwidth size, there are no
5391 // shift instructions which handle more than 128-bit vectors.
5392 if (!SVOp->getSimpleValueType(0).is128BitVector())
5395 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5396 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5402 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5404 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5405 unsigned NumNonZero, unsigned NumZero,
5407 const X86Subtarget* Subtarget,
5408 const TargetLowering &TLI) {
5415 for (unsigned i = 0; i < 16; ++i) {
5416 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5417 if (ThisIsNonZero && First) {
5419 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5421 V = DAG.getUNDEF(MVT::v8i16);
5426 SDValue ThisElt, LastElt;
5427 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5428 if (LastIsNonZero) {
5429 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5430 MVT::i16, Op.getOperand(i-1));
5432 if (ThisIsNonZero) {
5433 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5434 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5435 ThisElt, DAG.getConstant(8, MVT::i8));
5437 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5441 if (ThisElt.getNode())
5442 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5443 DAG.getIntPtrConstant(i/2));
5447 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5450 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5452 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5453 unsigned NumNonZero, unsigned NumZero,
5455 const X86Subtarget* Subtarget,
5456 const TargetLowering &TLI) {
5463 for (unsigned i = 0; i < 8; ++i) {
5464 bool isNonZero = (NonZeros & (1 << i)) != 0;
5468 V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5470 V = DAG.getUNDEF(MVT::v8i16);
5473 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5474 MVT::v8i16, V, Op.getOperand(i),
5475 DAG.getIntPtrConstant(i));
5482 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5483 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5484 unsigned NonZeros, unsigned NumNonZero,
5485 unsigned NumZero, SelectionDAG &DAG,
5486 const X86Subtarget *Subtarget,
5487 const TargetLowering &TLI) {
5488 // We know there's at least one non-zero element
5489 unsigned FirstNonZeroIdx = 0;
5490 SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5491 while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5492 X86::isZeroNode(FirstNonZero)) {
5494 FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5497 if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5498 !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5501 SDValue V = FirstNonZero.getOperand(0);
5502 MVT VVT = V.getSimpleValueType();
5503 if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5506 unsigned FirstNonZeroDst =
5507 cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5508 unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5509 unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5510 unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5512 for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5513 SDValue Elem = Op.getOperand(Idx);
5514 if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5517 // TODO: What else can be here? Deal with it.
5518 if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5521 // TODO: Some optimizations are still possible here
5522 // ex: Getting one element from a vector, and the rest from another.
5523 if (Elem.getOperand(0) != V)
5526 unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5529 else if (IncorrectIdx == -1U) {
5533 // There was already one element with an incorrect index.
5534 // We can't optimize this case to an insertps.
5538 if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5540 EVT VT = Op.getSimpleValueType();
5541 unsigned ElementMoveMask = 0;
5542 if (IncorrectIdx == -1U)
5543 ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5545 ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5547 SDValue InsertpsMask =
5548 DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5549 return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5555 /// getVShift - Return a vector logical shift node.
5557 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5558 unsigned NumBits, SelectionDAG &DAG,
5559 const TargetLowering &TLI, SDLoc dl) {
5560 assert(VT.is128BitVector() && "Unknown type for VShift");
5561 EVT ShVT = MVT::v2i64;
5562 unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5563 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5564 return DAG.getNode(ISD::BITCAST, dl, VT,
5565 DAG.getNode(Opc, dl, ShVT, SrcOp,
5566 DAG.getConstant(NumBits,
5567 TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5571 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5573 // Check if the scalar load can be widened into a vector load. And if
5574 // the address is "base + cst" see if the cst can be "absorbed" into
5575 // the shuffle mask.
5576 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5577 SDValue Ptr = LD->getBasePtr();
5578 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5580 EVT PVT = LD->getValueType(0);
5581 if (PVT != MVT::i32 && PVT != MVT::f32)
5586 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5587 FI = FINode->getIndex();
5589 } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5590 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5591 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5592 Offset = Ptr.getConstantOperandVal(1);
5593 Ptr = Ptr.getOperand(0);
5598 // FIXME: 256-bit vector instructions don't require a strict alignment,
5599 // improve this code to support it better.
5600 unsigned RequiredAlign = VT.getSizeInBits()/8;
5601 SDValue Chain = LD->getChain();
5602 // Make sure the stack object alignment is at least 16 or 32.
5603 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5604 if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5605 if (MFI->isFixedObjectIndex(FI)) {
5606 // Can't change the alignment. FIXME: It's possible to compute
5607 // the exact stack offset and reference FI + adjust offset instead.
5608 // If someone *really* cares about this. That's the way to implement it.
5611 MFI->setObjectAlignment(FI, RequiredAlign);
5615 // (Offset % 16 or 32) must be multiple of 4. Then address is then
5616 // Ptr + (Offset & ~15).
5619 if ((Offset % RequiredAlign) & 3)
5621 int64_t StartOffset = Offset & ~(RequiredAlign-1);
5623 Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5624 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5626 int EltNo = (Offset - StartOffset) >> 2;
5627 unsigned NumElems = VT.getVectorNumElements();
5629 EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5630 SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5631 LD->getPointerInfo().getWithOffset(StartOffset),
5632 false, false, false, 0);
5634 SmallVector<int, 8> Mask;
5635 for (unsigned i = 0; i != NumElems; ++i)
5636 Mask.push_back(EltNo);
5638 return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5644 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5645 /// vector of type 'VT', see if the elements can be replaced by a single large
5646 /// load which has the same value as a build_vector whose operands are 'elts'.
5648 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5650 /// FIXME: we'd also like to handle the case where the last elements are zero
5651 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5652 /// There's even a handy isZeroNode for that purpose.
5653 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5654 SDLoc &DL, SelectionDAG &DAG,
5655 bool isAfterLegalize) {
5656 EVT EltVT = VT.getVectorElementType();
5657 unsigned NumElems = Elts.size();
5659 LoadSDNode *LDBase = nullptr;
5660 unsigned LastLoadedElt = -1U;
5662 // For each element in the initializer, see if we've found a load or an undef.
5663 // If we don't find an initial load element, or later load elements are
5664 // non-consecutive, bail out.
5665 for (unsigned i = 0; i < NumElems; ++i) {
5666 SDValue Elt = Elts[i];
5668 if (!Elt.getNode() ||
5669 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5672 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5674 LDBase = cast<LoadSDNode>(Elt.getNode());
5678 if (Elt.getOpcode() == ISD::UNDEF)
5681 LoadSDNode *LD = cast<LoadSDNode>(Elt);
5682 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5687 // If we have found an entire vector of loads and undefs, then return a large
5688 // load of the entire vector width starting at the base pointer. If we found
5689 // consecutive loads for the low half, generate a vzext_load node.
5690 if (LastLoadedElt == NumElems - 1) {
5692 if (isAfterLegalize &&
5693 !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5696 SDValue NewLd = SDValue();
5698 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5699 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5700 LDBase->getPointerInfo(),
5701 LDBase->isVolatile(), LDBase->isNonTemporal(),
5702 LDBase->isInvariant(), 0);
5703 NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5704 LDBase->getPointerInfo(),
5705 LDBase->isVolatile(), LDBase->isNonTemporal(),
5706 LDBase->isInvariant(), LDBase->getAlignment());
5708 if (LDBase->hasAnyUseOfValue(1)) {
5709 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5711 SDValue(NewLd.getNode(), 1));
5712 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5713 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5714 SDValue(NewLd.getNode(), 1));
5719 if (NumElems == 4 && LastLoadedElt == 1 &&
5720 DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5721 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5722 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5724 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5725 LDBase->getPointerInfo(),
5726 LDBase->getAlignment(),
5727 false/*isVolatile*/, true/*ReadMem*/,
5730 // Make sure the newly-created LOAD is in the same position as LDBase in
5731 // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5732 // update uses of LDBase's output chain to use the TokenFactor.
5733 if (LDBase->hasAnyUseOfValue(1)) {
5734 SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5735 SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5736 DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5737 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5738 SDValue(ResNode.getNode(), 1));
5741 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5746 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5747 /// to generate a splat value for the following cases:
5748 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5749 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5750 /// a scalar load, or a constant.
5751 /// The VBROADCAST node is returned when a pattern is found,
5752 /// or SDValue() otherwise.
5753 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5754 SelectionDAG &DAG) {
5755 if (!Subtarget->hasFp256())
5758 MVT VT = Op.getSimpleValueType();
5761 assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5762 "Unsupported vector type for broadcast.");
5767 switch (Op.getOpcode()) {
5769 // Unknown pattern found.
5772 case ISD::BUILD_VECTOR: {
5773 // The BUILD_VECTOR node must be a splat.
5774 if (!isSplatVector(Op.getNode()))
5777 Ld = Op.getOperand(0);
5778 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5779 Ld.getOpcode() == ISD::ConstantFP);
5781 // The suspected load node has several users. Make sure that all
5782 // of its users are from the BUILD_VECTOR node.
5783 // Constants may have multiple users.
5784 if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5789 case ISD::VECTOR_SHUFFLE: {
5790 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5792 // Shuffles must have a splat mask where the first element is
5794 if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5797 SDValue Sc = Op.getOperand(0);
5798 if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5799 Sc.getOpcode() != ISD::BUILD_VECTOR) {
5801 if (!Subtarget->hasInt256())
5804 // Use the register form of the broadcast instruction available on AVX2.
5805 if (VT.getSizeInBits() >= 256)
5806 Sc = Extract128BitVector(Sc, 0, DAG, dl);
5807 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5810 Ld = Sc.getOperand(0);
5811 ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5812 Ld.getOpcode() == ISD::ConstantFP);
5814 // The scalar_to_vector node and the suspected
5815 // load node must have exactly one user.
5816 // Constants may have multiple users.
5818 // AVX-512 has register version of the broadcast
5819 bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5820 Ld.getValueType().getSizeInBits() >= 32;
5821 if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5828 bool IsGE256 = (VT.getSizeInBits() >= 256);
5830 // Handle the broadcasting a single constant scalar from the constant pool
5831 // into a vector. On Sandybridge it is still better to load a constant vector
5832 // from the constant pool and not to broadcast it from a scalar.
5833 if (ConstSplatVal && Subtarget->hasInt256()) {
5834 EVT CVT = Ld.getValueType();
5835 assert(!CVT.isVector() && "Must not broadcast a vector type");
5836 unsigned ScalarSize = CVT.getSizeInBits();
5838 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5839 const Constant *C = nullptr;
5840 if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5841 C = CI->getConstantIntValue();
5842 else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5843 C = CF->getConstantFPValue();
5845 assert(C && "Invalid constant type");
5847 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5848 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5849 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5850 Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5851 MachinePointerInfo::getConstantPool(),
5852 false, false, false, Alignment);
5854 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5858 bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5859 unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5861 // Handle AVX2 in-register broadcasts.
5862 if (!IsLoad && Subtarget->hasInt256() &&
5863 (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5864 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5866 // The scalar source must be a normal load.
5870 if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5871 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5873 // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5874 // double since there is no vbroadcastsd xmm
5875 if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5876 if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5877 return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5880 // Unsupported broadcast.
5884 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5885 /// underlying vector and index.
5887 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5889 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5891 int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5892 if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5895 // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5897 // (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5899 // (extract_vector_elt (vector_shuffle<2,u,u,u>
5900 // (extract_subvector (v8f32 %vreg0), Constant<4>),
5903 // In this case the vector is the extract_subvector expression and the index
5904 // is 2, as specified by the shuffle.
5905 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5906 SDValue ShuffleVec = SVOp->getOperand(0);
5907 MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5908 assert(ShuffleVecVT.getVectorElementType() ==
5909 ExtractedFromVec.getSimpleValueType().getVectorElementType());
5911 int ShuffleIdx = SVOp->getMaskElt(Idx);
5912 if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5913 ExtractedFromVec = ShuffleVec;
5919 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5920 MVT VT = Op.getSimpleValueType();
5922 // Skip if insert_vec_elt is not supported.
5923 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5924 if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5928 unsigned NumElems = Op.getNumOperands();
5932 SmallVector<unsigned, 4> InsertIndices;
5933 SmallVector<int, 8> Mask(NumElems, -1);
5935 for (unsigned i = 0; i != NumElems; ++i) {
5936 unsigned Opc = Op.getOperand(i).getOpcode();
5938 if (Opc == ISD::UNDEF)
5941 if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5942 // Quit if more than 1 elements need inserting.
5943 if (InsertIndices.size() > 1)
5946 InsertIndices.push_back(i);
5950 SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5951 SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5952 // Quit if non-constant index.
5953 if (!isa<ConstantSDNode>(ExtIdx))
5955 int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5957 // Quit if extracted from vector of different type.
5958 if (ExtractedFromVec.getValueType() != VT)
5961 if (!VecIn1.getNode())
5962 VecIn1 = ExtractedFromVec;
5963 else if (VecIn1 != ExtractedFromVec) {
5964 if (!VecIn2.getNode())
5965 VecIn2 = ExtractedFromVec;
5966 else if (VecIn2 != ExtractedFromVec)
5967 // Quit if more than 2 vectors to shuffle
5971 if (ExtractedFromVec == VecIn1)
5973 else if (ExtractedFromVec == VecIn2)
5974 Mask[i] = Idx + NumElems;
5977 if (!VecIn1.getNode())
5980 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5981 SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5982 for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5983 unsigned Idx = InsertIndices[i];
5984 NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5985 DAG.getIntPtrConstant(Idx));
5991 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5993 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5995 MVT VT = Op.getSimpleValueType();
5996 assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5997 "Unexpected type in LowerBUILD_VECTORvXi1!");
6000 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6001 SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6002 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6003 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6006 if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6007 SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6008 SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6009 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6012 bool AllContants = true;
6013 uint64_t Immediate = 0;
6014 int NonConstIdx = -1;
6015 bool IsSplat = true;
6016 unsigned NumNonConsts = 0;
6017 unsigned NumConsts = 0;
6018 for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6019 SDValue In = Op.getOperand(idx);
6020 if (In.getOpcode() == ISD::UNDEF)
6022 if (!isa<ConstantSDNode>(In)) {
6023 AllContants = false;
6029 if (cast<ConstantSDNode>(In)->getZExtValue())
6030 Immediate |= (1ULL << idx);
6032 if (In != Op.getOperand(0))
6037 SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6038 DAG.getConstant(Immediate, MVT::i16));
6039 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6040 DAG.getIntPtrConstant(0));
6043 if (NumNonConsts == 1 && NonConstIdx != 0) {
6046 SDValue VecAsImm = DAG.getConstant(Immediate,
6047 MVT::getIntegerVT(VT.getSizeInBits()));
6048 DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6051 DstVec = DAG.getUNDEF(VT);
6052 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6053 Op.getOperand(NonConstIdx),
6054 DAG.getIntPtrConstant(NonConstIdx));
6056 if (!IsSplat && (NonConstIdx != 0))
6057 llvm_unreachable("Unsupported BUILD_VECTOR operation");
6058 MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6061 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6062 DAG.getConstant(-1, SelectVT),
6063 DAG.getConstant(0, SelectVT));
6065 Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6066 DAG.getConstant((Immediate | 1), SelectVT),
6067 DAG.getConstant(Immediate, SelectVT));
6068 return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6071 /// \brief Return true if \p N implements a horizontal binop and return the
6072 /// operands for the horizontal binop into V0 and V1.
6074 /// This is a helper function of PerformBUILD_VECTORCombine.
6075 /// This function checks that the build_vector \p N in input implements a
6076 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6077 /// operation to match.
6078 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6079 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6080 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6083 /// This function only analyzes elements of \p N whose indices are
6084 /// in range [BaseIdx, LastIdx).
6085 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6087 unsigned BaseIdx, unsigned LastIdx,
6088 SDValue &V0, SDValue &V1) {
6089 EVT VT = N->getValueType(0);
6091 assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6092 assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6093 "Invalid Vector in input!");
6095 bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6096 bool CanFold = true;
6097 unsigned ExpectedVExtractIdx = BaseIdx;
6098 unsigned NumElts = LastIdx - BaseIdx;
6099 V0 = DAG.getUNDEF(VT);
6100 V1 = DAG.getUNDEF(VT);
6102 // Check if N implements a horizontal binop.
6103 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6104 SDValue Op = N->getOperand(i + BaseIdx);
6107 if (Op->getOpcode() == ISD::UNDEF) {
6108 // Update the expected vector extract index.
6109 if (i * 2 == NumElts)
6110 ExpectedVExtractIdx = BaseIdx;
6111 ExpectedVExtractIdx += 2;
6115 CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6120 SDValue Op0 = Op.getOperand(0);
6121 SDValue Op1 = Op.getOperand(1);
6123 // Try to match the following pattern:
6124 // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6125 CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6126 Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6127 Op0.getOperand(0) == Op1.getOperand(0) &&
6128 isa<ConstantSDNode>(Op0.getOperand(1)) &&
6129 isa<ConstantSDNode>(Op1.getOperand(1)));
6133 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6134 unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6136 if (i * 2 < NumElts) {
6137 if (V0.getOpcode() == ISD::UNDEF)
6138 V0 = Op0.getOperand(0);
6140 if (V1.getOpcode() == ISD::UNDEF)
6141 V1 = Op0.getOperand(0);
6142 if (i * 2 == NumElts)
6143 ExpectedVExtractIdx = BaseIdx;
6146 SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6147 if (I0 == ExpectedVExtractIdx)
6148 CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6149 else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6150 // Try to match the following dag sequence:
6151 // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6152 CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6156 ExpectedVExtractIdx += 2;
6162 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6163 /// a concat_vector.
6165 /// This is a helper function of PerformBUILD_VECTORCombine.
6166 /// This function expects two 256-bit vectors called V0 and V1.
6167 /// At first, each vector is split into two separate 128-bit vectors.
6168 /// Then, the resulting 128-bit vectors are used to implement two
6169 /// horizontal binary operations.
6171 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6173 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6174 /// the two new horizontal binop.
6175 /// When Mode is set, the first horizontal binop dag node would take as input
6176 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6177 /// horizontal binop dag node would take as input the lower 128-bit of V1
6178 /// and the upper 128-bit of V1.
6180 /// HADD V0_LO, V0_HI
6181 /// HADD V1_LO, V1_HI
6183 /// Otherwise, the first horizontal binop dag node takes as input the lower
6184 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6185 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6187 /// HADD V0_LO, V1_LO
6188 /// HADD V0_HI, V1_HI
6190 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6191 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6192 /// the upper 128-bits of the result.
6193 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6194 SDLoc DL, SelectionDAG &DAG,
6195 unsigned X86Opcode, bool Mode,
6196 bool isUndefLO, bool isUndefHI) {
6197 EVT VT = V0.getValueType();
6198 assert(VT.is256BitVector() && VT == V1.getValueType() &&
6199 "Invalid nodes in input!");
6201 unsigned NumElts = VT.getVectorNumElements();
6202 SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6203 SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6204 SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6205 SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6206 EVT NewVT = V0_LO.getValueType();
6208 SDValue LO = DAG.getUNDEF(NewVT);
6209 SDValue HI = DAG.getUNDEF(NewVT);
6212 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6213 if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6214 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6215 if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6216 HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6218 // Don't emit a horizontal binop if the result is expected to be UNDEF.
6219 if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6220 V1_LO->getOpcode() != ISD::UNDEF))
6221 LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6223 if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6224 V1_HI->getOpcode() != ISD::UNDEF))
6225 HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6228 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6231 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6232 /// sequence of 'vadd + vsub + blendi'.
6233 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6234 const X86Subtarget *Subtarget) {
6236 EVT VT = BV->getValueType(0);
6237 unsigned NumElts = VT.getVectorNumElements();
6238 SDValue InVec0 = DAG.getUNDEF(VT);
6239 SDValue InVec1 = DAG.getUNDEF(VT);
6241 assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6242 VT == MVT::v2f64) && "build_vector with an invalid type found!");
6244 // Don't try to emit a VSELECT that cannot be lowered into a blend.
6245 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6246 if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6249 // Odd-numbered elements in the input build vector are obtained from
6250 // adding two integer/float elements.
6251 // Even-numbered elements in the input build vector are obtained from
6252 // subtracting two integer/float elements.
6253 unsigned ExpectedOpcode = ISD::FSUB;
6254 unsigned NextExpectedOpcode = ISD::FADD;
6255 bool AddFound = false;
6256 bool SubFound = false;
6258 for (unsigned i = 0, e = NumElts; i != e; i++) {
6259 SDValue Op = BV->getOperand(i);
6261 // Skip 'undef' values.
6262 unsigned Opcode = Op.getOpcode();
6263 if (Opcode == ISD::UNDEF) {
6264 std::swap(ExpectedOpcode, NextExpectedOpcode);
6268 // Early exit if we found an unexpected opcode.
6269 if (Opcode != ExpectedOpcode)
6272 SDValue Op0 = Op.getOperand(0);
6273 SDValue Op1 = Op.getOperand(1);
6275 // Try to match the following pattern:
6276 // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6277 // Early exit if we cannot match that sequence.
6278 if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6279 Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6280 !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6281 !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6282 Op0.getOperand(1) != Op1.getOperand(1))
6285 unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6289 // We found a valid add/sub node. Update the information accordingly.
6295 // Update InVec0 and InVec1.
6296 if (InVec0.getOpcode() == ISD::UNDEF)
6297 InVec0 = Op0.getOperand(0);
6298 if (InVec1.getOpcode() == ISD::UNDEF)
6299 InVec1 = Op1.getOperand(0);
6301 // Make sure that operands in input to each add/sub node always
6302 // come from a same pair of vectors.
6303 if (InVec0 != Op0.getOperand(0)) {
6304 if (ExpectedOpcode == ISD::FSUB)
6307 // FADD is commutable. Try to commute the operands
6308 // and then test again.
6309 std::swap(Op0, Op1);
6310 if (InVec0 != Op0.getOperand(0))
6314 if (InVec1 != Op1.getOperand(0))
6317 // Update the pair of expected opcodes.
6318 std::swap(ExpectedOpcode, NextExpectedOpcode);
6321 // Don't try to fold this build_vector into a VSELECT if it has
6322 // too many UNDEF operands.
6323 if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6324 InVec1.getOpcode() != ISD::UNDEF) {
6325 // Emit a sequence of vector add and sub followed by a VSELECT.
6326 // The new VSELECT will be lowered into a BLENDI.
6327 // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6328 // and emit a single ADDSUB instruction.
6329 SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6330 SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6332 // Construct the VSELECT mask.
6333 EVT MaskVT = VT.changeVectorElementTypeToInteger();
6334 EVT SVT = MaskVT.getVectorElementType();
6335 unsigned SVTBits = SVT.getSizeInBits();
6336 SmallVector<SDValue, 8> Ops;
6338 for (unsigned i = 0, e = NumElts; i != e; ++i) {
6339 APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6340 APInt::getAllOnesValue(SVTBits);
6341 SDValue Constant = DAG.getConstant(Value, SVT);
6342 Ops.push_back(Constant);
6345 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6346 return DAG.getSelect(DL, VT, Mask, Sub, Add);
6352 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6353 const X86Subtarget *Subtarget) {
6355 EVT VT = N->getValueType(0);
6356 unsigned NumElts = VT.getVectorNumElements();
6357 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6358 SDValue InVec0, InVec1;
6360 // Try to match an ADDSUB.
6361 if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6362 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6363 SDValue Value = matchAddSub(BV, DAG, Subtarget);
6364 if (Value.getNode())
6368 // Try to match horizontal ADD/SUB.
6369 unsigned NumUndefsLO = 0;
6370 unsigned NumUndefsHI = 0;
6371 unsigned Half = NumElts/2;
6373 // Count the number of UNDEF operands in the build_vector in input.
6374 for (unsigned i = 0, e = Half; i != e; ++i)
6375 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6378 for (unsigned i = Half, e = NumElts; i != e; ++i)
6379 if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6382 // Early exit if this is either a build_vector of all UNDEFs or all the
6383 // operands but one are UNDEF.
6384 if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6387 if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6388 // Try to match an SSE3 float HADD/HSUB.
6389 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6390 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6392 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6393 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6394 } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6395 // Try to match an SSSE3 integer HADD/HSUB.
6396 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6397 return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6399 if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6400 return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6403 if (!Subtarget->hasAVX())
6406 if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6407 // Try to match an AVX horizontal add/sub of packed single/double
6408 // precision floating point values from 256-bit vectors.
6409 SDValue InVec2, InVec3;
6410 if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6411 isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6412 ((InVec0.getOpcode() == ISD::UNDEF ||
6413 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6414 ((InVec1.getOpcode() == ISD::UNDEF ||
6415 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6416 return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6418 if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6419 isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6420 ((InVec0.getOpcode() == ISD::UNDEF ||
6421 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6422 ((InVec1.getOpcode() == ISD::UNDEF ||
6423 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6424 return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6425 } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6426 // Try to match an AVX2 horizontal add/sub of signed integers.
6427 SDValue InVec2, InVec3;
6429 bool CanFold = true;
6431 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6432 isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6433 ((InVec0.getOpcode() == ISD::UNDEF ||
6434 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6435 ((InVec1.getOpcode() == ISD::UNDEF ||
6436 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6437 X86Opcode = X86ISD::HADD;
6438 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6439 isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6440 ((InVec0.getOpcode() == ISD::UNDEF ||
6441 InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6442 ((InVec1.getOpcode() == ISD::UNDEF ||
6443 InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6444 X86Opcode = X86ISD::HSUB;
6449 // Fold this build_vector into a single horizontal add/sub.
6450 // Do this only if the target has AVX2.
6451 if (Subtarget->hasAVX2())
6452 return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6454 // Do not try to expand this build_vector into a pair of horizontal
6455 // add/sub if we can emit a pair of scalar add/sub.
6456 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6459 // Convert this build_vector into a pair of horizontal binop followed by
6461 bool isUndefLO = NumUndefsLO == Half;
6462 bool isUndefHI = NumUndefsHI == Half;
6463 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6464 isUndefLO, isUndefHI);
6468 if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6469 VT == MVT::v16i16) && Subtarget->hasAVX()) {
6471 if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6472 X86Opcode = X86ISD::HADD;
6473 else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6474 X86Opcode = X86ISD::HSUB;
6475 else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6476 X86Opcode = X86ISD::FHADD;
6477 else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6478 X86Opcode = X86ISD::FHSUB;
6482 // Don't try to expand this build_vector into a pair of horizontal add/sub
6483 // if we can simply emit a pair of scalar add/sub.
6484 if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6487 // Convert this build_vector into two horizontal add/sub followed by
6489 bool isUndefLO = NumUndefsLO == Half;
6490 bool isUndefHI = NumUndefsHI == Half;
6491 return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6492 isUndefLO, isUndefHI);
6499 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6502 MVT VT = Op.getSimpleValueType();
6503 MVT ExtVT = VT.getVectorElementType();
6504 unsigned NumElems = Op.getNumOperands();
6506 // Generate vectors for predicate vectors.
6507 if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6508 return LowerBUILD_VECTORvXi1(Op, DAG);
6510 // Vectors containing all zeros can be matched by pxor and xorps later
6511 if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6512 // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6513 // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6514 if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6517 return getZeroVector(VT, Subtarget, DAG, dl);
6520 // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6521 // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6522 // vpcmpeqd on 256-bit vectors.
6523 if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6524 if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6527 if (!VT.is512BitVector())
6528 return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6531 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6532 if (Broadcast.getNode())
6535 unsigned EVTBits = ExtVT.getSizeInBits();
6537 unsigned NumZero = 0;
6538 unsigned NumNonZero = 0;
6539 unsigned NonZeros = 0;
6540 bool IsAllConstants = true;
6541 SmallSet<SDValue, 8> Values;
6542 for (unsigned i = 0; i < NumElems; ++i) {
6543 SDValue Elt = Op.getOperand(i);
6544 if (Elt.getOpcode() == ISD::UNDEF)
6547 if (Elt.getOpcode() != ISD::Constant &&
6548 Elt.getOpcode() != ISD::ConstantFP)
6549 IsAllConstants = false;
6550 if (X86::isZeroNode(Elt))
6553 NonZeros |= (1 << i);
6558 // All undef vector. Return an UNDEF. All zero vectors were handled above.
6559 if (NumNonZero == 0)
6560 return DAG.getUNDEF(VT);
6562 // Special case for single non-zero, non-undef, element.
6563 if (NumNonZero == 1) {
6564 unsigned Idx = countTrailingZeros(NonZeros);
6565 SDValue Item = Op.getOperand(Idx);
6567 // If this is an insertion of an i64 value on x86-32, and if the top bits of
6568 // the value are obviously zero, truncate the value to i32 and do the
6569 // insertion that way. Only do this if the value is non-constant or if the
6570 // value is a constant being inserted into element 0. It is cheaper to do
6571 // a constant pool load than it is to do a movd + shuffle.
6572 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6573 (!IsAllConstants || Idx == 0)) {
6574 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6576 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6577 EVT VecVT = MVT::v4i32;
6578 unsigned VecElts = 4;
6580 // Truncate the value (which may itself be a constant) to i32, and
6581 // convert it to a vector with movd (S2V+shuffle to zero extend).
6582 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6583 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6584 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6586 // Now we have our 32-bit value zero extended in the low element of
6587 // a vector. If Idx != 0, swizzle it into place.
6589 SmallVector<int, 4> Mask;
6590 Mask.push_back(Idx);
6591 for (unsigned i = 1; i != VecElts; ++i)
6593 Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6596 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6600 // If we have a constant or non-constant insertion into the low element of
6601 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6602 // the rest of the elements. This will be matched as movd/movq/movss/movsd
6603 // depending on what the source datatype is.
6606 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6608 if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6609 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6610 if (VT.is256BitVector() || VT.is512BitVector()) {
6611 SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6612 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6613 Item, DAG.getIntPtrConstant(0));
6615 assert(VT.is128BitVector() && "Expected an SSE value type!");
6616 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6617 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6618 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6621 if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6622 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6623 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6624 if (VT.is256BitVector()) {
6625 SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6626 Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6628 assert(VT.is128BitVector() && "Expected an SSE value type!");
6629 Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6631 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6635 // Is it a vector logical left shift?
6636 if (NumElems == 2 && Idx == 1 &&
6637 X86::isZeroNode(Op.getOperand(0)) &&
6638 !X86::isZeroNode(Op.getOperand(1))) {
6639 unsigned NumBits = VT.getSizeInBits();
6640 return getVShift(true, VT,
6641 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6642 VT, Op.getOperand(1)),
6643 NumBits/2, DAG, *this, dl);
6646 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6649 // Otherwise, if this is a vector with i32 or f32 elements, and the element
6650 // is a non-constant being inserted into an element other than the low one,
6651 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
6652 // movd/movss) to move this into the low element, then shuffle it into
6654 if (EVTBits == 32) {
6655 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6657 // Turn it into a shuffle of zero and zero-extended scalar to vector.
6658 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6659 SmallVector<int, 8> MaskVec;
6660 for (unsigned i = 0; i != NumElems; ++i)
6661 MaskVec.push_back(i == Idx ? 0 : 1);
6662 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6666 // Splat is obviously ok. Let legalizer expand it to a shuffle.
6667 if (Values.size() == 1) {
6668 if (EVTBits == 32) {
6669 // Instead of a shuffle like this:
6670 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6671 // Check if it's possible to issue this instead.
6672 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6673 unsigned Idx = countTrailingZeros(NonZeros);
6674 SDValue Item = Op.getOperand(Idx);
6675 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6676 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6681 // A vector full of immediates; various special cases are already
6682 // handled, so this is best done with a single constant-pool load.
6686 // For AVX-length vectors, build the individual 128-bit pieces and use
6687 // shuffles to put them in place.
6688 if (VT.is256BitVector() || VT.is512BitVector()) {
6689 SmallVector<SDValue, 64> V;
6690 for (unsigned i = 0; i != NumElems; ++i)
6691 V.push_back(Op.getOperand(i));
6693 EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6695 // Build both the lower and upper subvector.
6696 SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6697 makeArrayRef(&V[0], NumElems/2));
6698 SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6699 makeArrayRef(&V[NumElems / 2], NumElems/2));
6701 // Recreate the wider vector with the lower and upper part.
6702 if (VT.is256BitVector())
6703 return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6704 return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6707 // Let legalizer expand 2-wide build_vectors.
6708 if (EVTBits == 64) {
6709 if (NumNonZero == 1) {
6710 // One half is zero or undef.
6711 unsigned Idx = countTrailingZeros(NonZeros);
6712 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6713 Op.getOperand(Idx));
6714 return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6719 // If element VT is < 32 bits, convert it to inserts into a zero vector.
6720 if (EVTBits == 8 && NumElems == 16) {
6721 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6723 if (V.getNode()) return V;
6726 if (EVTBits == 16 && NumElems == 8) {
6727 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6729 if (V.getNode()) return V;
6732 // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6733 if (EVTBits == 32 && NumElems == 4) {
6734 SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6735 NumZero, DAG, Subtarget, *this);
6740 // If element VT is == 32 bits, turn it into a number of shuffles.
6741 SmallVector<SDValue, 8> V(NumElems);
6742 if (NumElems == 4 && NumZero > 0) {
6743 for (unsigned i = 0; i < 4; ++i) {
6744 bool isZero = !(NonZeros & (1 << i));
6746 V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6748 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6751 for (unsigned i = 0; i < 2; ++i) {
6752 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6755 V[i] = V[i*2]; // Must be a zero vector.
6758 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6761 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6764 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6769 bool Reverse1 = (NonZeros & 0x3) == 2;
6770 bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6774 static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6775 static_cast<int>(Reverse2 ? NumElems : NumElems+1)
6777 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6780 if (Values.size() > 1 && VT.is128BitVector()) {
6781 // Check for a build vector of consecutive loads.
6782 for (unsigned i = 0; i < NumElems; ++i)
6783 V[i] = Op.getOperand(i);
6785 // Check for elements which are consecutive loads.
6786 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6790 // Check for a build vector from mostly shuffle plus few inserting.
6791 SDValue Sh = buildFromShuffleMostly(Op, DAG);
6795 // For SSE 4.1, use insertps to put the high elements into the low element.
6796 if (getSubtarget()->hasSSE41()) {
6798 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6799 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6801 Result = DAG.getUNDEF(VT);
6803 for (unsigned i = 1; i < NumElems; ++i) {
6804 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6805 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6806 Op.getOperand(i), DAG.getIntPtrConstant(i));
6811 // Otherwise, expand into a number of unpckl*, start by extending each of
6812 // our (non-undef) elements to the full vector width with the element in the
6813 // bottom slot of the vector (which generates no code for SSE).
6814 for (unsigned i = 0; i < NumElems; ++i) {
6815 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6816 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6818 V[i] = DAG.getUNDEF(VT);
6821 // Next, we iteratively mix elements, e.g. for v4f32:
6822 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6823 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6824 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
6825 unsigned EltStride = NumElems >> 1;
6826 while (EltStride != 0) {
6827 for (unsigned i = 0; i < EltStride; ++i) {
6828 // If V[i+EltStride] is undef and this is the first round of mixing,
6829 // then it is safe to just drop this shuffle: V[i] is already in the
6830 // right place, the one element (since it's the first round) being
6831 // inserted as undef can be dropped. This isn't safe for successive
6832 // rounds because they will permute elements within both vectors.
6833 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6834 EltStride == NumElems/2)
6837 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6846 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6847 // to create 256-bit vectors from two other 128-bit ones.
6848 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6850 MVT ResVT = Op.getSimpleValueType();
6852 assert((ResVT.is256BitVector() ||
6853 ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6855 SDValue V1 = Op.getOperand(0);
6856 SDValue V2 = Op.getOperand(1);
6857 unsigned NumElems = ResVT.getVectorNumElements();
6858 if(ResVT.is256BitVector())
6859 return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6861 if (Op.getNumOperands() == 4) {
6862 MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6863 ResVT.getVectorNumElements()/2);
6864 SDValue V3 = Op.getOperand(2);
6865 SDValue V4 = Op.getOperand(3);
6866 return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6867 Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6869 return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6872 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6873 MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6874 assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6875 (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6876 Op.getNumOperands() == 4)));
6878 // AVX can use the vinsertf128 instruction to create 256-bit vectors
6879 // from two other 128-bit ones.
6881 // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6882 return LowerAVXCONCAT_VECTORS(Op, DAG);
6886 //===----------------------------------------------------------------------===//
6887 // Vector shuffle lowering
6889 // This is an experimental code path for lowering vector shuffles on x86. It is
6890 // designed to handle arbitrary vector shuffles and blends, gracefully
6891 // degrading performance as necessary. It works hard to recognize idiomatic
6892 // shuffles and lower them to optimal instruction patterns without leaving
6893 // a framework that allows reasonably efficient handling of all vector shuffle
6895 //===----------------------------------------------------------------------===//
6897 /// \brief Tiny helper function to identify a no-op mask.
6899 /// This is a somewhat boring predicate function. It checks whether the mask
6900 /// array input, which is assumed to be a single-input shuffle mask of the kind
6901 /// used by the X86 shuffle instructions (not a fully general
6902 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6903 /// in-place shuffle are 'no-op's.
6904 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6905 for (int i = 0, Size = Mask.size(); i < Size; ++i)
6906 if (Mask[i] != -1 && Mask[i] != i)
6911 /// \brief Helper function to classify a mask as a single-input mask.
6913 /// This isn't a generic single-input test because in the vector shuffle
6914 /// lowering we canonicalize single inputs to be the first input operand. This
6915 /// means we can more quickly test for a single input by only checking whether
6916 /// an input from the second operand exists. We also assume that the size of
6917 /// mask corresponds to the size of the input vectors which isn't true in the
6918 /// fully general case.
6919 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6921 if (M >= (int)Mask.size())
6926 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6928 /// This helper function produces an 8-bit shuffle immediate corresponding to
6929 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6930 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6933 /// NB: We rely heavily on "undef" masks preserving the input lane.
6934 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6935 SelectionDAG &DAG) {
6936 assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6937 assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6938 assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6939 assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6940 assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6943 Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6944 Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6945 Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6946 Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6947 return DAG.getConstant(Imm, MVT::i8);
6950 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6952 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6953 /// support for floating point shuffles but not integer shuffles. These
6954 /// instructions will incur a domain crossing penalty on some chips though so
6955 /// it is better to avoid lowering through this for integer vectors where
6957 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6958 const X86Subtarget *Subtarget,
6959 SelectionDAG &DAG) {
6961 assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6962 assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6963 assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6964 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6965 ArrayRef<int> Mask = SVOp->getMask();
6966 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6968 if (isSingleInputShuffleMask(Mask)) {
6969 // Straight shuffle of a single input vector. Simulate this by using the
6970 // single input as both of the "inputs" to this instruction..
6971 unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6972 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6973 DAG.getConstant(SHUFPDMask, MVT::i8));
6975 assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6976 assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6978 unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6979 return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6980 DAG.getConstant(SHUFPDMask, MVT::i8));
6983 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
6985 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
6986 /// the integer unit to minimize domain crossing penalties. However, for blends
6987 /// it falls back to the floating point shuffle operation with appropriate bit
6989 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6990 const X86Subtarget *Subtarget,
6991 SelectionDAG &DAG) {
6993 assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
6994 assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6995 assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6996 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6997 ArrayRef<int> Mask = SVOp->getMask();
6998 assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7000 if (isSingleInputShuffleMask(Mask)) {
7001 // Straight shuffle of a single input vector. For everything from SSE2
7002 // onward this has a single fast instruction with no scary immediates.
7003 // We have to map the mask as it is actually a v4i32 shuffle instruction.
7004 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7005 int WidenedMask[4] = {
7006 std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7007 std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7009 ISD::BITCAST, DL, MVT::v2i64,
7010 DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7011 getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7014 // We implement this with SHUFPD which is pretty lame because it will likely
7015 // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7016 // However, all the alternatives are still more cycles and newer chips don't
7017 // have this problem. It would be really nice if x86 had better shuffles here.
7018 V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7019 V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7020 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7021 DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7024 /// \brief Lower 4-lane 32-bit floating point shuffles.
7026 /// Uses instructions exclusively from the floating point unit to minimize
7027 /// domain crossing penalties, as these are sufficient to implement all v4f32
7029 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7030 const X86Subtarget *Subtarget,
7031 SelectionDAG &DAG) {
7033 assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7034 assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7035 assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7036 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7037 ArrayRef<int> Mask = SVOp->getMask();
7038 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7040 SDValue LowV = V1, HighV = V2;
7041 int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7044 std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7046 if (NumV2Elements == 0)
7047 // Straight shuffle of a single input vector. We pass the input vector to
7048 // both operands to simulate this with a SHUFPS.
7049 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7050 getV4X86ShuffleImm8ForMask(Mask, DAG));
7052 if (NumV2Elements == 1) {
7054 std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7056 // Compute the index adjacent to V2Index and in the same half by toggling
7058 int V2AdjIndex = V2Index ^ 1;
7060 if (Mask[V2AdjIndex] == -1) {
7061 // Handles all the cases where we have a single V2 element and an undef.
7062 // This will only ever happen in the high lanes because we commute the
7063 // vector otherwise.
7065 std::swap(LowV, HighV);
7066 NewMask[V2Index] -= 4;
7068 // Handle the case where the V2 element ends up adjacent to a V1 element.
7069 // To make this work, blend them together as the first step.
7070 int V1Index = V2AdjIndex;
7071 int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7072 V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7073 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7075 // Now proceed to reconstruct the final blend as we have the necessary
7076 // high or low half formed.
7083 NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7084 NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7086 } else if (NumV2Elements == 2) {
7087 if (Mask[0] < 4 && Mask[1] < 4) {
7088 // Handle the easy case where we have V1 in the low lanes and V2 in the
7089 // high lanes. We never see this reversed because we sort the shuffle.
7093 // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7094 // trying to place elements directly, just blend them and set up the final
7095 // shuffle to place them.
7097 // The first two blend mask elements are for V1, the second two are for
7099 int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7100 Mask[2] < 4 ? Mask[2] : Mask[3],
7101 (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7102 (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7103 V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7104 getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7106 // Now we do a normal shuffle of V1 by giving V1 as both operands to
7109 NewMask[0] = Mask[0] < 4 ? 0 : 2;
7110 NewMask[1] = Mask[0] < 4 ? 2 : 0;
7111 NewMask[2] = Mask[2] < 4 ? 1 : 3;
7112 NewMask[3] = Mask[2] < 4 ? 3 : 1;
7115 return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7116 getV4X86ShuffleImm8ForMask(NewMask, DAG));
7119 /// \brief Lower 4-lane i32 vector shuffles.
7121 /// We try to handle these with integer-domain shuffles where we can, but for
7122 /// blends we use the floating point domain blend instructions.
7123 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7124 const X86Subtarget *Subtarget,
7125 SelectionDAG &DAG) {
7127 assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7128 assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7129 assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7130 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7131 ArrayRef<int> Mask = SVOp->getMask();
7132 assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7134 if (isSingleInputShuffleMask(Mask))
7135 // Straight shuffle of a single input vector. For everything from SSE2
7136 // onward this has a single fast instruction with no scary immediates.
7137 return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7138 getV4X86ShuffleImm8ForMask(Mask, DAG));
7140 // We implement this with SHUFPS because it can blend from two vectors.
7141 // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7142 // up the inputs, bypassing domain shift penalties that we would encur if we
7143 // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7145 return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7146 DAG.getVectorShuffle(
7148 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7149 DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7152 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7153 /// shuffle lowering, and the most complex part.
7155 /// The lowering strategy is to try to form pairs of input lanes which are
7156 /// targeted at the same half of the final vector, and then use a dword shuffle
7157 /// to place them onto the right half, and finally unpack the paired lanes into
7158 /// their final position.
7160 /// The exact breakdown of how to form these dword pairs and align them on the
7161 /// correct sides is really tricky. See the comments within the function for
7162 /// more of the details.
7163 static SDValue lowerV8I16SingleInputVectorShuffle(
7164 SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7165 const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7166 assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7167 MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7168 MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7170 SmallVector<int, 4> LoInputs;
7171 std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7172 [](int M) { return M >= 0; });
7173 std::sort(LoInputs.begin(), LoInputs.end());
7174 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7175 SmallVector<int, 4> HiInputs;
7176 std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7177 [](int M) { return M >= 0; });
7178 std::sort(HiInputs.begin(), HiInputs.end());
7179 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7181 std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7182 int NumHToL = LoInputs.size() - NumLToL;
7184 std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7185 int NumHToH = HiInputs.size() - NumLToH;
7186 MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7187 MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7188 MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7189 MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7191 // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7192 // such inputs we can swap two of the dwords across the half mark and end up
7193 // with <=2 inputs to each half in each half. Once there, we can fall through
7194 // to the generic code below. For example:
7196 // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7197 // Mask: [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7199 // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7201 auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7202 int ThreeInputHalfSum, int OneInputHalfOffset) {
7203 // Compute the index of dword with only one word among the three inputs in
7204 // a half by taking the sum of the half with three inputs and subtracting
7205 // the sum of the actual three inputs. The difference is the remaining
7207 int DWordA = (ThreeInputHalfSum -
7208 std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7210 int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7212 int PSHUFDMask[] = {0, 1, 2, 3};
7213 PSHUFDMask[DWordA] = DWordB;
7214 PSHUFDMask[DWordB] = DWordA;
7215 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7216 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7217 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7218 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7220 // Adjust the mask to match the new locations of A and B.
7222 if (M != -1 && M/2 == DWordA)
7223 M = 2 * DWordB + M % 2;
7224 else if (M != -1 && M/2 == DWordB)
7225 M = 2 * DWordA + M % 2;
7227 // Recurse back into this routine to re-compute state now that this isn't
7228 // a 3 and 1 problem.
7229 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7232 if (NumLToL == 3 && NumHToL == 1)
7233 return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7234 else if (NumLToL == 1 && NumHToL == 3)
7235 return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7236 else if (NumLToH == 1 && NumHToH == 3)
7237 return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7238 else if (NumLToH == 3 && NumHToH == 1)
7239 return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7241 // At this point there are at most two inputs to the low and high halves from
7242 // each half. That means the inputs can always be grouped into dwords and
7243 // those dwords can then be moved to the correct half with a dword shuffle.
7244 // We use at most one low and one high word shuffle to collect these paired
7245 // inputs into dwords, and finally a dword shuffle to place them.
7246 int PSHUFLMask[4] = {-1, -1, -1, -1};
7247 int PSHUFHMask[4] = {-1, -1, -1, -1};
7248 int PSHUFDMask[4] = {-1, -1, -1, -1};
7250 // First fix the masks for all the inputs that are staying in their
7251 // original halves. This will then dictate the targets of the cross-half
7253 auto fixInPlaceInputs = [&PSHUFDMask](
7254 ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7255 MutableArrayRef<int> HalfMask, int HalfOffset) {
7256 if (InPlaceInputs.empty())
7258 if (InPlaceInputs.size() == 1) {
7259 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7260 InPlaceInputs[0] - HalfOffset;
7261 PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7265 assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7266 SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7267 InPlaceInputs[0] - HalfOffset;
7268 // Put the second input next to the first so that they are packed into
7269 // a dword. We find the adjacent index by toggling the low bit.
7270 int AdjIndex = InPlaceInputs[0] ^ 1;
7271 SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7272 std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7273 PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7275 if (!HToLInputs.empty())
7276 fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7277 if (!LToHInputs.empty())
7278 fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7280 // Now gather the cross-half inputs and place them into a free dword of
7281 // their target half.
7282 // FIXME: This operation could almost certainly be simplified dramatically to
7283 // look more like the 3-1 fixing operation.
7284 auto moveInputsToRightHalf = [&PSHUFDMask](
7285 MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7286 MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7287 int SourceOffset, int DestOffset) {
7288 auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7289 return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7291 auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7293 int LowWord = Word & ~1;
7294 int HighWord = Word | 1;
7295 return isWordClobbered(SourceHalfMask, LowWord) ||
7296 isWordClobbered(SourceHalfMask, HighWord);
7299 if (IncomingInputs.empty())
7302 if (ExistingInputs.empty()) {
7303 // Map any dwords with inputs from them into the right half.
7304 for (int Input : IncomingInputs) {
7305 // If the source half mask maps over the inputs, turn those into
7306 // swaps and use the swapped lane.
7307 if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7308 if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7309 SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7310 Input - SourceOffset;
7311 // We have to swap the uses in our half mask in one sweep.
7312 for (int &M : HalfMask)
7313 if (M == SourceHalfMask[Input - SourceOffset])
7315 else if (M == Input)
7316 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7318 assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7319 Input - SourceOffset &&
7320 "Previous placement doesn't match!");
7322 // Note that this correctly re-maps both when we do a swap and when
7323 // we observe the other side of the swap above. We rely on that to
7324 // avoid swapping the members of the input list directly.
7325 Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7328 // Map the input's dword into the correct half.
7329 if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7330 PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7332 assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7334 "Previous placement doesn't match!");
7337 // And just directly shift any other-half mask elements to be same-half
7338 // as we will have mirrored the dword containing the element into the
7339 // same position within that half.
7340 for (int &M : HalfMask)
7341 if (M >= SourceOffset && M < SourceOffset + 4) {
7342 M = M - SourceOffset + DestOffset;
7343 assert(M >= 0 && "This should never wrap below zero!");
7348 // Ensure we have the input in a viable dword of its current half. This
7349 // is particularly tricky because the original position may be clobbered
7350 // by inputs being moved and *staying* in that half.
7351 if (IncomingInputs.size() == 1) {
7352 if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7353 int InputFixed = std::find(std::begin(SourceHalfMask),
7354 std::end(SourceHalfMask), -1) -
7355 std::begin(SourceHalfMask) + SourceOffset;
7356 SourceHalfMask[InputFixed - SourceOffset] =
7357 IncomingInputs[0] - SourceOffset;
7358 std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7360 IncomingInputs[0] = InputFixed;
7362 } else if (IncomingInputs.size() == 2) {
7363 if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7364 isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7365 int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7366 assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7367 "Not all dwords can be clobbered!");
7368 SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7369 SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7370 for (int &M : HalfMask)
7371 if (M == IncomingInputs[0])
7372 M = SourceDWordBase + SourceOffset;
7373 else if (M == IncomingInputs[1])
7374 M = SourceDWordBase + 1 + SourceOffset;
7375 IncomingInputs[0] = SourceDWordBase + SourceOffset;
7376 IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7379 llvm_unreachable("Unhandled input size!");
7382 // Now hoist the DWord down to the right half.
7383 int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7384 assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7385 PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7386 for (int Input : IncomingInputs)
7387 std::replace(HalfMask.begin(), HalfMask.end(), Input,
7388 FreeDWord * 2 + Input % 2);
7390 moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7391 /*SourceOffset*/ 4, /*DestOffset*/ 0);
7392 moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7393 /*SourceOffset*/ 0, /*DestOffset*/ 4);
7395 // Now enact all the shuffles we've computed to move the inputs into their
7397 if (!isNoopShuffleMask(PSHUFLMask))
7398 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7399 getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7400 if (!isNoopShuffleMask(PSHUFHMask))
7401 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7402 getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7403 if (!isNoopShuffleMask(PSHUFDMask))
7404 V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7405 DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7406 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7407 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7409 // At this point, each half should contain all its inputs, and we can then
7410 // just shuffle them into their final position.
7411 assert(std::count_if(LoMask.begin(), LoMask.end(),
7412 [](int M) { return M >= 4; }) == 0 &&
7413 "Failed to lift all the high half inputs to the low mask!");
7414 assert(std::count_if(HiMask.begin(), HiMask.end(),
7415 [](int M) { return M >= 0 && M < 4; }) == 0 &&
7416 "Failed to lift all the low half inputs to the high mask!");
7418 // Do a half shuffle for the low mask.
7419 if (!isNoopShuffleMask(LoMask))
7420 V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7421 getV4X86ShuffleImm8ForMask(LoMask, DAG));
7423 // Do a half shuffle with the high mask after shifting its values down.
7424 for (int &M : HiMask)
7427 if (!isNoopShuffleMask(HiMask))
7428 V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7429 getV4X86ShuffleImm8ForMask(HiMask, DAG));
7434 /// \brief Detect whether the mask pattern should be lowered through
7437 /// This essentially tests whether viewing the mask as an interleaving of two
7438 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7439 /// lowering it through interleaving is a significantly better strategy.
7440 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7441 int NumEvenInputs[2] = {0, 0};
7442 int NumOddInputs[2] = {0, 0};
7443 int NumLoInputs[2] = {0, 0};
7444 int NumHiInputs[2] = {0, 0};
7445 for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7449 int InputIdx = Mask[i] >= Size;
7452 ++NumLoInputs[InputIdx];
7454 ++NumHiInputs[InputIdx];
7457 ++NumEvenInputs[InputIdx];
7459 ++NumOddInputs[InputIdx];
7462 // The minimum number of cross-input results for both the interleaved and
7463 // split cases. If interleaving results in fewer cross-input results, return
7465 int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7466 NumEvenInputs[0] + NumOddInputs[1]);
7467 int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7468 NumLoInputs[0] + NumHiInputs[1]);
7469 return InterleavedCrosses < SplitCrosses;
7472 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7474 /// This strategy only works when the inputs from each vector fit into a single
7475 /// half of that vector, and generally there are not so many inputs as to leave
7476 /// the in-place shuffles required highly constrained (and thus expensive). It
7477 /// shifts all the inputs into a single side of both input vectors and then
7478 /// uses an unpack to interleave these inputs in a single vector. At that
7479 /// point, we will fall back on the generic single input shuffle lowering.
7480 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7482 MutableArrayRef<int> Mask,
7483 const X86Subtarget *Subtarget,
7484 SelectionDAG &DAG) {
7485 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7486 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7487 SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7488 for (int i = 0; i < 8; ++i)
7489 if (Mask[i] >= 0 && Mask[i] < 4)
7490 LoV1Inputs.push_back(i);
7491 else if (Mask[i] >= 4 && Mask[i] < 8)
7492 HiV1Inputs.push_back(i);
7493 else if (Mask[i] >= 8 && Mask[i] < 12)
7494 LoV2Inputs.push_back(i);
7495 else if (Mask[i] >= 12)
7496 HiV2Inputs.push_back(i);
7498 int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7499 int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7502 assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7503 assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7504 assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7506 bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7507 HiV1Inputs.size() + HiV2Inputs.size();
7509 auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7510 ArrayRef<int> HiInputs, bool MoveToLo,
7512 ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7513 ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7514 if (BadInputs.empty())
7517 int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7518 int MoveOffset = MoveToLo ? 0 : 4;
7520 if (GoodInputs.empty()) {
7521 for (int BadInput : BadInputs) {
7522 MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7523 Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7526 if (GoodInputs.size() == 2) {
7527 // If the low inputs are spread across two dwords, pack them into
7529 MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7530 Mask[GoodInputs[0]] - MaskOffset;
7531 MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7532 Mask[GoodInputs[1]] - MaskOffset;
7533 Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7534 Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7536 // Otherwise pin the low inputs.
7537 for (int GoodInput : GoodInputs)
7538 MoveMask[Mask[GoodInput]] = Mask[GoodInput] - MaskOffset;
7542 std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7543 std::begin(MoveMask);
7544 assert(MoveMaskIdx >= MoveOffset && "Established above");
7546 if (BadInputs.size() == 2) {
7547 assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7548 assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7549 MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7550 Mask[BadInputs[0]] - MaskOffset;
7551 MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7552 Mask[BadInputs[1]] - MaskOffset;
7553 Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7554 Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7556 assert(BadInputs.size() == 1 && "All sizes handled");
7557 MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7558 Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7562 return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7565 V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7567 V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7570 // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7571 // cross-half traffic in the final shuffle.
7573 // Munge the mask to be a single-input mask after the unpack merges the
7577 M = 2 * (M % 4) + (M / 8);
7579 return DAG.getVectorShuffle(
7580 MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7581 DL, MVT::v8i16, V1, V2),
7582 DAG.getUNDEF(MVT::v8i16), Mask);
7585 /// \brief Generic lowering of 8-lane i16 shuffles.
7587 /// This handles both single-input shuffles and combined shuffle/blends with
7588 /// two inputs. The single input shuffles are immediately delegated to
7589 /// a dedicated lowering routine.
7591 /// The blends are lowered in one of three fundamental ways. If there are few
7592 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7593 /// of the input is significantly cheaper when lowered as an interleaving of
7594 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7595 /// halves of the inputs separately (making them have relatively few inputs)
7596 /// and then concatenate them.
7597 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7598 const X86Subtarget *Subtarget,
7599 SelectionDAG &DAG) {
7601 assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7602 assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7603 assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7604 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7605 ArrayRef<int> OrigMask = SVOp->getMask();
7606 int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7607 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7608 MutableArrayRef<int> Mask(MaskStorage);
7610 assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7612 auto isV1 = [](int M) { return M >= 0 && M < 8; };
7613 auto isV2 = [](int M) { return M >= 8; };
7615 int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7616 int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7618 if (NumV2Inputs == 0)
7619 return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7621 assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7622 "to be V1-input shuffles.");
7624 if (NumV1Inputs + NumV2Inputs <= 4)
7625 return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7627 // Check whether an interleaving lowering is likely to be more efficient.
7628 // This isn't perfect but it is a strong heuristic that tends to work well on
7629 // the kinds of shuffles that show up in practice.
7631 // FIXME: Handle 1x, 2x, and 4x interleaving.
7632 if (shouldLowerAsInterleaving(Mask)) {
7633 // FIXME: Figure out whether we should pack these into the low or high
7636 int EMask[8], OMask[8];
7637 for (int i = 0; i < 4; ++i) {
7638 EMask[i] = Mask[2*i];
7639 OMask[i] = Mask[2*i + 1];
7644 SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7645 SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7647 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7650 int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7651 int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7653 for (int i = 0; i < 4; ++i) {
7654 LoBlendMask[i] = Mask[i];
7655 HiBlendMask[i] = Mask[i + 4];
7658 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7659 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7660 LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7661 HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7663 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7664 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7667 /// \brief Generic lowering of v16i8 shuffles.
7669 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7670 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7671 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7672 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7674 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7675 const X86Subtarget *Subtarget,
7676 SelectionDAG &DAG) {
7678 assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7679 assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7680 assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7681 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7682 ArrayRef<int> OrigMask = SVOp->getMask();
7683 assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7684 int MaskStorage[16] = {
7685 OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7686 OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7],
7687 OrigMask[8], OrigMask[9], OrigMask[10], OrigMask[11],
7688 OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7689 MutableArrayRef<int> Mask(MaskStorage);
7690 MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7691 MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7693 // For single-input shuffles, there are some nicer lowering tricks we can use.
7694 if (isSingleInputShuffleMask(Mask)) {
7695 // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7696 // Notably, this handles splat and partial-splat shuffles more efficiently.
7698 // FIXME: We should check for other patterns which can be widened into an
7699 // i16 shuffle as well.
7700 auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7701 for (int i = 0; i < 16; i += 2) {
7702 if (Mask[i] != Mask[i + 1])
7707 if (canWidenViaDuplication(Mask)) {
7708 SmallVector<int, 4> LoInputs;
7709 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7710 [](int M) { return M >= 0 && M < 8; });
7711 std::sort(LoInputs.begin(), LoInputs.end());
7712 LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7714 SmallVector<int, 4> HiInputs;
7715 std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7716 [](int M) { return M >= 8; });
7717 std::sort(HiInputs.begin(), HiInputs.end());
7718 HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7721 bool TargetLo = LoInputs.size() >= HiInputs.size();
7722 ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7723 ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7726 SmallDenseMap<int, int, 8> LaneMap;
7727 for (int i = 0; i < 16; ++i)
7729 for (int I : InPlaceInputs) {
7733 int FreeByteIdx = 0;
7734 int TargetOffset = TargetLo ? 0 : 8;
7735 for (int I : MovingInputs) {
7736 // Walk the free index into the byte mask until we find an unoccupied
7737 // spot. We bound this to 8 steps to catch bugs, the pigeonhole
7738 // principle indicates that there *must* be a spot as we can only have
7739 // 8 duplicated inputs. We have to walk the index using modular
7740 // arithmetic to wrap around as necessary.
7741 // FIXME: We could do a much better job of picking an inexpensive slot
7742 // so this doesn't go through the worst case for the byte shuffle.
7743 for (int j = 0; j < 8 && ByteMask[FreeByteIdx + TargetOffset] != -1;
7744 ++j, FreeByteIdx = (FreeByteIdx + 1) % 8)
7746 assert(ByteMask[FreeByteIdx + TargetOffset] == -1 &&
7747 "Failed to find a free byte!");
7748 ByteMask[FreeByteIdx + TargetOffset] = I;
7749 LaneMap[I] = FreeByteIdx + TargetOffset;
7751 V1 = DAG.getVectorShuffle(MVT::v16i8, DL, V1, DAG.getUNDEF(MVT::v16i8),
7757 // Unpack the bytes to form the i16s that will be shuffled into place.
7758 V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7759 MVT::v16i8, V1, V1);
7761 int I16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7762 for (int i = 0; i < 16; i += 2) {
7764 I16Shuffle[i / 2] = Mask[i] - (TargetLo ? 0 : 8);
7765 assert(I16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7767 return DAG.getVectorShuffle(MVT::v8i16, DL,
7768 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7769 DAG.getUNDEF(MVT::v8i16), I16Shuffle);
7773 // Check whether an interleaving lowering is likely to be more efficient.
7774 // This isn't perfect but it is a strong heuristic that tends to work well on
7775 // the kinds of shuffles that show up in practice.
7777 // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7778 if (shouldLowerAsInterleaving(Mask)) {
7779 // FIXME: Figure out whether we should pack these into the low or high
7782 int EMask[16], OMask[16];
7783 for (int i = 0; i < 8; ++i) {
7784 EMask[i] = Mask[2*i];
7785 OMask[i] = Mask[2*i + 1];
7790 SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7791 SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7793 return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7795 SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7797 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7798 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, Zero));
7800 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7801 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, Zero));
7803 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7804 DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V2, Zero));
7806 DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7807 DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V2, Zero));
7809 int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7810 int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7811 int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7812 int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7814 auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7815 MutableArrayRef<int> V1HalfBlendMask,
7816 MutableArrayRef<int> V2HalfBlendMask) {
7817 for (int i = 0; i < 8; ++i)
7818 if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7819 V1HalfBlendMask[i] = HalfMask[i];
7821 } else if (HalfMask[i] >= 16) {
7822 V2HalfBlendMask[i] = HalfMask[i] - 16;
7823 HalfMask[i] = i + 8;
7826 buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7827 buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7829 SDValue V1Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1LoBlendMask);
7830 SDValue V2Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2LoBlendMask);
7831 SDValue V1Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1HiBlendMask);
7832 SDValue V2Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2HiBlendMask);
7834 SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7835 SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7837 return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7840 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7842 /// This routine breaks down the specific type of 128-bit shuffle and
7843 /// dispatches to the lowering routines accordingly.
7844 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7845 MVT VT, const X86Subtarget *Subtarget,
7846 SelectionDAG &DAG) {
7847 switch (VT.SimpleTy) {
7849 return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7851 return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7853 return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7855 return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7857 return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7859 return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7862 llvm_unreachable("Unimplemented!");
7866 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7867 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7868 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7869 if (Mask[i] + 1 != Mask[i+1])
7875 /// \brief Top-level lowering for x86 vector shuffles.
7877 /// This handles decomposition, canonicalization, and lowering of all x86
7878 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7879 /// above in helper routines. The canonicalization attempts to widen shuffles
7880 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7881 /// s.t. only one of the two inputs needs to be tested, etc.
7882 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7883 SelectionDAG &DAG) {
7884 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7885 ArrayRef<int> Mask = SVOp->getMask();
7886 SDValue V1 = Op.getOperand(0);
7887 SDValue V2 = Op.getOperand(1);
7888 MVT VT = Op.getSimpleValueType();
7889 int NumElements = VT.getVectorNumElements();
7892 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7894 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7895 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7896 if (V1IsUndef && V2IsUndef)
7897 return DAG.getUNDEF(VT);
7899 // When we create a shuffle node we put the UNDEF node to second operand,
7900 // but in some cases the first operand may be transformed to UNDEF.
7901 // In this case we should just commute the node.
7903 return CommuteVectorShuffle(SVOp, DAG);
7905 // Check for non-undef masks pointing at an undef vector and make the masks
7906 // undef as well. This makes it easier to match the shuffle based solely on
7910 if (M >= NumElements) {
7911 SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7912 for (int &M : NewMask)
7913 if (M >= NumElements)
7915 return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7918 // For integer vector shuffles, try to collapse them into a shuffle of fewer
7919 // lanes but wider integers. We cap this to not form integers larger than i64
7920 // but it might be interesting to form i128 integers to handle flipping the
7921 // low and high halves of AVX 256-bit vectors.
7922 if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7923 areAdjacentMasksSequential(Mask)) {
7924 SmallVector<int, 8> NewMask;
7925 for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7926 NewMask.push_back(Mask[i] / 2);
7928 MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7929 VT.getVectorNumElements() / 2);
7930 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7931 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7932 return DAG.getNode(ISD::BITCAST, dl, VT,
7933 DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7936 int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7937 for (int M : SVOp->getMask())
7940 else if (M < NumElements)
7945 // Commute the shuffle as needed such that more elements come from V1 than
7946 // V2. This allows us to match the shuffle pattern strictly on how many
7947 // elements come from V1 without handling the symmetric cases.
7948 if (NumV2Elements > NumV1Elements)
7949 return CommuteVectorShuffle(SVOp, DAG);
7951 // When the number of V1 and V2 elements are the same, try to minimize the
7952 // number of uses of V2 in the low half of the vector.
7953 if (NumV1Elements == NumV2Elements) {
7954 int LowV1Elements = 0, LowV2Elements = 0;
7955 for (int M : SVOp->getMask().slice(0, NumElements / 2))
7956 if (M >= NumElements)
7960 if (LowV2Elements > LowV1Elements)
7961 return CommuteVectorShuffle(SVOp, DAG);
7964 // For each vector width, delegate to a specialized lowering routine.
7965 if (VT.getSizeInBits() == 128)
7966 return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
7968 llvm_unreachable("Unimplemented!");
7972 //===----------------------------------------------------------------------===//
7973 // Legacy vector shuffle lowering
7975 // This code is the legacy code handling vector shuffles until the above
7976 // replaces its functionality and performance.
7977 //===----------------------------------------------------------------------===//
7979 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
7980 bool hasInt256, unsigned *MaskOut = nullptr) {
7981 MVT EltVT = VT.getVectorElementType();
7983 // There is no blend with immediate in AVX-512.
7984 if (VT.is512BitVector())
7987 if (!hasSSE41 || EltVT == MVT::i8)
7989 if (!hasInt256 && VT == MVT::v16i16)
7992 unsigned MaskValue = 0;
7993 unsigned NumElems = VT.getVectorNumElements();
7994 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
7995 unsigned NumLanes = (NumElems - 1) / 8 + 1;
7996 unsigned NumElemsInLane = NumElems / NumLanes;
7998 // Blend for v16i16 should be symetric for the both lanes.
7999 for (unsigned i = 0; i < NumElemsInLane; ++i) {
8001 int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8002 int EltIdx = MaskVals[i];
8004 if ((EltIdx < 0 || EltIdx == (int)i) &&
8005 (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8008 if (((unsigned)EltIdx == (i + NumElems)) &&
8009 (SndLaneEltIdx < 0 ||
8010 (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8011 MaskValue |= (1 << i);
8017 *MaskOut = MaskValue;
8021 // Try to lower a shuffle node into a simple blend instruction.
8022 // This function assumes isBlendMask returns true for this
8023 // SuffleVectorSDNode
8024 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8026 const X86Subtarget *Subtarget,
8027 SelectionDAG &DAG) {
8028 MVT VT = SVOp->getSimpleValueType(0);
8029 MVT EltVT = VT.getVectorElementType();
8030 assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8031 Subtarget->hasInt256() && "Trying to lower a "
8032 "VECTOR_SHUFFLE to a Blend but "
8033 "with the wrong mask"));
8034 SDValue V1 = SVOp->getOperand(0);
8035 SDValue V2 = SVOp->getOperand(1);
8037 unsigned NumElems = VT.getVectorNumElements();
8039 // Convert i32 vectors to floating point if it is not AVX2.
8040 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8042 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8043 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8045 V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8046 V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8049 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8050 DAG.getConstant(MaskValue, MVT::i32));
8051 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8054 /// In vector type \p VT, return true if the element at index \p InputIdx
8055 /// falls on a different 128-bit lane than \p OutputIdx.
8056 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8057 unsigned OutputIdx) {
8058 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8059 return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8062 /// Generate a PSHUFB if possible. Selects elements from \p V1 according to
8063 /// \p MaskVals. MaskVals[OutputIdx] = InputIdx specifies that we want to
8064 /// shuffle the element at InputIdx in V1 to OutputIdx in the result. If \p
8065 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8067 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8068 SelectionDAG &DAG) {
8069 MVT VT = V1.getSimpleValueType();
8070 assert(VT.is128BitVector() || VT.is256BitVector());
8072 MVT EltVT = VT.getVectorElementType();
8073 unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8074 unsigned NumElts = VT.getVectorNumElements();
8076 SmallVector<SDValue, 32> PshufbMask;
8077 for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8078 int InputIdx = MaskVals[OutputIdx];
8079 unsigned InputByteIdx;
8081 if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8082 InputByteIdx = 0x80;
8084 // Cross lane is not allowed.
8085 if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8087 InputByteIdx = InputIdx * EltSizeInBytes;
8088 // Index is an byte offset within the 128-bit lane.
8089 InputByteIdx &= 0xf;
8092 for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8093 PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8094 if (InputByteIdx != 0x80)
8099 MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8101 V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8102 return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8103 DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8106 // v8i16 shuffles - Prefer shuffles in the following order:
8107 // 1. [all] pshuflw, pshufhw, optional move
8108 // 2. [ssse3] 1 x pshufb
8109 // 3. [ssse3] 2 x pshufb + 1 x por
8110 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8112 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8113 SelectionDAG &DAG) {
8114 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8115 SDValue V1 = SVOp->getOperand(0);
8116 SDValue V2 = SVOp->getOperand(1);
8118 SmallVector<int, 8> MaskVals;
8120 // Determine if more than 1 of the words in each of the low and high quadwords
8121 // of the result come from the same quadword of one of the two inputs. Undef
8122 // mask values count as coming from any quadword, for better codegen.
8124 // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8125 // feeds this quad. For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8126 unsigned LoQuad[] = { 0, 0, 0, 0 };
8127 unsigned HiQuad[] = { 0, 0, 0, 0 };
8128 // Indices of quads used.
8129 std::bitset<4> InputQuads;
8130 for (unsigned i = 0; i < 8; ++i) {
8131 unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8132 int EltIdx = SVOp->getMaskElt(i);
8133 MaskVals.push_back(EltIdx);
8142 InputQuads.set(EltIdx / 4);
8145 int BestLoQuad = -1;
8146 unsigned MaxQuad = 1;
8147 for (unsigned i = 0; i < 4; ++i) {
8148 if (LoQuad[i] > MaxQuad) {
8150 MaxQuad = LoQuad[i];
8154 int BestHiQuad = -1;
8156 for (unsigned i = 0; i < 4; ++i) {
8157 if (HiQuad[i] > MaxQuad) {
8159 MaxQuad = HiQuad[i];
8163 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8164 // of the two input vectors, shuffle them into one input vector so only a
8165 // single pshufb instruction is necessary. If there are more than 2 input
8166 // quads, disable the next transformation since it does not help SSSE3.
8167 bool V1Used = InputQuads[0] || InputQuads[1];
8168 bool V2Used = InputQuads[2] || InputQuads[3];
8169 if (Subtarget->hasSSSE3()) {
8170 if (InputQuads.count() == 2 && V1Used && V2Used) {
8171 BestLoQuad = InputQuads[0] ? 0 : 1;
8172 BestHiQuad = InputQuads[2] ? 2 : 3;
8174 if (InputQuads.count() > 2) {
8180 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8181 // the shuffle mask. If a quad is scored as -1, that means that it contains
8182 // words from all 4 input quadwords.
8184 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8186 BestLoQuad < 0 ? 0 : BestLoQuad,
8187 BestHiQuad < 0 ? 1 : BestHiQuad
8189 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8190 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8191 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8192 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8194 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8195 // source words for the shuffle, to aid later transformations.
8196 bool AllWordsInNewV = true;
8197 bool InOrder[2] = { true, true };
8198 for (unsigned i = 0; i != 8; ++i) {
8199 int idx = MaskVals[i];
8201 InOrder[i/4] = false;
8202 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8204 AllWordsInNewV = false;
8208 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8209 if (AllWordsInNewV) {
8210 for (int i = 0; i != 8; ++i) {
8211 int idx = MaskVals[i];
8214 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8215 if ((idx != i) && idx < 4)
8217 if ((idx != i) && idx > 3)
8226 // If we've eliminated the use of V2, and the new mask is a pshuflw or
8227 // pshufhw, that's as cheap as it gets. Return the new shuffle.
8228 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8229 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8230 unsigned TargetMask = 0;
8231 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8232 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8233 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8234 TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8235 getShufflePSHUFLWImmediate(SVOp);
8236 V1 = NewV.getOperand(0);
8237 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8241 // Promote splats to a larger type which usually leads to more efficient code.
8242 // FIXME: Is this true if pshufb is available?
8243 if (SVOp->isSplat())
8244 return PromoteSplat(SVOp, DAG);
8246 // If we have SSSE3, and all words of the result are from 1 input vector,
8247 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
8248 // is present, fall back to case 4.
8249 if (Subtarget->hasSSSE3()) {
8250 SmallVector<SDValue,16> pshufbMask;
8252 // If we have elements from both input vectors, set the high bit of the
8253 // shuffle mask element to zero out elements that come from V2 in the V1
8254 // mask, and elements that come from V1 in the V2 mask, so that the two
8255 // results can be OR'd together.
8256 bool TwoInputs = V1Used && V2Used;
8257 V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8259 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8261 // Calculate the shuffle mask for the second input, shuffle it, and
8262 // OR it with the first shuffled input.
8263 CommuteVectorShuffleMask(MaskVals, 8);
8264 V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8265 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8266 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8269 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8270 // and update MaskVals with new element order.
8271 std::bitset<8> InOrder;
8272 if (BestLoQuad >= 0) {
8273 int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8274 for (int i = 0; i != 4; ++i) {
8275 int idx = MaskVals[i];
8278 } else if ((idx / 4) == BestLoQuad) {
8283 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8286 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8287 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8288 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8290 getShufflePSHUFLWImmediate(SVOp), DAG);
8294 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8295 // and update MaskVals with the new element order.
8296 if (BestHiQuad >= 0) {
8297 int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8298 for (unsigned i = 4; i != 8; ++i) {
8299 int idx = MaskVals[i];
8302 } else if ((idx / 4) == BestHiQuad) {
8303 MaskV[i] = (idx & 3) + 4;
8307 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8310 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8311 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8312 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8314 getShufflePSHUFHWImmediate(SVOp), DAG);
8318 // In case BestHi & BestLo were both -1, which means each quadword has a word
8319 // from each of the four input quadwords, calculate the InOrder bitvector now
8320 // before falling through to the insert/extract cleanup.
8321 if (BestLoQuad == -1 && BestHiQuad == -1) {
8323 for (int i = 0; i != 8; ++i)
8324 if (MaskVals[i] < 0 || MaskVals[i] == i)
8328 // The other elements are put in the right place using pextrw and pinsrw.
8329 for (unsigned i = 0; i != 8; ++i) {
8332 int EltIdx = MaskVals[i];
8335 SDValue ExtOp = (EltIdx < 8) ?
8336 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8337 DAG.getIntPtrConstant(EltIdx)) :
8338 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8339 DAG.getIntPtrConstant(EltIdx - 8));
8340 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8341 DAG.getIntPtrConstant(i));
8346 /// \brief v16i16 shuffles
8348 /// FIXME: We only support generation of a single pshufb currently. We can
8349 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8350 /// well (e.g 2 x pshufb + 1 x por).
8352 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8353 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8354 SDValue V1 = SVOp->getOperand(0);
8355 SDValue V2 = SVOp->getOperand(1);
8358 if (V2.getOpcode() != ISD::UNDEF)
8361 SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8362 return getPSHUFB(MaskVals, V1, dl, DAG);
8365 // v16i8 shuffles - Prefer shuffles in the following order:
8366 // 1. [ssse3] 1 x pshufb
8367 // 2. [ssse3] 2 x pshufb + 1 x por
8368 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
8369 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8370 const X86Subtarget* Subtarget,
8371 SelectionDAG &DAG) {
8372 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8373 SDValue V1 = SVOp->getOperand(0);
8374 SDValue V2 = SVOp->getOperand(1);
8376 ArrayRef<int> MaskVals = SVOp->getMask();
8378 // Promote splats to a larger type which usually leads to more efficient code.
8379 // FIXME: Is this true if pshufb is available?
8380 if (SVOp->isSplat())
8381 return PromoteSplat(SVOp, DAG);
8383 // If we have SSSE3, case 1 is generated when all result bytes come from
8384 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
8385 // present, fall back to case 3.
8387 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8388 if (Subtarget->hasSSSE3()) {
8389 SmallVector<SDValue,16> pshufbMask;
8391 // If all result elements are from one input vector, then only translate
8392 // undef mask values to 0x80 (zero out result) in the pshufb mask.
8394 // Otherwise, we have elements from both input vectors, and must zero out
8395 // elements that come from V2 in the first mask, and V1 in the second mask
8396 // so that we can OR them together.
8397 for (unsigned i = 0; i != 16; ++i) {
8398 int EltIdx = MaskVals[i];
8399 if (EltIdx < 0 || EltIdx >= 16)
8401 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8403 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8404 DAG.getNode(ISD::BUILD_VECTOR, dl,
8405 MVT::v16i8, pshufbMask));
8407 // As PSHUFB will zero elements with negative indices, it's safe to ignore
8408 // the 2nd operand if it's undefined or zero.
8409 if (V2.getOpcode() == ISD::UNDEF ||
8410 ISD::isBuildVectorAllZeros(V2.getNode()))
8413 // Calculate the shuffle mask for the second input, shuffle it, and
8414 // OR it with the first shuffled input.
8416 for (unsigned i = 0; i != 16; ++i) {
8417 int EltIdx = MaskVals[i];
8418 EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8419 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8421 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8422 DAG.getNode(ISD::BUILD_VECTOR, dl,
8423 MVT::v16i8, pshufbMask));
8424 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8427 // No SSSE3 - Calculate in place words and then fix all out of place words
8428 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
8429 // the 16 different words that comprise the two doublequadword input vectors.
8430 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8431 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8433 for (int i = 0; i != 8; ++i) {
8434 int Elt0 = MaskVals[i*2];
8435 int Elt1 = MaskVals[i*2+1];
8437 // This word of the result is all undef, skip it.
8438 if (Elt0 < 0 && Elt1 < 0)
8441 // This word of the result is already in the correct place, skip it.
8442 if ((Elt0 == i*2) && (Elt1 == i*2+1))
8445 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8446 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8449 // If Elt0 and Elt1 are defined, are consecutive, and can be load
8450 // using a single extract together, load it and store it.
8451 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8452 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8453 DAG.getIntPtrConstant(Elt1 / 2));
8454 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8455 DAG.getIntPtrConstant(i));
8459 // If Elt1 is defined, extract it from the appropriate source. If the
8460 // source byte is not also odd, shift the extracted word left 8 bits
8461 // otherwise clear the bottom 8 bits if we need to do an or.
8463 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8464 DAG.getIntPtrConstant(Elt1 / 2));
8465 if ((Elt1 & 1) == 0)
8466 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8468 TLI.getShiftAmountTy(InsElt.getValueType())));
8470 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8471 DAG.getConstant(0xFF00, MVT::i16));
8473 // If Elt0 is defined, extract it from the appropriate source. If the
8474 // source byte is not also even, shift the extracted word right 8 bits. If
8475 // Elt1 was also defined, OR the extracted values together before
8476 // inserting them in the result.
8478 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8479 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8480 if ((Elt0 & 1) != 0)
8481 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8483 TLI.getShiftAmountTy(InsElt0.getValueType())));
8485 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8486 DAG.getConstant(0x00FF, MVT::i16));
8487 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8490 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8491 DAG.getIntPtrConstant(i));
8493 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8496 // v32i8 shuffles - Translate to VPSHUFB if possible.
8498 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8499 const X86Subtarget *Subtarget,
8500 SelectionDAG &DAG) {
8501 MVT VT = SVOp->getSimpleValueType(0);
8502 SDValue V1 = SVOp->getOperand(0);
8503 SDValue V2 = SVOp->getOperand(1);
8505 SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8507 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8508 bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8509 bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8511 // VPSHUFB may be generated if
8512 // (1) one of input vector is undefined or zeroinitializer.
8513 // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8514 // And (2) the mask indexes don't cross the 128-bit lane.
8515 if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8516 (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8519 if (V1IsAllZero && !V2IsAllZero) {
8520 CommuteVectorShuffleMask(MaskVals, 32);
8523 return getPSHUFB(MaskVals, V1, dl, DAG);
8526 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8527 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8528 /// done when every pair / quad of shuffle mask elements point to elements in
8529 /// the right sequence. e.g.
8530 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8532 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8533 SelectionDAG &DAG) {
8534 MVT VT = SVOp->getSimpleValueType(0);
8536 unsigned NumElems = VT.getVectorNumElements();
8539 switch (VT.SimpleTy) {
8540 default: llvm_unreachable("Unexpected!");
8543 return SDValue(SVOp, 0);
8544 case MVT::v4f32: NewVT = MVT::v2f64; Scale = 2; break;
8545 case MVT::v4i32: NewVT = MVT::v2i64; Scale = 2; break;
8546 case MVT::v8i16: NewVT = MVT::v4i32; Scale = 2; break;
8547 case MVT::v16i8: NewVT = MVT::v4i32; Scale = 4; break;
8548 case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8549 case MVT::v32i8: NewVT = MVT::v8i32; Scale = 4; break;
8552 SmallVector<int, 8> MaskVec;
8553 for (unsigned i = 0; i != NumElems; i += Scale) {
8555 for (unsigned j = 0; j != Scale; ++j) {
8556 int EltIdx = SVOp->getMaskElt(i+j);
8560 StartIdx = (EltIdx / Scale);
8561 if (EltIdx != (int)(StartIdx*Scale + j))
8564 MaskVec.push_back(StartIdx);
8567 SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8568 SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8569 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8572 /// getVZextMovL - Return a zero-extending vector move low node.
8574 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8575 SDValue SrcOp, SelectionDAG &DAG,
8576 const X86Subtarget *Subtarget, SDLoc dl) {
8577 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8578 LoadSDNode *LD = nullptr;
8579 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8580 LD = dyn_cast<LoadSDNode>(SrcOp);
8582 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8584 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8585 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8586 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8587 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8588 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8590 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8591 return DAG.getNode(ISD::BITCAST, dl, VT,
8592 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8593 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8601 return DAG.getNode(ISD::BITCAST, dl, VT,
8602 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8603 DAG.getNode(ISD::BITCAST, dl,
8607 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8608 /// which could not be matched by any known target speficic shuffle
8610 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8612 SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8613 if (NewOp.getNode())
8616 MVT VT = SVOp->getSimpleValueType(0);
8618 unsigned NumElems = VT.getVectorNumElements();
8619 unsigned NumLaneElems = NumElems / 2;
8622 MVT EltVT = VT.getVectorElementType();
8623 MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8626 SmallVector<int, 16> Mask;
8627 for (unsigned l = 0; l < 2; ++l) {
8628 // Build a shuffle mask for the output, discovering on the fly which
8629 // input vectors to use as shuffle operands (recorded in InputUsed).
8630 // If building a suitable shuffle vector proves too hard, then bail
8631 // out with UseBuildVector set.
8632 bool UseBuildVector = false;
8633 int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8634 unsigned LaneStart = l * NumLaneElems;
8635 for (unsigned i = 0; i != NumLaneElems; ++i) {
8636 // The mask element. This indexes into the input.
8637 int Idx = SVOp->getMaskElt(i+LaneStart);
8639 // the mask element does not index into any input vector.
8644 // The input vector this mask element indexes into.
8645 int Input = Idx / NumLaneElems;
8647 // Turn the index into an offset from the start of the input vector.
8648 Idx -= Input * NumLaneElems;
8650 // Find or create a shuffle vector operand to hold this input.
8652 for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8653 if (InputUsed[OpNo] == Input)
8654 // This input vector is already an operand.
8656 if (InputUsed[OpNo] < 0) {
8657 // Create a new operand for this input vector.
8658 InputUsed[OpNo] = Input;
8663 if (OpNo >= array_lengthof(InputUsed)) {
8664 // More than two input vectors used! Give up on trying to create a
8665 // shuffle vector. Insert all elements into a BUILD_VECTOR instead.
8666 UseBuildVector = true;
8670 // Add the mask index for the new shuffle vector.
8671 Mask.push_back(Idx + OpNo * NumLaneElems);
8674 if (UseBuildVector) {
8675 SmallVector<SDValue, 16> SVOps;
8676 for (unsigned i = 0; i != NumLaneElems; ++i) {
8677 // The mask element. This indexes into the input.
8678 int Idx = SVOp->getMaskElt(i+LaneStart);
8680 SVOps.push_back(DAG.getUNDEF(EltVT));
8684 // The input vector this mask element indexes into.
8685 int Input = Idx / NumElems;
8687 // Turn the index into an offset from the start of the input vector.
8688 Idx -= Input * NumElems;
8690 // Extract the vector element by hand.
8691 SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8692 SVOp->getOperand(Input),
8693 DAG.getIntPtrConstant(Idx)));
8696 // Construct the output using a BUILD_VECTOR.
8697 Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8698 } else if (InputUsed[0] < 0) {
8699 // No input vectors were used! The result is undefined.
8700 Output[l] = DAG.getUNDEF(NVT);
8702 SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8703 (InputUsed[0] % 2) * NumLaneElems,
8705 // If only one input was used, use an undefined vector for the other.
8706 SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8707 Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8708 (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8709 // At least one input vector was used. Create a new shuffle vector.
8710 Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8716 // Concatenate the result back
8717 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8720 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8721 /// 4 elements, and match them with several different shuffle types.
8723 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8724 SDValue V1 = SVOp->getOperand(0);
8725 SDValue V2 = SVOp->getOperand(1);
8727 MVT VT = SVOp->getSimpleValueType(0);
8729 assert(VT.is128BitVector() && "Unsupported vector size");
8731 std::pair<int, int> Locs[4];
8732 int Mask1[] = { -1, -1, -1, -1 };
8733 SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8737 for (unsigned i = 0; i != 4; ++i) {
8738 int Idx = PermMask[i];
8740 Locs[i] = std::make_pair(-1, -1);
8742 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8744 Locs[i] = std::make_pair(0, NumLo);
8748 Locs[i] = std::make_pair(1, NumHi);
8750 Mask1[2+NumHi] = Idx;
8756 if (NumLo <= 2 && NumHi <= 2) {
8757 // If no more than two elements come from either vector. This can be
8758 // implemented with two shuffles. First shuffle gather the elements.
8759 // The second shuffle, which takes the first shuffle as both of its
8760 // vector operands, put the elements into the right order.
8761 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8763 int Mask2[] = { -1, -1, -1, -1 };
8765 for (unsigned i = 0; i != 4; ++i)
8766 if (Locs[i].first != -1) {
8767 unsigned Idx = (i < 2) ? 0 : 4;
8768 Idx += Locs[i].first * 2 + Locs[i].second;
8772 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8775 if (NumLo == 3 || NumHi == 3) {
8776 // Otherwise, we must have three elements from one vector, call it X, and
8777 // one element from the other, call it Y. First, use a shufps to build an
8778 // intermediate vector with the one element from Y and the element from X
8779 // that will be in the same half in the final destination (the indexes don't
8780 // matter). Then, use a shufps to build the final vector, taking the half
8781 // containing the element from Y from the intermediate, and the other half
8784 // Normalize it so the 3 elements come from V1.
8785 CommuteVectorShuffleMask(PermMask, 4);
8789 // Find the element from V2.
8791 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8792 int Val = PermMask[HiIndex];
8799 Mask1[0] = PermMask[HiIndex];
8801 Mask1[2] = PermMask[HiIndex^1];
8803 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8806 Mask1[0] = PermMask[0];
8807 Mask1[1] = PermMask[1];
8808 Mask1[2] = HiIndex & 1 ? 6 : 4;
8809 Mask1[3] = HiIndex & 1 ? 4 : 6;
8810 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8813 Mask1[0] = HiIndex & 1 ? 2 : 0;
8814 Mask1[1] = HiIndex & 1 ? 0 : 2;
8815 Mask1[2] = PermMask[2];
8816 Mask1[3] = PermMask[3];
8821 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8824 // Break it into (shuffle shuffle_hi, shuffle_lo).
8825 int LoMask[] = { -1, -1, -1, -1 };
8826 int HiMask[] = { -1, -1, -1, -1 };
8828 int *MaskPtr = LoMask;
8829 unsigned MaskIdx = 0;
8832 for (unsigned i = 0; i != 4; ++i) {
8839 int Idx = PermMask[i];
8841 Locs[i] = std::make_pair(-1, -1);
8842 } else if (Idx < 4) {
8843 Locs[i] = std::make_pair(MaskIdx, LoIdx);
8844 MaskPtr[LoIdx] = Idx;
8847 Locs[i] = std::make_pair(MaskIdx, HiIdx);
8848 MaskPtr[HiIdx] = Idx;
8853 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8854 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8855 int MaskOps[] = { -1, -1, -1, -1 };
8856 for (unsigned i = 0; i != 4; ++i)
8857 if (Locs[i].first != -1)
8858 MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8859 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8862 static bool MayFoldVectorLoad(SDValue V) {
8863 while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8864 V = V.getOperand(0);
8866 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8867 V = V.getOperand(0);
8868 if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8869 V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8870 // BUILD_VECTOR (load), undef
8871 V = V.getOperand(0);
8873 return MayFoldLoad(V);
8877 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8878 MVT VT = Op.getSimpleValueType();
8880 // Canonizalize to v2f64.
8881 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8882 return DAG.getNode(ISD::BITCAST, dl, VT,
8883 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8888 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8890 SDValue V1 = Op.getOperand(0);
8891 SDValue V2 = Op.getOperand(1);
8892 MVT VT = Op.getSimpleValueType();
8894 assert(VT != MVT::v2i64 && "unsupported shuffle type");
8896 if (HasSSE2 && VT == MVT::v2f64)
8897 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8899 // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8900 return DAG.getNode(ISD::BITCAST, dl, VT,
8901 getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8902 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8903 DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8907 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8908 SDValue V1 = Op.getOperand(0);
8909 SDValue V2 = Op.getOperand(1);
8910 MVT VT = Op.getSimpleValueType();
8912 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8913 "unsupported shuffle type");
8915 if (V2.getOpcode() == ISD::UNDEF)
8919 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8923 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8924 SDValue V1 = Op.getOperand(0);
8925 SDValue V2 = Op.getOperand(1);
8926 MVT VT = Op.getSimpleValueType();
8927 unsigned NumElems = VT.getVectorNumElements();
8929 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8930 // operand of these instructions is only memory, so check if there's a
8931 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8933 bool CanFoldLoad = false;
8935 // Trivial case, when V2 comes from a load.
8936 if (MayFoldVectorLoad(V2))
8939 // When V1 is a load, it can be folded later into a store in isel, example:
8940 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8942 // (MOVLPSmr addr:$src1, VR128:$src2)
8943 // So, recognize this potential and also use MOVLPS or MOVLPD
8944 else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8947 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8949 if (HasSSE2 && NumElems == 2)
8950 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
8953 // If we don't care about the second element, proceed to use movss.
8954 if (SVOp->getMaskElt(1) != -1)
8955 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
8958 // movl and movlp will both match v2i64, but v2i64 is never matched by
8959 // movl earlier because we make it strict to avoid messing with the movlp load
8960 // folding logic (see the code above getMOVLP call). Match it here then,
8961 // this is horrible, but will stay like this until we move all shuffle
8962 // matching to x86 specific nodes. Note that for the 1st condition all
8963 // types are matched with movsd.
8965 // FIXME: isMOVLMask should be checked and matched before getMOVLP,
8966 // as to remove this logic from here, as much as possible
8967 if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
8968 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8969 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8972 assert(VT != MVT::v4i32 && "unsupported shuffle type");
8974 // Invert the operand order and use SHUFPS to match it.
8975 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
8976 getShuffleSHUFImmediate(SVOp), DAG);
8979 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
8980 SelectionDAG &DAG) {
8982 MVT VT = Load->getSimpleValueType(0);
8983 MVT EVT = VT.getVectorElementType();
8984 SDValue Addr = Load->getOperand(1);
8985 SDValue NewAddr = DAG.getNode(
8986 ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
8987 DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
8990 DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
8991 DAG.getMachineFunction().getMachineMemOperand(
8992 Load->getMemOperand(), 0, EVT.getStoreSize()));
8996 // It is only safe to call this function if isINSERTPSMask is true for
8997 // this shufflevector mask.
8998 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
8999 SelectionDAG &DAG) {
9000 // Generate an insertps instruction when inserting an f32 from memory onto a
9001 // v4f32 or when copying a member from one v4f32 to another.
9002 // We also use it for transferring i32 from one register to another,
9003 // since it simply copies the same bits.
9004 // If we're transferring an i32 from memory to a specific element in a
9005 // register, we output a generic DAG that will match the PINSRD
9007 MVT VT = SVOp->getSimpleValueType(0);
9008 MVT EVT = VT.getVectorElementType();
9009 SDValue V1 = SVOp->getOperand(0);
9010 SDValue V2 = SVOp->getOperand(1);
9011 auto Mask = SVOp->getMask();
9012 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9013 "unsupported vector type for insertps/pinsrd");
9015 auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9016 auto FromV2Predicate = [](const int &i) { return i >= 4; };
9017 int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9025 DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9028 assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9029 "More than one element from V1 and from V2, or no elements from one "
9030 "of the vectors. This case should not have returned true from "
9035 std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9038 unsigned SrcIndex = Mask[DestIndex] % 4;
9039 if (MayFoldLoad(From)) {
9040 // Trivial case, when From comes from a load and is only used by the
9041 // shuffle. Make it use insertps from the vector that we need from that
9044 NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9045 if (!NewLoad.getNode())
9048 if (EVT == MVT::f32) {
9049 // Create this as a scalar to vector to match the instruction pattern.
9050 SDValue LoadScalarToVector =
9051 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9052 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9053 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9055 } else { // EVT == MVT::i32
9056 // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9057 // instruction, to match the PINSRD instruction, which loads an i32 to a
9058 // certain vector element.
9059 return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9060 DAG.getConstant(DestIndex, MVT::i32));
9064 // Vector-element-to-vector
9065 SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9066 return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9069 // Reduce a vector shuffle to zext.
9070 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9071 SelectionDAG &DAG) {
9072 // PMOVZX is only available from SSE41.
9073 if (!Subtarget->hasSSE41())
9076 MVT VT = Op.getSimpleValueType();
9078 // Only AVX2 support 256-bit vector integer extending.
9079 if (!Subtarget->hasInt256() && VT.is256BitVector())
9082 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9084 SDValue V1 = Op.getOperand(0);
9085 SDValue V2 = Op.getOperand(1);
9086 unsigned NumElems = VT.getVectorNumElements();
9088 // Extending is an unary operation and the element type of the source vector
9089 // won't be equal to or larger than i64.
9090 if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9091 VT.getVectorElementType() == MVT::i64)
9094 // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9095 unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9096 while ((1U << Shift) < NumElems) {
9097 if (SVOp->getMaskElt(1U << Shift) == 1)
9100 // The maximal ratio is 8, i.e. from i8 to i64.
9105 // Check the shuffle mask.
9106 unsigned Mask = (1U << Shift) - 1;
9107 for (unsigned i = 0; i != NumElems; ++i) {
9108 int EltIdx = SVOp->getMaskElt(i);
9109 if ((i & Mask) != 0 && EltIdx != -1)
9111 if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9115 unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9116 MVT NeVT = MVT::getIntegerVT(NBits);
9117 MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9119 if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9122 // Simplify the operand as it's prepared to be fed into shuffle.
9123 unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9124 if (V1.getOpcode() == ISD::BITCAST &&
9125 V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9126 V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9127 V1.getOperand(0).getOperand(0)
9128 .getSimpleValueType().getSizeInBits() == SignificantBits) {
9129 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9130 SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9131 ConstantSDNode *CIdx =
9132 dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9133 // If it's foldable, i.e. normal load with single use, we will let code
9134 // selection to fold it. Otherwise, we will short the conversion sequence.
9135 if (CIdx && CIdx->getZExtValue() == 0 &&
9136 (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9137 MVT FullVT = V.getSimpleValueType();
9138 MVT V1VT = V1.getSimpleValueType();
9139 if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9140 // The "ext_vec_elt" node is wider than the result node.
9141 // In this case we should extract subvector from V.
9142 // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9143 unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9144 MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9145 FullVT.getVectorNumElements()/Ratio);
9146 V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9147 DAG.getIntPtrConstant(0));
9149 V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9153 return DAG.getNode(ISD::BITCAST, DL, VT,
9154 DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9157 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9158 SelectionDAG &DAG) {
9159 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9160 MVT VT = Op.getSimpleValueType();
9162 SDValue V1 = Op.getOperand(0);
9163 SDValue V2 = Op.getOperand(1);
9165 if (isZeroShuffle(SVOp))
9166 return getZeroVector(VT, Subtarget, DAG, dl);
9168 // Handle splat operations
9169 if (SVOp->isSplat()) {
9170 // Use vbroadcast whenever the splat comes from a foldable load
9171 SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9172 if (Broadcast.getNode())
9176 // Check integer expanding shuffles.
9177 SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9178 if (NewOp.getNode())
9181 // If the shuffle can be profitably rewritten as a narrower shuffle, then
9183 if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9185 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9186 if (NewOp.getNode())
9187 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9188 } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9189 // FIXME: Figure out a cleaner way to do this.
9190 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9191 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9192 if (NewOp.getNode()) {
9193 MVT NewVT = NewOp.getSimpleValueType();
9194 if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9195 NewVT, true, false))
9196 return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9199 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9200 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9201 if (NewOp.getNode()) {
9202 MVT NewVT = NewOp.getSimpleValueType();
9203 if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9204 return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9213 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9214 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9215 SDValue V1 = Op.getOperand(0);
9216 SDValue V2 = Op.getOperand(1);
9217 MVT VT = Op.getSimpleValueType();
9219 unsigned NumElems = VT.getVectorNumElements();
9220 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9221 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9222 bool V1IsSplat = false;
9223 bool V2IsSplat = false;
9224 bool HasSSE2 = Subtarget->hasSSE2();
9225 bool HasFp256 = Subtarget->hasFp256();
9226 bool HasInt256 = Subtarget->hasInt256();
9227 MachineFunction &MF = DAG.getMachineFunction();
9228 bool OptForSize = MF.getFunction()->getAttributes().
9229 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9231 // Check if we should use the experimental vector shuffle lowering. If so,
9232 // delegate completely to that code path.
9233 if (ExperimentalVectorShuffleLowering)
9234 return lowerVectorShuffle(Op, Subtarget, DAG);
9236 assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9238 if (V1IsUndef && V2IsUndef)
9239 return DAG.getUNDEF(VT);
9241 // When we create a shuffle node we put the UNDEF node to second operand,
9242 // but in some cases the first operand may be transformed to UNDEF.
9243 // In this case we should just commute the node.
9245 return CommuteVectorShuffle(SVOp, DAG);
9247 // Vector shuffle lowering takes 3 steps:
9249 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9250 // narrowing and commutation of operands should be handled.
9251 // 2) Matching of shuffles with known shuffle masks to x86 target specific
9253 // 3) Rewriting of unmatched masks into new generic shuffle operations,
9254 // so the shuffle can be broken into other shuffles and the legalizer can
9255 // try the lowering again.
9257 // The general idea is that no vector_shuffle operation should be left to
9258 // be matched during isel, all of them must be converted to a target specific
9261 // Normalize the input vectors. Here splats, zeroed vectors, profitable
9262 // narrowing and commutation of operands should be handled. The actual code
9263 // doesn't include all of those, work in progress...
9264 SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9265 if (NewOp.getNode())
9268 SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9270 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9271 // unpckh_undef). Only use pshufd if speed is more important than size.
9272 if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9273 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9274 if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9275 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9277 if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9278 V2IsUndef && MayFoldVectorLoad(V1))
9279 return getMOVDDup(Op, dl, V1, DAG);
9281 if (isMOVHLPS_v_undef_Mask(M, VT))
9282 return getMOVHighToLow(Op, dl, DAG);
9284 // Use to match splats
9285 if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9286 (VT == MVT::v2f64 || VT == MVT::v2i64))
9287 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9289 if (isPSHUFDMask(M, VT)) {
9290 // The actual implementation will match the mask in the if above and then
9291 // during isel it can match several different instructions, not only pshufd
9292 // as its name says, sad but true, emulate the behavior for now...
9293 if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9294 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9296 unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9298 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9299 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9301 if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9302 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9305 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9309 if (isPALIGNRMask(M, VT, Subtarget))
9310 return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9311 getShufflePALIGNRImmediate(SVOp),
9314 // Check if this can be converted into a logical shift.
9315 bool isLeft = false;
9318 bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9319 if (isShift && ShVal.hasOneUse()) {
9320 // If the shifted value has multiple uses, it may be cheaper to use
9321 // v_set0 + movlhps or movhlps, etc.
9322 MVT EltVT = VT.getVectorElementType();
9323 ShAmt *= EltVT.getSizeInBits();
9324 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9327 if (isMOVLMask(M, VT)) {
9328 if (ISD::isBuildVectorAllZeros(V1.getNode()))
9329 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9330 if (!isMOVLPMask(M, VT)) {
9331 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9332 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9334 if (VT == MVT::v4i32 || VT == MVT::v4f32)
9335 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9339 // FIXME: fold these into legal mask.
9340 if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9341 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9343 if (isMOVHLPSMask(M, VT))
9344 return getMOVHighToLow(Op, dl, DAG);
9346 if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9347 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9349 if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9350 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9352 if (isMOVLPMask(M, VT))
9353 return getMOVLP(Op, dl, DAG, HasSSE2);
9355 if (ShouldXformToMOVHLPS(M, VT) ||
9356 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9357 return CommuteVectorShuffle(SVOp, DAG);
9360 // No better options. Use a vshldq / vsrldq.
9361 MVT EltVT = VT.getVectorElementType();
9362 ShAmt *= EltVT.getSizeInBits();
9363 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9366 bool Commuted = false;
9367 // FIXME: This should also accept a bitcast of a splat? Be careful, not
9368 // 1,1,1,1 -> v8i16 though.
9369 V1IsSplat = isSplatVector(V1.getNode());
9370 V2IsSplat = isSplatVector(V2.getNode());
9372 // Canonicalize the splat or undef, if present, to be on the RHS.
9373 if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9374 CommuteVectorShuffleMask(M, NumElems);
9376 std::swap(V1IsSplat, V2IsSplat);
9380 if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9381 // Shuffling low element of v1 into undef, just return v1.
9384 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9385 // the instruction selector will not match, so get a canonical MOVL with
9386 // swapped operands to undo the commute.
9387 return getMOVL(DAG, dl, VT, V2, V1);
9390 if (isUNPCKLMask(M, VT, HasInt256))
9391 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9393 if (isUNPCKHMask(M, VT, HasInt256))
9394 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9397 // Normalize mask so all entries that point to V2 points to its first
9398 // element then try to match unpck{h|l} again. If match, return a
9399 // new vector_shuffle with the corrected mask.p
9400 SmallVector<int, 8> NewMask(M.begin(), M.end());
9401 NormalizeMask(NewMask, NumElems);
9402 if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9403 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9404 if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9405 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9409 // Commute is back and try unpck* again.
9410 // FIXME: this seems wrong.
9411 CommuteVectorShuffleMask(M, NumElems);
9413 std::swap(V1IsSplat, V2IsSplat);
9415 if (isUNPCKLMask(M, VT, HasInt256))
9416 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9418 if (isUNPCKHMask(M, VT, HasInt256))
9419 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9422 // Normalize the node to match x86 shuffle ops if needed
9423 if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9424 return CommuteVectorShuffle(SVOp, DAG);
9426 // The checks below are all present in isShuffleMaskLegal, but they are
9427 // inlined here right now to enable us to directly emit target specific
9428 // nodes, and remove one by one until they don't return Op anymore.
9430 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9431 SVOp->getSplatIndex() == 0 && V2IsUndef) {
9432 if (VT == MVT::v2f64 || VT == MVT::v2i64)
9433 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9436 if (isPSHUFHWMask(M, VT, HasInt256))
9437 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9438 getShufflePSHUFHWImmediate(SVOp),
9441 if (isPSHUFLWMask(M, VT, HasInt256))
9442 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9443 getShufflePSHUFLWImmediate(SVOp),
9447 if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9449 return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9451 if (isSHUFPMask(M, VT))
9452 return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9453 getShuffleSHUFImmediate(SVOp), DAG);
9455 if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9456 return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9457 if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9458 return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9460 //===--------------------------------------------------------------------===//
9461 // Generate target specific nodes for 128 or 256-bit shuffles only
9462 // supported in the AVX instruction set.
9465 // Handle VMOVDDUPY permutations
9466 if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9467 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9469 // Handle VPERMILPS/D* permutations
9470 if (isVPERMILPMask(M, VT)) {
9471 if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9472 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9473 getShuffleSHUFImmediate(SVOp), DAG);
9474 return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9475 getShuffleSHUFImmediate(SVOp), DAG);
9479 if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9480 return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9481 Idx*(NumElems/2), DAG, dl);
9483 // Handle VPERM2F128/VPERM2I128 permutations
9484 if (isVPERM2X128Mask(M, VT, HasFp256))
9485 return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9486 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9488 if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9489 return getINSERTPS(SVOp, dl, DAG);
9492 if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9493 return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9495 if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9496 VT.is512BitVector()) {
9497 MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9498 MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9499 SmallVector<SDValue, 16> permclMask;
9500 for (unsigned i = 0; i != NumElems; ++i) {
9501 permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9504 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9506 // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9507 return DAG.getNode(X86ISD::VPERMV, dl, VT,
9508 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9509 return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9510 DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9513 //===--------------------------------------------------------------------===//
9514 // Since no target specific shuffle was selected for this generic one,
9515 // lower it into other known shuffles. FIXME: this isn't true yet, but
9516 // this is the plan.
9519 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9520 if (VT == MVT::v8i16) {
9521 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9522 if (NewOp.getNode())
9526 if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9527 SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9528 if (NewOp.getNode())
9532 if (VT == MVT::v16i8) {
9533 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9534 if (NewOp.getNode())
9538 if (VT == MVT::v32i8) {
9539 SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9540 if (NewOp.getNode())
9544 // Handle all 128-bit wide vectors with 4 elements, and match them with
9545 // several different shuffle types.
9546 if (NumElems == 4 && VT.is128BitVector())
9547 return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9549 // Handle general 256-bit shuffles
9550 if (VT.is256BitVector())
9551 return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9556 // This function assumes its argument is a BUILD_VECTOR of constants or
9557 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9559 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9560 unsigned &MaskValue) {
9562 unsigned NumElems = BuildVector->getNumOperands();
9563 // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9564 unsigned NumLanes = (NumElems - 1) / 8 + 1;
9565 unsigned NumElemsInLane = NumElems / NumLanes;
9567 // Blend for v16i16 should be symetric for the both lanes.
9568 for (unsigned i = 0; i < NumElemsInLane; ++i) {
9569 SDValue EltCond = BuildVector->getOperand(i);
9570 SDValue SndLaneEltCond =
9571 (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9573 int Lane1Cond = -1, Lane2Cond = -1;
9574 if (isa<ConstantSDNode>(EltCond))
9575 Lane1Cond = !isZero(EltCond);
9576 if (isa<ConstantSDNode>(SndLaneEltCond))
9577 Lane2Cond = !isZero(SndLaneEltCond);
9579 if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9580 // Lane1Cond != 0, means we want the first argument.
9581 // Lane1Cond == 0, means we want the second argument.
9582 // The encoding of this argument is 0 for the first argument, 1
9583 // for the second. Therefore, invert the condition.
9584 MaskValue |= !Lane1Cond << i;
9585 else if (Lane1Cond < 0)
9586 MaskValue |= !Lane2Cond << i;
9593 // Try to lower a vselect node into a simple blend instruction.
9594 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9595 SelectionDAG &DAG) {
9596 SDValue Cond = Op.getOperand(0);
9597 SDValue LHS = Op.getOperand(1);
9598 SDValue RHS = Op.getOperand(2);
9600 MVT VT = Op.getSimpleValueType();
9601 MVT EltVT = VT.getVectorElementType();
9602 unsigned NumElems = VT.getVectorNumElements();
9604 // There is no blend with immediate in AVX-512.
9605 if (VT.is512BitVector())
9608 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9610 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9613 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9616 // Check the mask for BLEND and build the value.
9617 unsigned MaskValue = 0;
9618 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9621 // Convert i32 vectors to floating point if it is not AVX2.
9622 // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9624 if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9625 BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9627 LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9628 RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9631 SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9632 DAG.getConstant(MaskValue, MVT::i32));
9633 return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9636 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9637 SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9638 if (BlendOp.getNode())
9641 // Some types for vselect were previously set to Expand, not Legal or
9642 // Custom. Return an empty SDValue so we fall-through to Expand, after
9643 // the Custom lowering phase.
9644 MVT VT = Op.getSimpleValueType();
9645 switch (VT.SimpleTy) {
9653 // We couldn't create a "Blend with immediate" node.
9654 // This node should still be legal, but we'll have to emit a blendv*
9659 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9660 MVT VT = Op.getSimpleValueType();
9663 if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9666 if (VT.getSizeInBits() == 8) {
9667 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9668 Op.getOperand(0), Op.getOperand(1));
9669 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9670 DAG.getValueType(VT));
9671 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9674 if (VT.getSizeInBits() == 16) {
9675 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9676 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9678 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9679 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9680 DAG.getNode(ISD::BITCAST, dl,
9684 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9685 Op.getOperand(0), Op.getOperand(1));
9686 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9687 DAG.getValueType(VT));
9688 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9691 if (VT == MVT::f32) {
9692 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9693 // the result back to FR32 register. It's only worth matching if the
9694 // result has a single use which is a store or a bitcast to i32. And in
9695 // the case of a store, it's not worth it if the index is a constant 0,
9696 // because a MOVSSmr can be used instead, which is smaller and faster.
9697 if (!Op.hasOneUse())
9699 SDNode *User = *Op.getNode()->use_begin();
9700 if ((User->getOpcode() != ISD::STORE ||
9701 (isa<ConstantSDNode>(Op.getOperand(1)) &&
9702 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9703 (User->getOpcode() != ISD::BITCAST ||
9704 User->getValueType(0) != MVT::i32))
9706 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9707 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9710 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9713 if (VT == MVT::i32 || VT == MVT::i64) {
9714 // ExtractPS/pextrq works with constant index.
9715 if (isa<ConstantSDNode>(Op.getOperand(1)))
9721 /// Extract one bit from mask vector, like v16i1 or v8i1.
9722 /// AVX-512 feature.
9724 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9725 SDValue Vec = Op.getOperand(0);
9727 MVT VecVT = Vec.getSimpleValueType();
9728 SDValue Idx = Op.getOperand(1);
9729 MVT EltVT = Op.getSimpleValueType();
9731 assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9733 // variable index can't be handled in mask registers,
9734 // extend vector to VR512
9735 if (!isa<ConstantSDNode>(Idx)) {
9736 MVT ExtVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9737 SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9738 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9739 ExtVT.getVectorElementType(), Ext, Idx);
9740 return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9743 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9744 const TargetRegisterClass* rc = getRegClassFor(VecVT);
9745 unsigned MaxSift = rc->getSize()*8 - 1;
9746 Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9747 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9748 Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9749 DAG.getConstant(MaxSift, MVT::i8));
9750 return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9751 DAG.getIntPtrConstant(0));
9755 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9756 SelectionDAG &DAG) const {
9758 SDValue Vec = Op.getOperand(0);
9759 MVT VecVT = Vec.getSimpleValueType();
9760 SDValue Idx = Op.getOperand(1);
9762 if (Op.getSimpleValueType() == MVT::i1)
9763 return ExtractBitFromMaskVector(Op, DAG);
9765 if (!isa<ConstantSDNode>(Idx)) {
9766 if (VecVT.is512BitVector() ||
9767 (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9768 VecVT.getVectorElementType().getSizeInBits() == 32)) {
9771 MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9772 MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9773 MaskEltVT.getSizeInBits());
9775 Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9776 SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9777 getZeroVector(MaskVT, Subtarget, DAG, dl),
9778 Idx, DAG.getConstant(0, getPointerTy()));
9779 SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9780 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9781 Perm, DAG.getConstant(0, getPointerTy()));
9786 // If this is a 256-bit vector result, first extract the 128-bit vector and
9787 // then extract the element from the 128-bit vector.
9788 if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9790 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9791 // Get the 128-bit vector.
9792 Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9793 MVT EltVT = VecVT.getVectorElementType();
9795 unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9797 //if (IdxVal >= NumElems/2)
9798 // IdxVal -= NumElems/2;
9799 IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9800 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9801 DAG.getConstant(IdxVal, MVT::i32));
9804 assert(VecVT.is128BitVector() && "Unexpected vector length");
9806 if (Subtarget->hasSSE41()) {
9807 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9812 MVT VT = Op.getSimpleValueType();
9813 // TODO: handle v16i8.
9814 if (VT.getSizeInBits() == 16) {
9815 SDValue Vec = Op.getOperand(0);
9816 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9818 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9819 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9820 DAG.getNode(ISD::BITCAST, dl,
9823 // Transform it so it match pextrw which produces a 32-bit result.
9824 MVT EltVT = MVT::i32;
9825 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9826 Op.getOperand(0), Op.getOperand(1));
9827 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9828 DAG.getValueType(VT));
9829 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9832 if (VT.getSizeInBits() == 32) {
9833 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9837 // SHUFPS the element to the lowest double word, then movss.
9838 int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9839 MVT VVT = Op.getOperand(0).getSimpleValueType();
9840 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9841 DAG.getUNDEF(VVT), Mask);
9842 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9843 DAG.getIntPtrConstant(0));
9846 if (VT.getSizeInBits() == 64) {
9847 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9848 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9849 // to match extract_elt for f64.
9850 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9854 // UNPCKHPD the element to the lowest double word, then movsd.
9855 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9856 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9857 int Mask[2] = { 1, -1 };
9858 MVT VVT = Op.getOperand(0).getSimpleValueType();
9859 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9860 DAG.getUNDEF(VVT), Mask);
9861 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9862 DAG.getIntPtrConstant(0));
9868 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9869 MVT VT = Op.getSimpleValueType();
9870 MVT EltVT = VT.getVectorElementType();
9873 SDValue N0 = Op.getOperand(0);
9874 SDValue N1 = Op.getOperand(1);
9875 SDValue N2 = Op.getOperand(2);
9877 if (!VT.is128BitVector())
9880 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9881 isa<ConstantSDNode>(N2)) {
9883 if (VT == MVT::v8i16)
9884 Opc = X86ISD::PINSRW;
9885 else if (VT == MVT::v16i8)
9886 Opc = X86ISD::PINSRB;
9888 Opc = X86ISD::PINSRB;
9890 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9892 if (N1.getValueType() != MVT::i32)
9893 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9894 if (N2.getValueType() != MVT::i32)
9895 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9896 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9899 if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9900 // Bits [7:6] of the constant are the source select. This will always be
9901 // zero here. The DAG Combiner may combine an extract_elt index into these
9902 // bits. For example (insert (extract, 3), 2) could be matched by putting
9903 // the '3' into bits [7:6] of X86ISD::INSERTPS.
9904 // Bits [5:4] of the constant are the destination select. This is the
9905 // value of the incoming immediate.
9906 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
9907 // combine either bitwise AND or insert of float 0.0 to set these bits.
9908 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9909 // Create this as a scalar to vector..
9910 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9911 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9914 if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9915 // PINSR* works with constant index.
9921 /// Insert one bit to mask vector, like v16i1 or v8i1.
9922 /// AVX-512 feature.
9924 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9926 SDValue Vec = Op.getOperand(0);
9927 SDValue Elt = Op.getOperand(1);
9928 SDValue Idx = Op.getOperand(2);
9929 MVT VecVT = Vec.getSimpleValueType();
9931 if (!isa<ConstantSDNode>(Idx)) {
9932 // Non constant index. Extend source and destination,
9933 // insert element and then truncate the result.
9934 MVT ExtVecVT = (VecVT == MVT::v8i1 ? MVT::v8i64 : MVT::v16i32);
9935 MVT ExtEltVT = (VecVT == MVT::v8i1 ? MVT::i64 : MVT::i32);
9936 SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
9937 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9938 DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9939 return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
9942 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9943 SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
9944 if (Vec.getOpcode() == ISD::UNDEF)
9945 return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9946 DAG.getConstant(IdxVal, MVT::i8));
9947 const TargetRegisterClass* rc = getRegClassFor(VecVT);
9948 unsigned MaxSift = rc->getSize()*8 - 1;
9949 EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9950 DAG.getConstant(MaxSift, MVT::i8));
9951 EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
9952 DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9953 return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
9956 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
9957 MVT VT = Op.getSimpleValueType();
9958 MVT EltVT = VT.getVectorElementType();
9960 if (EltVT == MVT::i1)
9961 return InsertBitToMaskVector(Op, DAG);
9964 SDValue N0 = Op.getOperand(0);
9965 SDValue N1 = Op.getOperand(1);
9966 SDValue N2 = Op.getOperand(2);
9968 // If this is a 256-bit vector result, first extract the 128-bit vector,
9969 // insert the element into the extracted half and then place it back.
9970 if (VT.is256BitVector() || VT.is512BitVector()) {
9971 if (!isa<ConstantSDNode>(N2))
9974 // Get the desired 128-bit vector half.
9975 unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
9976 SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
9978 // Insert the element into the desired half.
9979 unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
9980 unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
9982 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
9983 DAG.getConstant(IdxIn128, MVT::i32));
9985 // Insert the changed part back to the 256-bit vector
9986 return Insert128BitVector(N0, V, IdxVal, DAG, dl);
9989 if (Subtarget->hasSSE41())
9990 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
9992 if (EltVT == MVT::i8)
9995 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
9996 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
9997 // as its second argument.
9998 if (N1.getValueType() != MVT::i32)
9999 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10000 if (N2.getValueType() != MVT::i32)
10001 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10002 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10007 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10009 MVT OpVT = Op.getSimpleValueType();
10011 // If this is a 256-bit vector result, first insert into a 128-bit
10012 // vector and then insert into the 256-bit vector.
10013 if (!OpVT.is128BitVector()) {
10014 // Insert into a 128-bit vector.
10015 unsigned SizeFactor = OpVT.getSizeInBits()/128;
10016 MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10017 OpVT.getVectorNumElements() / SizeFactor);
10019 Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10021 // Insert the 128-bit vector.
10022 return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10025 if (OpVT == MVT::v1i64 &&
10026 Op.getOperand(0).getValueType() == MVT::i64)
10027 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10029 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10030 assert(OpVT.is128BitVector() && "Expected an SSE type!");
10031 return DAG.getNode(ISD::BITCAST, dl, OpVT,
10032 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10035 // Lower a node with an EXTRACT_SUBVECTOR opcode. This may result in
10036 // a simple subregister reference or explicit instructions to grab
10037 // upper bits of a vector.
10038 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10039 SelectionDAG &DAG) {
10041 SDValue In = Op.getOperand(0);
10042 SDValue Idx = Op.getOperand(1);
10043 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10044 MVT ResVT = Op.getSimpleValueType();
10045 MVT InVT = In.getSimpleValueType();
10047 if (Subtarget->hasFp256()) {
10048 if (ResVT.is128BitVector() &&
10049 (InVT.is256BitVector() || InVT.is512BitVector()) &&
10050 isa<ConstantSDNode>(Idx)) {
10051 return Extract128BitVector(In, IdxVal, DAG, dl);
10053 if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10054 isa<ConstantSDNode>(Idx)) {
10055 return Extract256BitVector(In, IdxVal, DAG, dl);
10061 // Lower a node with an INSERT_SUBVECTOR opcode. This may result in a
10062 // simple superregister reference or explicit instructions to insert
10063 // the upper bits of a vector.
10064 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10065 SelectionDAG &DAG) {
10066 if (Subtarget->hasFp256()) {
10067 SDLoc dl(Op.getNode());
10068 SDValue Vec = Op.getNode()->getOperand(0);
10069 SDValue SubVec = Op.getNode()->getOperand(1);
10070 SDValue Idx = Op.getNode()->getOperand(2);
10072 if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10073 Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10074 SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10075 isa<ConstantSDNode>(Idx)) {
10076 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10077 return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10080 if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10081 SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10082 isa<ConstantSDNode>(Idx)) {
10083 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10084 return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10090 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10091 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10092 // one of the above mentioned nodes. It has to be wrapped because otherwise
10093 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10094 // be used to form addressing mode. These wrapped nodes will be selected
10097 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10098 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10100 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10101 // global base reg.
10102 unsigned char OpFlag = 0;
10103 unsigned WrapperKind = X86ISD::Wrapper;
10104 CodeModel::Model M = DAG.getTarget().getCodeModel();
10106 if (Subtarget->isPICStyleRIPRel() &&
10107 (M == CodeModel::Small || M == CodeModel::Kernel))
10108 WrapperKind = X86ISD::WrapperRIP;
10109 else if (Subtarget->isPICStyleGOT())
10110 OpFlag = X86II::MO_GOTOFF;
10111 else if (Subtarget->isPICStyleStubPIC())
10112 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10114 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10115 CP->getAlignment(),
10116 CP->getOffset(), OpFlag);
10118 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10119 // With PIC, the address is actually $g + Offset.
10121 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10122 DAG.getNode(X86ISD::GlobalBaseReg,
10123 SDLoc(), getPointerTy()),
10130 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10131 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10133 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10134 // global base reg.
10135 unsigned char OpFlag = 0;
10136 unsigned WrapperKind = X86ISD::Wrapper;
10137 CodeModel::Model M = DAG.getTarget().getCodeModel();
10139 if (Subtarget->isPICStyleRIPRel() &&
10140 (M == CodeModel::Small || M == CodeModel::Kernel))
10141 WrapperKind = X86ISD::WrapperRIP;
10142 else if (Subtarget->isPICStyleGOT())
10143 OpFlag = X86II::MO_GOTOFF;
10144 else if (Subtarget->isPICStyleStubPIC())
10145 OpFlag = X86II::MO_PIC_BASE_OFFSET;
10147 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10150 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10152 // With PIC, the address is actually $g + Offset.
10154 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10155 DAG.getNode(X86ISD::GlobalBaseReg,
10156 SDLoc(), getPointerTy()),
10163 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10164 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10166 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10167 // global base reg.
10168 unsigned char OpFlag = 0;
10169 unsigned WrapperKind = X86ISD::Wrapper;
10170 CodeModel::Model M = DAG.getTarget().getCodeModel();
10172 if (Subtarget->isPICStyleRIPRel() &&
10173 (M == CodeModel::Small || M == CodeModel::Kernel)) {
10174 if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10175 OpFlag = X86II::MO_GOTPCREL;
10176 WrapperKind = X86ISD::WrapperRIP;
10177 } else if (Subtarget->isPICStyleGOT()) {
10178 OpFlag = X86II::MO_GOT;
10179 } else if (Subtarget->isPICStyleStubPIC()) {
10180 OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10181 } else if (Subtarget->isPICStyleStubNoDynamic()) {
10182 OpFlag = X86II::MO_DARWIN_NONLAZY;
10185 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10188 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10190 // With PIC, the address is actually $g + Offset.
10191 if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10192 !Subtarget->is64Bit()) {
10193 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10194 DAG.getNode(X86ISD::GlobalBaseReg,
10195 SDLoc(), getPointerTy()),
10199 // For symbols that require a load from a stub to get the address, emit the
10201 if (isGlobalStubReference(OpFlag))
10202 Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10203 MachinePointerInfo::getGOT(), false, false, false, 0);
10209 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10210 // Create the TargetBlockAddressAddress node.
10211 unsigned char OpFlags =
10212 Subtarget->ClassifyBlockAddressReference();
10213 CodeModel::Model M = DAG.getTarget().getCodeModel();
10214 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10215 int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10217 SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10220 if (Subtarget->isPICStyleRIPRel() &&
10221 (M == CodeModel::Small || M == CodeModel::Kernel))
10222 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10224 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10226 // With PIC, the address is actually $g + Offset.
10227 if (isGlobalRelativeToPICBase(OpFlags)) {
10228 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10229 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10237 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10238 int64_t Offset, SelectionDAG &DAG) const {
10239 // Create the TargetGlobalAddress node, folding in the constant
10240 // offset if it is legal.
10241 unsigned char OpFlags =
10242 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10243 CodeModel::Model M = DAG.getTarget().getCodeModel();
10245 if (OpFlags == X86II::MO_NO_FLAG &&
10246 X86::isOffsetSuitableForCodeModel(Offset, M)) {
10247 // A direct static reference to a global.
10248 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10251 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10254 if (Subtarget->isPICStyleRIPRel() &&
10255 (M == CodeModel::Small || M == CodeModel::Kernel))
10256 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10258 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10260 // With PIC, the address is actually $g + Offset.
10261 if (isGlobalRelativeToPICBase(OpFlags)) {
10262 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10263 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10267 // For globals that require a load from a stub to get the address, emit the
10269 if (isGlobalStubReference(OpFlags))
10270 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10271 MachinePointerInfo::getGOT(), false, false, false, 0);
10273 // If there was a non-zero offset that we didn't fold, create an explicit
10274 // addition for it.
10276 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10277 DAG.getConstant(Offset, getPointerTy()));
10283 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10284 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10285 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10286 return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10290 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10291 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10292 unsigned char OperandFlags, bool LocalDynamic = false) {
10293 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10294 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10296 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10297 GA->getValueType(0),
10301 X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10305 SDValue Ops[] = { Chain, TGA, *InFlag };
10306 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10308 SDValue Ops[] = { Chain, TGA };
10309 Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10312 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10313 MFI->setAdjustsStack(true);
10315 SDValue Flag = Chain.getValue(1);
10316 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10319 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10321 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10324 SDLoc dl(GA); // ? function entry point might be better
10325 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10326 DAG.getNode(X86ISD::GlobalBaseReg,
10327 SDLoc(), PtrVT), InFlag);
10328 InFlag = Chain.getValue(1);
10330 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10333 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10335 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10337 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10338 X86::RAX, X86II::MO_TLSGD);
10341 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10347 // Get the start address of the TLS block for this module.
10348 X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10349 .getInfo<X86MachineFunctionInfo>();
10350 MFI->incNumLocalDynamicTLSAccesses();
10354 Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10355 X86II::MO_TLSLD, /*LocalDynamic=*/true);
10358 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10359 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10360 InFlag = Chain.getValue(1);
10361 Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10362 X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10365 // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10369 unsigned char OperandFlags = X86II::MO_DTPOFF;
10370 unsigned WrapperKind = X86ISD::Wrapper;
10371 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10372 GA->getValueType(0),
10373 GA->getOffset(), OperandFlags);
10374 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10376 // Add x@dtpoff with the base.
10377 return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10380 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10381 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10382 const EVT PtrVT, TLSModel::Model model,
10383 bool is64Bit, bool isPIC) {
10386 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10387 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10388 is64Bit ? 257 : 256));
10390 SDValue ThreadPointer =
10391 DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10392 MachinePointerInfo(Ptr), false, false, false, 0);
10394 unsigned char OperandFlags = 0;
10395 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
10397 unsigned WrapperKind = X86ISD::Wrapper;
10398 if (model == TLSModel::LocalExec) {
10399 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10400 } else if (model == TLSModel::InitialExec) {
10402 OperandFlags = X86II::MO_GOTTPOFF;
10403 WrapperKind = X86ISD::WrapperRIP;
10405 OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10408 llvm_unreachable("Unexpected model");
10411 // emit "addl x@ntpoff,%eax" (local exec)
10412 // or "addl x@indntpoff,%eax" (initial exec)
10413 // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10415 DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10416 GA->getOffset(), OperandFlags);
10417 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10419 if (model == TLSModel::InitialExec) {
10420 if (isPIC && !is64Bit) {
10421 Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10422 DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10426 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10427 MachinePointerInfo::getGOT(), false, false, false, 0);
10430 // The address of the thread local variable is the add of the thread
10431 // pointer with the offset of the variable.
10432 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10436 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10438 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10439 const GlobalValue *GV = GA->getGlobal();
10441 if (Subtarget->isTargetELF()) {
10442 TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10445 case TLSModel::GeneralDynamic:
10446 if (Subtarget->is64Bit())
10447 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10448 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10449 case TLSModel::LocalDynamic:
10450 return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10451 Subtarget->is64Bit());
10452 case TLSModel::InitialExec:
10453 case TLSModel::LocalExec:
10454 return LowerToTLSExecModel(
10455 GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10456 DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10458 llvm_unreachable("Unknown TLS model.");
10461 if (Subtarget->isTargetDarwin()) {
10462 // Darwin only has one model of TLS. Lower to that.
10463 unsigned char OpFlag = 0;
10464 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10465 X86ISD::WrapperRIP : X86ISD::Wrapper;
10467 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10468 // global base reg.
10469 bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10470 !Subtarget->is64Bit();
10472 OpFlag = X86II::MO_TLVP_PIC_BASE;
10474 OpFlag = X86II::MO_TLVP;
10476 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10477 GA->getValueType(0),
10478 GA->getOffset(), OpFlag);
10479 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10481 // With PIC32, the address is actually $g + Offset.
10483 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10484 DAG.getNode(X86ISD::GlobalBaseReg,
10485 SDLoc(), getPointerTy()),
10488 // Lowering the machine isd will make sure everything is in the right
10490 SDValue Chain = DAG.getEntryNode();
10491 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10492 SDValue Args[] = { Chain, Offset };
10493 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10495 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10496 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10497 MFI->setAdjustsStack(true);
10499 // And our return value (tls address) is in the standard call return value
10501 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10502 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10503 Chain.getValue(1));
10506 if (Subtarget->isTargetKnownWindowsMSVC() ||
10507 Subtarget->isTargetWindowsGNU()) {
10508 // Just use the implicit TLS architecture
10509 // Need to generate someting similar to:
10510 // mov rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10512 // mov ecx, dword [rel _tls_index]: Load index (from C runtime)
10513 // mov rcx, qword [rdx+rcx*8]
10514 // mov eax, .tls$:tlsvar
10515 // [rax+rcx] contains the address
10516 // Windows 64bit: gs:0x58
10517 // Windows 32bit: fs:__tls_array
10520 SDValue Chain = DAG.getEntryNode();
10522 // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10523 // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10524 // use its literal value of 0x2C.
10525 Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10526 ? Type::getInt8PtrTy(*DAG.getContext(),
10528 : Type::getInt32PtrTy(*DAG.getContext(),
10532 Subtarget->is64Bit()
10533 ? DAG.getIntPtrConstant(0x58)
10534 : (Subtarget->isTargetWindowsGNU()
10535 ? DAG.getIntPtrConstant(0x2C)
10536 : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10538 SDValue ThreadPointer =
10539 DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10540 MachinePointerInfo(Ptr), false, false, false, 0);
10542 // Load the _tls_index variable
10543 SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10544 if (Subtarget->is64Bit())
10545 IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10546 IDX, MachinePointerInfo(), MVT::i32,
10549 IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10550 false, false, false, 0);
10552 SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10554 IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10556 SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10557 res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10558 false, false, false, 0);
10560 // Get the offset of start of .tls section
10561 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10562 GA->getValueType(0),
10563 GA->getOffset(), X86II::MO_SECREL);
10564 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10566 // The address of the thread local variable is the add of the thread
10567 // pointer with the offset of the variable.
10568 return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10571 llvm_unreachable("TLS not implemented for this target.");
10574 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10575 /// and take a 2 x i32 value to shift plus a shift amount.
10576 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10577 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10578 MVT VT = Op.getSimpleValueType();
10579 unsigned VTBits = VT.getSizeInBits();
10581 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10582 SDValue ShOpLo = Op.getOperand(0);
10583 SDValue ShOpHi = Op.getOperand(1);
10584 SDValue ShAmt = Op.getOperand(2);
10585 // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10586 // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10588 SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10589 DAG.getConstant(VTBits - 1, MVT::i8));
10590 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10591 DAG.getConstant(VTBits - 1, MVT::i8))
10592 : DAG.getConstant(0, VT);
10594 SDValue Tmp2, Tmp3;
10595 if (Op.getOpcode() == ISD::SHL_PARTS) {
10596 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10597 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10599 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10600 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10603 // If the shift amount is larger or equal than the width of a part we can't
10604 // rely on the results of shld/shrd. Insert a test and select the appropriate
10605 // values for large shift amounts.
10606 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10607 DAG.getConstant(VTBits, MVT::i8));
10608 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10609 AndNode, DAG.getConstant(0, MVT::i8));
10612 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10613 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10614 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10616 if (Op.getOpcode() == ISD::SHL_PARTS) {
10617 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10618 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10620 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10621 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10624 SDValue Ops[2] = { Lo, Hi };
10625 return DAG.getMergeValues(Ops, dl);
10628 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10629 SelectionDAG &DAG) const {
10630 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10632 if (SrcVT.isVector())
10635 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10636 "Unknown SINT_TO_FP to lower!");
10638 // These are really Legal; return the operand so the caller accepts it as
10640 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10642 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10643 Subtarget->is64Bit()) {
10648 unsigned Size = SrcVT.getSizeInBits()/8;
10649 MachineFunction &MF = DAG.getMachineFunction();
10650 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10651 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10652 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10654 MachinePointerInfo::getFixedStack(SSFI),
10656 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10659 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10661 SelectionDAG &DAG) const {
10665 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10667 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10669 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10671 unsigned ByteSize = SrcVT.getSizeInBits()/8;
10673 FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10674 MachineMemOperand *MMO;
10676 int SSFI = FI->getIndex();
10678 DAG.getMachineFunction()
10679 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10680 MachineMemOperand::MOLoad, ByteSize, ByteSize);
10682 MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10683 StackSlot = StackSlot.getOperand(1);
10685 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10686 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10688 Tys, Ops, SrcVT, MMO);
10691 Chain = Result.getValue(1);
10692 SDValue InFlag = Result.getValue(2);
10694 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10695 // shouldn't be necessary except that RFP cannot be live across
10696 // multiple blocks. When stackifier is fixed, they can be uncoupled.
10697 MachineFunction &MF = DAG.getMachineFunction();
10698 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10699 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10700 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10701 Tys = DAG.getVTList(MVT::Other);
10703 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10705 MachineMemOperand *MMO =
10706 DAG.getMachineFunction()
10707 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10708 MachineMemOperand::MOStore, SSFISize, SSFISize);
10710 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10711 Ops, Op.getValueType(), MMO);
10712 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10713 MachinePointerInfo::getFixedStack(SSFI),
10714 false, false, false, 0);
10720 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10721 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10722 SelectionDAG &DAG) const {
10723 // This algorithm is not obvious. Here it is what we're trying to output:
10726 punpckldq (c0), %xmm0 // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10727 subpd (c1), %xmm0 // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10729 haddpd %xmm0, %xmm0
10731 pshufd $0x4e, %xmm0, %xmm1
10737 LLVMContext *Context = DAG.getContext();
10739 // Build some magic constants.
10740 static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10741 Constant *C0 = ConstantDataVector::get(*Context, CV0);
10742 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10744 SmallVector<Constant*,2> CV1;
10746 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10747 APInt(64, 0x4330000000000000ULL))));
10749 ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10750 APInt(64, 0x4530000000000000ULL))));
10751 Constant *C1 = ConstantVector::get(CV1);
10752 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10754 // Load the 64-bit value into an XMM register.
10755 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10757 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10758 MachinePointerInfo::getConstantPool(),
10759 false, false, false, 16);
10760 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10761 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10764 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10765 MachinePointerInfo::getConstantPool(),
10766 false, false, false, 16);
10767 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10768 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10771 if (Subtarget->hasSSE3()) {
10772 // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10773 Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10775 SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10776 SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10778 Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10779 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10783 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10784 DAG.getIntPtrConstant(0));
10787 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10788 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10789 SelectionDAG &DAG) const {
10791 // FP constant to bias correct the final result.
10792 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10795 // Load the 32-bit value into an XMM register.
10796 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10799 // Zero out the upper parts of the register.
10800 Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10802 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10803 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10804 DAG.getIntPtrConstant(0));
10806 // Or the load with the bias.
10807 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10808 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10809 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10810 MVT::v2f64, Load)),
10811 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10812 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10813 MVT::v2f64, Bias)));
10814 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10815 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10816 DAG.getIntPtrConstant(0));
10818 // Subtract the bias.
10819 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10821 // Handle final rounding.
10822 EVT DestVT = Op.getValueType();
10824 if (DestVT.bitsLT(MVT::f64))
10825 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10826 DAG.getIntPtrConstant(0));
10827 if (DestVT.bitsGT(MVT::f64))
10828 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10830 // Handle final rounding.
10834 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10835 SelectionDAG &DAG) const {
10836 SDValue N0 = Op.getOperand(0);
10837 MVT SVT = N0.getSimpleValueType();
10840 assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10841 SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10842 "Custom UINT_TO_FP is not supported!");
10844 MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10845 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10846 DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10849 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10850 SelectionDAG &DAG) const {
10851 SDValue N0 = Op.getOperand(0);
10854 if (Op.getValueType().isVector())
10855 return lowerUINT_TO_FP_vec(Op, DAG);
10857 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10858 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10859 // the optimization here.
10860 if (DAG.SignBitIsZero(N0))
10861 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10863 MVT SrcVT = N0.getSimpleValueType();
10864 MVT DstVT = Op.getSimpleValueType();
10865 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10866 return LowerUINT_TO_FP_i64(Op, DAG);
10867 if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10868 return LowerUINT_TO_FP_i32(Op, DAG);
10869 if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10872 // Make a 64-bit buffer, and use it to build an FILD.
10873 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10874 if (SrcVT == MVT::i32) {
10875 SDValue WordOff = DAG.getConstant(4, getPointerTy());
10876 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10877 getPointerTy(), StackSlot, WordOff);
10878 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10879 StackSlot, MachinePointerInfo(),
10881 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10882 OffsetSlot, MachinePointerInfo(),
10884 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10888 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10889 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10890 StackSlot, MachinePointerInfo(),
10892 // For i64 source, we need to add the appropriate power of 2 if the input
10893 // was negative. This is the same as the optimization in
10894 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10895 // we must be careful to do the computation in x87 extended precision, not
10896 // in SSE. (The generic code can't know it's OK to do this, or how to.)
10897 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10898 MachineMemOperand *MMO =
10899 DAG.getMachineFunction()
10900 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10901 MachineMemOperand::MOLoad, 8, 8);
10903 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10904 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10905 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10908 APInt FF(32, 0x5F800000ULL);
10910 // Check whether the sign bit is set.
10911 SDValue SignSet = DAG.getSetCC(dl,
10912 getSetCCResultType(*DAG.getContext(), MVT::i64),
10913 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10916 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10917 SDValue FudgePtr = DAG.getConstantPool(
10918 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10921 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10922 SDValue Zero = DAG.getIntPtrConstant(0);
10923 SDValue Four = DAG.getIntPtrConstant(4);
10924 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10926 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10928 // Load the value out, extending it from f32 to f80.
10929 // FIXME: Avoid the extend by constructing the right constant pool?
10930 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10931 FudgePtr, MachinePointerInfo::getConstantPool(),
10932 MVT::f32, false, false, 4);
10933 // Extend everything to 80 bits to force it to be done on x87.
10934 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10935 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10938 std::pair<SDValue,SDValue>
10939 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
10940 bool IsSigned, bool IsReplace) const {
10943 EVT DstTy = Op.getValueType();
10945 if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
10946 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
10950 assert(DstTy.getSimpleVT() <= MVT::i64 &&
10951 DstTy.getSimpleVT() >= MVT::i16 &&
10952 "Unknown FP_TO_INT to lower!");
10954 // These are really Legal.
10955 if (DstTy == MVT::i32 &&
10956 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10957 return std::make_pair(SDValue(), SDValue());
10958 if (Subtarget->is64Bit() &&
10959 DstTy == MVT::i64 &&
10960 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10961 return std::make_pair(SDValue(), SDValue());
10963 // We lower FP->int64 either into FISTP64 followed by a load from a temporary
10964 // stack slot, or into the FTOL runtime function.
10965 MachineFunction &MF = DAG.getMachineFunction();
10966 unsigned MemSize = DstTy.getSizeInBits()/8;
10967 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
10968 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10971 if (!IsSigned && isIntegerTypeFTOL(DstTy))
10972 Opc = X86ISD::WIN_FTOL;
10974 switch (DstTy.getSimpleVT().SimpleTy) {
10975 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
10976 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
10977 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
10978 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
10981 SDValue Chain = DAG.getEntryNode();
10982 SDValue Value = Op.getOperand(0);
10983 EVT TheVT = Op.getOperand(0).getValueType();
10984 // FIXME This causes a redundant load/store if the SSE-class value is already
10985 // in memory, such as if it is on the callstack.
10986 if (isScalarFPTypeInSSEReg(TheVT)) {
10987 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
10988 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
10989 MachinePointerInfo::getFixedStack(SSFI),
10991 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
10993 Chain, StackSlot, DAG.getValueType(TheVT)
10996 MachineMemOperand *MMO =
10997 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10998 MachineMemOperand::MOLoad, MemSize, MemSize);
10999 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11000 Chain = Value.getValue(1);
11001 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11002 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11005 MachineMemOperand *MMO =
11006 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11007 MachineMemOperand::MOStore, MemSize, MemSize);
11009 if (Opc != X86ISD::WIN_FTOL) {
11010 // Build the FP_TO_INT*_IN_MEM
11011 SDValue Ops[] = { Chain, Value, StackSlot };
11012 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11014 return std::make_pair(FIST, StackSlot);
11016 SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11017 DAG.getVTList(MVT::Other, MVT::Glue),
11019 SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11020 MVT::i32, ftol.getValue(1));
11021 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11022 MVT::i32, eax.getValue(2));
11023 SDValue Ops[] = { eax, edx };
11024 SDValue pair = IsReplace
11025 ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11026 : DAG.getMergeValues(Ops, DL);
11027 return std::make_pair(pair, SDValue());
11031 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11032 const X86Subtarget *Subtarget) {
11033 MVT VT = Op->getSimpleValueType(0);
11034 SDValue In = Op->getOperand(0);
11035 MVT InVT = In.getSimpleValueType();
11038 // Optimize vectors in AVX mode:
11041 // Use vpunpcklwd for 4 lower elements v8i16 -> v4i32.
11042 // Use vpunpckhwd for 4 upper elements v8i16 -> v4i32.
11043 // Concat upper and lower parts.
11046 // Use vpunpckldq for 4 lower elements v4i32 -> v2i64.
11047 // Use vpunpckhdq for 4 upper elements v4i32 -> v2i64.
11048 // Concat upper and lower parts.
11051 if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11052 ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11053 ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11056 if (Subtarget->hasInt256())
11057 return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11059 SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11060 SDValue Undef = DAG.getUNDEF(InVT);
11061 bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11062 SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11063 SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11065 MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11066 VT.getVectorNumElements()/2);
11068 OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11069 OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11071 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11074 static SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11075 SelectionDAG &DAG) {
11076 MVT VT = Op->getSimpleValueType(0);
11077 SDValue In = Op->getOperand(0);
11078 MVT InVT = In.getSimpleValueType();
11080 unsigned int NumElts = VT.getVectorNumElements();
11081 if (NumElts != 8 && NumElts != 16)
11084 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11085 return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11087 EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11088 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11089 // Now we have only mask extension
11090 assert(InVT.getVectorElementType() == MVT::i1);
11091 SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11092 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11093 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11094 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11095 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11096 MachinePointerInfo::getConstantPool(),
11097 false, false, false, Alignment);
11099 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11100 if (VT.is512BitVector())
11102 return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11105 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11106 SelectionDAG &DAG) {
11107 if (Subtarget->hasFp256()) {
11108 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11116 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11117 SelectionDAG &DAG) {
11119 MVT VT = Op.getSimpleValueType();
11120 SDValue In = Op.getOperand(0);
11121 MVT SVT = In.getSimpleValueType();
11123 if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11124 return LowerZERO_EXTEND_AVX512(Op, DAG);
11126 if (Subtarget->hasFp256()) {
11127 SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11132 assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11133 VT.getVectorNumElements() != SVT.getVectorNumElements());
11137 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11139 MVT VT = Op.getSimpleValueType();
11140 SDValue In = Op.getOperand(0);
11141 MVT InVT = In.getSimpleValueType();
11143 if (VT == MVT::i1) {
11144 assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11145 "Invalid scalar TRUNCATE operation");
11146 if (InVT == MVT::i32)
11148 if (InVT.getSizeInBits() == 64)
11149 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11150 else if (InVT.getSizeInBits() < 32)
11151 In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11152 return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11154 assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11155 "Invalid TRUNCATE operation");
11157 if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11158 if (VT.getVectorElementType().getSizeInBits() >=8)
11159 return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11161 assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11162 unsigned NumElts = InVT.getVectorNumElements();
11163 assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11164 if (InVT.getSizeInBits() < 512) {
11165 MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11166 In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11170 SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11171 const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11172 SDValue CP = DAG.getConstantPool(C, getPointerTy());
11173 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11174 SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11175 MachinePointerInfo::getConstantPool(),
11176 false, false, false, Alignment);
11177 SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11178 SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11179 return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11182 if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11183 // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11184 if (Subtarget->hasInt256()) {
11185 static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11186 In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11187 In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11189 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11190 DAG.getIntPtrConstant(0));
11193 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11194 DAG.getIntPtrConstant(0));
11195 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11196 DAG.getIntPtrConstant(2));
11197 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11198 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11199 static const int ShufMask[] = {0, 2, 4, 6};
11200 return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11203 if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11204 // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11205 if (Subtarget->hasInt256()) {
11206 In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11208 SmallVector<SDValue,32> pshufbMask;
11209 for (unsigned i = 0; i < 2; ++i) {
11210 pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11211 pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11212 pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11213 pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11214 pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11215 pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11216 pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11217 pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11218 for (unsigned j = 0; j < 8; ++j)
11219 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11221 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11222 In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11223 In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11225 static const int ShufMask[] = {0, 2, -1, -1};
11226 In = DAG.getVectorShuffle(MVT::v4i64, DL, In, DAG.getUNDEF(MVT::v4i64),
11228 In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11229 DAG.getIntPtrConstant(0));
11230 return DAG.getNode(ISD::BITCAST, DL, VT, In);
11233 SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11234 DAG.getIntPtrConstant(0));
11236 SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11237 DAG.getIntPtrConstant(4));
11239 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11240 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11242 // The PSHUFB mask:
11243 static const int ShufMask1[] = {0, 1, 4, 5, 8, 9, 12, 13,
11244 -1, -1, -1, -1, -1, -1, -1, -1};
11246 SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11247 OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11248 OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11250 OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11251 OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11253 // The MOVLHPS Mask:
11254 static const int ShufMask2[] = {0, 1, 4, 5};
11255 SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11256 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11259 // Handle truncation of V256 to V128 using shuffles.
11260 if (!VT.is128BitVector() || !InVT.is256BitVector())
11263 assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11265 unsigned NumElems = VT.getVectorNumElements();
11266 MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11268 SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11269 // Prepare truncation shuffle mask
11270 for (unsigned i = 0; i != NumElems; ++i)
11271 MaskVec[i] = i * 2;
11272 SDValue V = DAG.getVectorShuffle(NVT, DL,
11273 DAG.getNode(ISD::BITCAST, DL, NVT, In),
11274 DAG.getUNDEF(NVT), &MaskVec[0]);
11275 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11276 DAG.getIntPtrConstant(0));
11279 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11280 SelectionDAG &DAG) const {
11281 assert(!Op.getSimpleValueType().isVector());
11283 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11284 /*IsSigned=*/ true, /*IsReplace=*/ false);
11285 SDValue FIST = Vals.first, StackSlot = Vals.second;
11286 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11287 if (!FIST.getNode()) return Op;
11289 if (StackSlot.getNode())
11290 // Load the result.
11291 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11292 FIST, StackSlot, MachinePointerInfo(),
11293 false, false, false, 0);
11295 // The node is the result.
11299 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11300 SelectionDAG &DAG) const {
11301 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11302 /*IsSigned=*/ false, /*IsReplace=*/ false);
11303 SDValue FIST = Vals.first, StackSlot = Vals.second;
11304 assert(FIST.getNode() && "Unexpected failure");
11306 if (StackSlot.getNode())
11307 // Load the result.
11308 return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11309 FIST, StackSlot, MachinePointerInfo(),
11310 false, false, false, 0);
11312 // The node is the result.
11316 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11318 MVT VT = Op.getSimpleValueType();
11319 SDValue In = Op.getOperand(0);
11320 MVT SVT = In.getSimpleValueType();
11322 assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11324 return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11325 DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11326 In, DAG.getUNDEF(SVT)));
11329 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11330 LLVMContext *Context = DAG.getContext();
11332 MVT VT = Op.getSimpleValueType();
11334 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11335 if (VT.isVector()) {
11336 EltVT = VT.getVectorElementType();
11337 NumElts = VT.getVectorNumElements();
11340 if (EltVT == MVT::f64)
11341 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11342 APInt(64, ~(1ULL << 63))));
11344 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11345 APInt(32, ~(1U << 31))));
11346 C = ConstantVector::getSplat(NumElts, C);
11347 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11348 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11349 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11350 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11351 MachinePointerInfo::getConstantPool(),
11352 false, false, false, Alignment);
11353 if (VT.isVector()) {
11354 MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11355 return DAG.getNode(ISD::BITCAST, dl, VT,
11356 DAG.getNode(ISD::AND, dl, ANDVT,
11357 DAG.getNode(ISD::BITCAST, dl, ANDVT,
11359 DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11361 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11364 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11365 LLVMContext *Context = DAG.getContext();
11367 MVT VT = Op.getSimpleValueType();
11369 unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11370 if (VT.isVector()) {
11371 EltVT = VT.getVectorElementType();
11372 NumElts = VT.getVectorNumElements();
11375 if (EltVT == MVT::f64)
11376 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11377 APInt(64, 1ULL << 63)));
11379 C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11380 APInt(32, 1U << 31)));
11381 C = ConstantVector::getSplat(NumElts, C);
11382 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11383 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11384 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11385 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11386 MachinePointerInfo::getConstantPool(),
11387 false, false, false, Alignment);
11388 if (VT.isVector()) {
11389 MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11390 return DAG.getNode(ISD::BITCAST, dl, VT,
11391 DAG.getNode(ISD::XOR, dl, XORVT,
11392 DAG.getNode(ISD::BITCAST, dl, XORVT,
11394 DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11397 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11400 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11401 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11402 LLVMContext *Context = DAG.getContext();
11403 SDValue Op0 = Op.getOperand(0);
11404 SDValue Op1 = Op.getOperand(1);
11406 MVT VT = Op.getSimpleValueType();
11407 MVT SrcVT = Op1.getSimpleValueType();
11409 // If second operand is smaller, extend it first.
11410 if (SrcVT.bitsLT(VT)) {
11411 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11414 // And if it is bigger, shrink it first.
11415 if (SrcVT.bitsGT(VT)) {
11416 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11420 // At this point the operands and the result should have the same
11421 // type, and that won't be f80 since that is not custom lowered.
11423 // First get the sign bit of second operand.
11424 SmallVector<Constant*,4> CV;
11425 if (SrcVT == MVT::f64) {
11426 const fltSemantics &Sem = APFloat::IEEEdouble;
11427 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11428 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11430 const fltSemantics &Sem = APFloat::IEEEsingle;
11431 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11432 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11433 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11434 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11436 Constant *C = ConstantVector::get(CV);
11437 SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11438 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11439 MachinePointerInfo::getConstantPool(),
11440 false, false, false, 16);
11441 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11443 // Shift sign bit right or left if the two operands have different types.
11444 if (SrcVT.bitsGT(VT)) {
11445 // Op0 is MVT::f32, Op1 is MVT::f64.
11446 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11447 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11448 DAG.getConstant(32, MVT::i32));
11449 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11450 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11451 DAG.getIntPtrConstant(0));
11454 // Clear first operand sign bit.
11456 if (VT == MVT::f64) {
11457 const fltSemantics &Sem = APFloat::IEEEdouble;
11458 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11459 APInt(64, ~(1ULL << 63)))));
11460 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11462 const fltSemantics &Sem = APFloat::IEEEsingle;
11463 CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11464 APInt(32, ~(1U << 31)))));
11465 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11466 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11467 CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11469 C = ConstantVector::get(CV);
11470 CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11471 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11472 MachinePointerInfo::getConstantPool(),
11473 false, false, false, 16);
11474 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11476 // Or the value with the sign bit.
11477 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11480 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11481 SDValue N0 = Op.getOperand(0);
11483 MVT VT = Op.getSimpleValueType();
11485 // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11486 SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11487 DAG.getConstant(1, VT));
11488 return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11491 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11493 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11494 SelectionDAG &DAG) {
11495 assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11497 if (!Subtarget->hasSSE41())
11500 if (!Op->hasOneUse())
11503 SDNode *N = Op.getNode();
11506 SmallVector<SDValue, 8> Opnds;
11507 DenseMap<SDValue, unsigned> VecInMap;
11508 SmallVector<SDValue, 8> VecIns;
11509 EVT VT = MVT::Other;
11511 // Recognize a special case where a vector is casted into wide integer to
11513 Opnds.push_back(N->getOperand(0));
11514 Opnds.push_back(N->getOperand(1));
11516 for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11517 SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11518 // BFS traverse all OR'd operands.
11519 if (I->getOpcode() == ISD::OR) {
11520 Opnds.push_back(I->getOperand(0));
11521 Opnds.push_back(I->getOperand(1));
11522 // Re-evaluate the number of nodes to be traversed.
11523 e += 2; // 2 more nodes (LHS and RHS) are pushed.
11527 // Quit if a non-EXTRACT_VECTOR_ELT
11528 if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11531 // Quit if without a constant index.
11532 SDValue Idx = I->getOperand(1);
11533 if (!isa<ConstantSDNode>(Idx))
11536 SDValue ExtractedFromVec = I->getOperand(0);
11537 DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11538 if (M == VecInMap.end()) {
11539 VT = ExtractedFromVec.getValueType();
11540 // Quit if not 128/256-bit vector.
11541 if (!VT.is128BitVector() && !VT.is256BitVector())
11543 // Quit if not the same type.
11544 if (VecInMap.begin() != VecInMap.end() &&
11545 VT != VecInMap.begin()->first.getValueType())
11547 M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11548 VecIns.push_back(ExtractedFromVec);
11550 M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11553 assert((VT.is128BitVector() || VT.is256BitVector()) &&
11554 "Not extracted from 128-/256-bit vector.");
11556 unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11558 for (DenseMap<SDValue, unsigned>::const_iterator
11559 I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11560 // Quit if not all elements are used.
11561 if (I->second != FullMask)
11565 EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11567 // Cast all vectors into TestVT for PTEST.
11568 for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11569 VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11571 // If more than one full vectors are evaluated, OR them first before PTEST.
11572 for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11573 // Each iteration will OR 2 nodes and append the result until there is only
11574 // 1 node left, i.e. the final OR'd value of all vectors.
11575 SDValue LHS = VecIns[Slot];
11576 SDValue RHS = VecIns[Slot + 1];
11577 VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11580 return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11581 VecIns.back(), VecIns.back());
11584 /// \brief return true if \c Op has a use that doesn't just read flags.
11585 static bool hasNonFlagsUse(SDValue Op) {
11586 for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11588 SDNode *User = *UI;
11589 unsigned UOpNo = UI.getOperandNo();
11590 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11591 // Look pass truncate.
11592 UOpNo = User->use_begin().getOperandNo();
11593 User = *User->use_begin();
11596 if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11597 !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11603 /// Emit nodes that will be selected as "test Op0,Op0", or something
11605 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11606 SelectionDAG &DAG) const {
11607 if (Op.getValueType() == MVT::i1)
11608 // KORTEST instruction should be selected
11609 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11610 DAG.getConstant(0, Op.getValueType()));
11612 // CF and OF aren't always set the way we want. Determine which
11613 // of these we need.
11614 bool NeedCF = false;
11615 bool NeedOF = false;
11618 case X86::COND_A: case X86::COND_AE:
11619 case X86::COND_B: case X86::COND_BE:
11622 case X86::COND_G: case X86::COND_GE:
11623 case X86::COND_L: case X86::COND_LE:
11624 case X86::COND_O: case X86::COND_NO: {
11625 // Check if we really need to set the
11626 // Overflow flag. If NoSignedWrap is present
11627 // that is not actually needed.
11628 switch (Op->getOpcode()) {
11633 const BinaryWithFlagsSDNode *BinNode =
11634 cast<BinaryWithFlagsSDNode>(Op.getNode());
11635 if (BinNode->hasNoSignedWrap())
11645 // See if we can use the EFLAGS value from the operand instead of
11646 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11647 // we prove that the arithmetic won't overflow, we can't use OF or CF.
11648 if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11649 // Emit a CMP with 0, which is the TEST pattern.
11650 //if (Op.getValueType() == MVT::i1)
11651 // return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11652 // DAG.getConstant(0, MVT::i1));
11653 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11654 DAG.getConstant(0, Op.getValueType()));
11656 unsigned Opcode = 0;
11657 unsigned NumOperands = 0;
11659 // Truncate operations may prevent the merge of the SETCC instruction
11660 // and the arithmetic instruction before it. Attempt to truncate the operands
11661 // of the arithmetic instruction and use a reduced bit-width instruction.
11662 bool NeedTruncation = false;
11663 SDValue ArithOp = Op;
11664 if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11665 SDValue Arith = Op->getOperand(0);
11666 // Both the trunc and the arithmetic op need to have one user each.
11667 if (Arith->hasOneUse())
11668 switch (Arith.getOpcode()) {
11675 NeedTruncation = true;
11681 // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11682 // which may be the result of a CAST. We use the variable 'Op', which is the
11683 // non-casted variable when we check for possible users.
11684 switch (ArithOp.getOpcode()) {
11686 // Due to an isel shortcoming, be conservative if this add is likely to be
11687 // selected as part of a load-modify-store instruction. When the root node
11688 // in a match is a store, isel doesn't know how to remap non-chain non-flag
11689 // uses of other nodes in the match, such as the ADD in this case. This
11690 // leads to the ADD being left around and reselected, with the result being
11691 // two adds in the output. Alas, even if none our users are stores, that
11692 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
11693 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
11694 // climbing the DAG back to the root, and it doesn't seem to be worth the
11696 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11697 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11698 if (UI->getOpcode() != ISD::CopyToReg &&
11699 UI->getOpcode() != ISD::SETCC &&
11700 UI->getOpcode() != ISD::STORE)
11703 if (ConstantSDNode *C =
11704 dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11705 // An add of one will be selected as an INC.
11706 if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11707 Opcode = X86ISD::INC;
11712 // An add of negative one (subtract of one) will be selected as a DEC.
11713 if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11714 Opcode = X86ISD::DEC;
11720 // Otherwise use a regular EFLAGS-setting add.
11721 Opcode = X86ISD::ADD;
11726 // If we have a constant logical shift that's only used in a comparison
11727 // against zero turn it into an equivalent AND. This allows turning it into
11728 // a TEST instruction later.
11729 if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11730 isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11731 EVT VT = Op.getValueType();
11732 unsigned BitWidth = VT.getSizeInBits();
11733 unsigned ShAmt = Op->getConstantOperandVal(1);
11734 if (ShAmt >= BitWidth) // Avoid undefined shifts.
11736 APInt Mask = ArithOp.getOpcode() == ISD::SRL
11737 ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11738 : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11739 if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11741 SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11742 DAG.getConstant(Mask, VT));
11743 DAG.ReplaceAllUsesWith(Op, New);
11749 // If the primary and result isn't used, don't bother using X86ISD::AND,
11750 // because a TEST instruction will be better.
11751 if (!hasNonFlagsUse(Op))
11757 // Due to the ISEL shortcoming noted above, be conservative if this op is
11758 // likely to be selected as part of a load-modify-store instruction.
11759 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11760 UE = Op.getNode()->use_end(); UI != UE; ++UI)
11761 if (UI->getOpcode() == ISD::STORE)
11764 // Otherwise use a regular EFLAGS-setting instruction.
11765 switch (ArithOp.getOpcode()) {
11766 default: llvm_unreachable("unexpected operator!");
11767 case ISD::SUB: Opcode = X86ISD::SUB; break;
11768 case ISD::XOR: Opcode = X86ISD::XOR; break;
11769 case ISD::AND: Opcode = X86ISD::AND; break;
11771 if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11772 SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11773 if (EFLAGS.getNode())
11776 Opcode = X86ISD::OR;
11790 return SDValue(Op.getNode(), 1);
11796 // If we found that truncation is beneficial, perform the truncation and
11798 if (NeedTruncation) {
11799 EVT VT = Op.getValueType();
11800 SDValue WideVal = Op->getOperand(0);
11801 EVT WideVT = WideVal.getValueType();
11802 unsigned ConvertedOp = 0;
11803 // Use a target machine opcode to prevent further DAGCombine
11804 // optimizations that may separate the arithmetic operations
11805 // from the setcc node.
11806 switch (WideVal.getOpcode()) {
11808 case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11809 case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11810 case ISD::AND: ConvertedOp = X86ISD::AND; break;
11811 case ISD::OR: ConvertedOp = X86ISD::OR; break;
11812 case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11816 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11817 if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11818 SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11819 SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11820 Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11826 // Emit a CMP with 0, which is the TEST pattern.
11827 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11828 DAG.getConstant(0, Op.getValueType()));
11830 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11831 SmallVector<SDValue, 4> Ops;
11832 for (unsigned i = 0; i != NumOperands; ++i)
11833 Ops.push_back(Op.getOperand(i));
11835 SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11836 DAG.ReplaceAllUsesWith(Op, New);
11837 return SDValue(New.getNode(), 1);
11840 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11842 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11843 SDLoc dl, SelectionDAG &DAG) const {
11844 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11845 if (C->getAPIntValue() == 0)
11846 return EmitTest(Op0, X86CC, dl, DAG);
11848 if (Op0.getValueType() == MVT::i1)
11849 llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11852 if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11853 Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11854 // Do the comparison at i32 if it's smaller, besides the Atom case.
11855 // This avoids subregister aliasing issues. Keep the smaller reference
11856 // if we're optimizing for size, however, as that'll allow better folding
11857 // of memory operations.
11858 if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11859 !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11860 AttributeSet::FunctionIndex, Attribute::MinSize) &&
11861 !Subtarget->isAtom()) {
11862 unsigned ExtendOp =
11863 isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11864 Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11865 Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11867 // Use SUB instead of CMP to enable CSE between SUB and CMP.
11868 SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11869 SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11871 return SDValue(Sub.getNode(), 1);
11873 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11876 /// Convert a comparison if required by the subtarget.
11877 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11878 SelectionDAG &DAG) const {
11879 // If the subtarget does not support the FUCOMI instruction, floating-point
11880 // comparisons have to be converted.
11881 if (Subtarget->hasCMov() ||
11882 Cmp.getOpcode() != X86ISD::CMP ||
11883 !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11884 !Cmp.getOperand(1).getValueType().isFloatingPoint())
11887 // The instruction selector will select an FUCOM instruction instead of
11888 // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11889 // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11890 // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11892 SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11893 SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11894 SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11895 DAG.getConstant(8, MVT::i8));
11896 SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11897 return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11900 static bool isAllOnes(SDValue V) {
11901 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11902 return C && C->isAllOnesValue();
11905 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11906 /// if it's possible.
11907 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11908 SDLoc dl, SelectionDAG &DAG) const {
11909 SDValue Op0 = And.getOperand(0);
11910 SDValue Op1 = And.getOperand(1);
11911 if (Op0.getOpcode() == ISD::TRUNCATE)
11912 Op0 = Op0.getOperand(0);
11913 if (Op1.getOpcode() == ISD::TRUNCATE)
11914 Op1 = Op1.getOperand(0);
11917 if (Op1.getOpcode() == ISD::SHL)
11918 std::swap(Op0, Op1);
11919 if (Op0.getOpcode() == ISD::SHL) {
11920 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11921 if (And00C->getZExtValue() == 1) {
11922 // If we looked past a truncate, check that it's only truncating away
11924 unsigned BitWidth = Op0.getValueSizeInBits();
11925 unsigned AndBitWidth = And.getValueSizeInBits();
11926 if (BitWidth > AndBitWidth) {
11928 DAG.computeKnownBits(Op0, Zeros, Ones);
11929 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11933 RHS = Op0.getOperand(1);
11935 } else if (Op1.getOpcode() == ISD::Constant) {
11936 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11937 uint64_t AndRHSVal = AndRHS->getZExtValue();
11938 SDValue AndLHS = Op0;
11940 if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
11941 LHS = AndLHS.getOperand(0);
11942 RHS = AndLHS.getOperand(1);
11945 // Use BT if the immediate can't be encoded in a TEST instruction.
11946 if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
11948 RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
11952 if (LHS.getNode()) {
11953 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
11954 // instruction. Since the shift amount is in-range-or-undefined, we know
11955 // that doing a bittest on the i32 value is ok. We extend to i32 because
11956 // the encoding for the i16 version is larger than the i32 version.
11957 // Also promote i16 to i32 for performance / code size reason.
11958 if (LHS.getValueType() == MVT::i8 ||
11959 LHS.getValueType() == MVT::i16)
11960 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
11962 // If the operand types disagree, extend the shift amount to match. Since
11963 // BT ignores high bits (like shifts) we can use anyextend.
11964 if (LHS.getValueType() != RHS.getValueType())
11965 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
11967 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
11968 X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
11969 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11970 DAG.getConstant(Cond, MVT::i8), BT);
11976 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
11978 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
11983 // SSE Condition code mapping:
11992 switch (SetCCOpcode) {
11993 default: llvm_unreachable("Unexpected SETCC condition");
11995 case ISD::SETEQ: SSECC = 0; break;
11997 case ISD::SETGT: Swap = true; // Fallthrough
11999 case ISD::SETOLT: SSECC = 1; break;
12001 case ISD::SETGE: Swap = true; // Fallthrough
12003 case ISD::SETOLE: SSECC = 2; break;
12004 case ISD::SETUO: SSECC = 3; break;
12006 case ISD::SETNE: SSECC = 4; break;
12007 case ISD::SETULE: Swap = true; // Fallthrough
12008 case ISD::SETUGE: SSECC = 5; break;
12009 case ISD::SETULT: Swap = true; // Fallthrough
12010 case ISD::SETUGT: SSECC = 6; break;
12011 case ISD::SETO: SSECC = 7; break;
12013 case ISD::SETONE: SSECC = 8; break;
12016 std::swap(Op0, Op1);
12021 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12022 // ones, and then concatenate the result back.
12023 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12024 MVT VT = Op.getSimpleValueType();
12026 assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12027 "Unsupported value type for operation");
12029 unsigned NumElems = VT.getVectorNumElements();
12031 SDValue CC = Op.getOperand(2);
12033 // Extract the LHS vectors
12034 SDValue LHS = Op.getOperand(0);
12035 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12036 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12038 // Extract the RHS vectors
12039 SDValue RHS = Op.getOperand(1);
12040 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12041 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12043 // Issue the operation on the smaller types and concatenate the result back
12044 MVT EltVT = VT.getVectorElementType();
12045 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12046 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12047 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12048 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12051 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12052 const X86Subtarget *Subtarget) {
12053 SDValue Op0 = Op.getOperand(0);
12054 SDValue Op1 = Op.getOperand(1);
12055 SDValue CC = Op.getOperand(2);
12056 MVT VT = Op.getSimpleValueType();
12059 assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12060 Op.getValueType().getScalarType() == MVT::i1 &&
12061 "Cannot set masked compare for this operation");
12063 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12065 bool Unsigned = false;
12068 switch (SetCCOpcode) {
12069 default: llvm_unreachable("Unexpected SETCC condition");
12070 case ISD::SETNE: SSECC = 4; break;
12071 case ISD::SETEQ: Opc = X86ISD::PCMPEQM; break;
12072 case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12073 case ISD::SETLT: Swap = true; //fall-through
12074 case ISD::SETGT: Opc = X86ISD::PCMPGTM; break;
12075 case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12076 case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12077 case ISD::SETGE: Swap = true; SSECC = 2; break; // LE + swap
12078 case ISD::SETULE: Unsigned = true; //fall-through
12079 case ISD::SETLE: SSECC = 2; break;
12083 std::swap(Op0, Op1);
12085 return DAG.getNode(Opc, dl, VT, Op0, Op1);
12086 Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12087 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12088 DAG.getConstant(SSECC, MVT::i8));
12091 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12092 /// operand \p Op1. If non-trivial (for example because it's not constant)
12093 /// return an empty value.
12094 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12096 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12100 MVT VT = Op1.getSimpleValueType();
12101 MVT EVT = VT.getVectorElementType();
12102 unsigned n = VT.getVectorNumElements();
12103 SmallVector<SDValue, 8> ULTOp1;
12105 for (unsigned i = 0; i < n; ++i) {
12106 ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12107 if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12110 // Avoid underflow.
12111 APInt Val = Elt->getAPIntValue();
12115 ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12118 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12121 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12122 SelectionDAG &DAG) {
12123 SDValue Op0 = Op.getOperand(0);
12124 SDValue Op1 = Op.getOperand(1);
12125 SDValue CC = Op.getOperand(2);
12126 MVT VT = Op.getSimpleValueType();
12127 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12128 bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12133 MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12134 assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12137 unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12138 unsigned Opc = X86ISD::CMPP;
12139 if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12140 assert(VT.getVectorNumElements() <= 16);
12141 Opc = X86ISD::CMPM;
12143 // In the two special cases we can't handle, emit two comparisons.
12146 unsigned CombineOpc;
12147 if (SetCCOpcode == ISD::SETUEQ) {
12148 CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12150 assert(SetCCOpcode == ISD::SETONE);
12151 CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12154 SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12155 DAG.getConstant(CC0, MVT::i8));
12156 SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12157 DAG.getConstant(CC1, MVT::i8));
12158 return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12160 // Handle all other FP comparisons here.
12161 return DAG.getNode(Opc, dl, VT, Op0, Op1,
12162 DAG.getConstant(SSECC, MVT::i8));
12165 // Break 256-bit integer vector compare into smaller ones.
12166 if (VT.is256BitVector() && !Subtarget->hasInt256())
12167 return Lower256IntVSETCC(Op, DAG);
12169 bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12170 EVT OpVT = Op1.getValueType();
12171 if (Subtarget->hasAVX512()) {
12172 if (Op1.getValueType().is512BitVector() ||
12173 (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12174 return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12176 // In AVX-512 architecture setcc returns mask with i1 elements,
12177 // But there is no compare instruction for i8 and i16 elements.
12178 // We are not talking about 512-bit operands in this case, these
12179 // types are illegal.
12181 (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12182 OpVT.getVectorElementType().getSizeInBits() >= 8))
12183 return DAG.getNode(ISD::TRUNCATE, dl, VT,
12184 DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12187 // We are handling one of the integer comparisons here. Since SSE only has
12188 // GT and EQ comparisons for integer, swapping operands and multiple
12189 // operations may be required for some comparisons.
12191 bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12192 bool Subus = false;
12194 switch (SetCCOpcode) {
12195 default: llvm_unreachable("Unexpected SETCC condition");
12196 case ISD::SETNE: Invert = true;
12197 case ISD::SETEQ: Opc = X86ISD::PCMPEQ; break;
12198 case ISD::SETLT: Swap = true;
12199 case ISD::SETGT: Opc = X86ISD::PCMPGT; break;
12200 case ISD::SETGE: Swap = true;
12201 case ISD::SETLE: Opc = X86ISD::PCMPGT;
12202 Invert = true; break;
12203 case ISD::SETULT: Swap = true;
12204 case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12205 FlipSigns = true; break;
12206 case ISD::SETUGE: Swap = true;
12207 case ISD::SETULE: Opc = X86ISD::PCMPGT;
12208 FlipSigns = true; Invert = true; break;
12211 // Special case: Use min/max operations for SETULE/SETUGE
12212 MVT VET = VT.getVectorElementType();
12214 (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12215 || (Subtarget->hasSSE2() && (VET == MVT::i8));
12218 switch (SetCCOpcode) {
12220 case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12221 case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12224 if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12227 bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12228 if (!MinMax && hasSubus) {
12229 // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12231 // t = psubus Op0, Op1
12232 // pcmpeq t, <0..0>
12233 switch (SetCCOpcode) {
12235 case ISD::SETULT: {
12236 // If the comparison is against a constant we can turn this into a
12237 // setule. With psubus, setule does not require a swap. This is
12238 // beneficial because the constant in the register is no longer
12239 // destructed as the destination so it can be hoisted out of a loop.
12240 // Only do this pre-AVX since vpcmp* is no longer destructive.
12241 if (Subtarget->hasAVX())
12243 SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12244 if (ULEOp1.getNode()) {
12246 Subus = true; Invert = false; Swap = false;
12250 // Psubus is better than flip-sign because it requires no inversion.
12251 case ISD::SETUGE: Subus = true; Invert = false; Swap = true; break;
12252 case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12256 Opc = X86ISD::SUBUS;
12262 std::swap(Op0, Op1);
12264 // Check that the operation in question is available (most are plain SSE2,
12265 // but PCMPGTQ and PCMPEQQ have different requirements).
12266 if (VT == MVT::v2i64) {
12267 if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12268 assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12270 // First cast everything to the right type.
12271 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12272 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12274 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12275 // bits of the inputs before performing those operations. The lower
12276 // compare is always unsigned.
12279 SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12281 SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12282 SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12283 SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12284 Sign, Zero, Sign, Zero);
12286 Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12287 Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12289 // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12290 SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12291 SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12293 // Create masks for only the low parts/high parts of the 64 bit integers.
12294 static const int MaskHi[] = { 1, 1, 3, 3 };
12295 static const int MaskLo[] = { 0, 0, 2, 2 };
12296 SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12297 SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12298 SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12300 SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12301 Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12304 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12306 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12309 if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12310 // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12311 // pcmpeqd + pshufd + pand.
12312 assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12314 // First cast everything to the right type.
12315 Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12316 Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12319 SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12321 // Make sure the lower and upper halves are both all-ones.
12322 static const int Mask[] = { 1, 0, 3, 2 };
12323 SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12324 Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12327 Result = DAG.getNOT(dl, Result, MVT::v4i32);
12329 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12333 // Since SSE has no unsigned integer comparisons, we need to flip the sign
12334 // bits of the inputs before performing those operations.
12336 EVT EltVT = VT.getVectorElementType();
12337 SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12338 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12339 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12342 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12344 // If the logical-not of the result is required, perform that now.
12346 Result = DAG.getNOT(dl, Result, VT);
12349 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12352 Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12353 getZeroVector(VT, Subtarget, DAG, dl));
12358 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12360 MVT VT = Op.getSimpleValueType();
12362 if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12364 assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12365 && "SetCC type must be 8-bit or 1-bit integer");
12366 SDValue Op0 = Op.getOperand(0);
12367 SDValue Op1 = Op.getOperand(1);
12369 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12371 // Optimize to BT if possible.
12372 // Lower (X & (1 << N)) == 0 to BT(X, N).
12373 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12374 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12375 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12376 Op1.getOpcode() == ISD::Constant &&
12377 cast<ConstantSDNode>(Op1)->isNullValue() &&
12378 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12379 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12380 if (NewSetCC.getNode())
12384 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
12386 if (Op1.getOpcode() == ISD::Constant &&
12387 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12388 cast<ConstantSDNode>(Op1)->isNullValue()) &&
12389 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12391 // If the input is a setcc, then reuse the input setcc or use a new one with
12392 // the inverted condition.
12393 if (Op0.getOpcode() == X86ISD::SETCC) {
12394 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12395 bool Invert = (CC == ISD::SETNE) ^
12396 cast<ConstantSDNode>(Op1)->isNullValue();
12400 CCode = X86::GetOppositeBranchCondition(CCode);
12401 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12402 DAG.getConstant(CCode, MVT::i8),
12403 Op0.getOperand(1));
12405 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12409 if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12410 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12411 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12413 ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12414 return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12417 bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12418 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12419 if (X86CC == X86::COND_INVALID)
12422 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12423 EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12424 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12425 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12427 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12431 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12432 static bool isX86LogicalCmp(SDValue Op) {
12433 unsigned Opc = Op.getNode()->getOpcode();
12434 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12435 Opc == X86ISD::SAHF)
12437 if (Op.getResNo() == 1 &&
12438 (Opc == X86ISD::ADD ||
12439 Opc == X86ISD::SUB ||
12440 Opc == X86ISD::ADC ||
12441 Opc == X86ISD::SBB ||
12442 Opc == X86ISD::SMUL ||
12443 Opc == X86ISD::UMUL ||
12444 Opc == X86ISD::INC ||
12445 Opc == X86ISD::DEC ||
12446 Opc == X86ISD::OR ||
12447 Opc == X86ISD::XOR ||
12448 Opc == X86ISD::AND))
12451 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12457 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12458 if (V.getOpcode() != ISD::TRUNCATE)
12461 SDValue VOp0 = V.getOperand(0);
12462 unsigned InBits = VOp0.getValueSizeInBits();
12463 unsigned Bits = V.getValueSizeInBits();
12464 return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12467 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12468 bool addTest = true;
12469 SDValue Cond = Op.getOperand(0);
12470 SDValue Op1 = Op.getOperand(1);
12471 SDValue Op2 = Op.getOperand(2);
12473 EVT VT = Op1.getValueType();
12476 // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12477 // are available. Otherwise fp cmovs get lowered into a less efficient branch
12478 // sequence later on.
12479 if (Cond.getOpcode() == ISD::SETCC &&
12480 ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12481 (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12482 VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12483 SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12484 int SSECC = translateX86FSETCC(
12485 cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12488 if (Subtarget->hasAVX512()) {
12489 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12490 DAG.getConstant(SSECC, MVT::i8));
12491 return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12493 SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12494 DAG.getConstant(SSECC, MVT::i8));
12495 SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12496 SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12497 return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12501 if (Cond.getOpcode() == ISD::SETCC) {
12502 SDValue NewCond = LowerSETCC(Cond, DAG);
12503 if (NewCond.getNode())
12507 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12508 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12509 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12510 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12511 if (Cond.getOpcode() == X86ISD::SETCC &&
12512 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12513 isZero(Cond.getOperand(1).getOperand(1))) {
12514 SDValue Cmp = Cond.getOperand(1);
12516 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12518 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12519 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12520 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12522 SDValue CmpOp0 = Cmp.getOperand(0);
12523 // Apply further optimizations for special cases
12524 // (select (x != 0), -1, 0) -> neg & sbb
12525 // (select (x == 0), 0, -1) -> neg & sbb
12526 if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12527 if (YC->isNullValue() &&
12528 (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12529 SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12530 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12531 DAG.getConstant(0, CmpOp0.getValueType()),
12533 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12534 DAG.getConstant(X86::COND_B, MVT::i8),
12535 SDValue(Neg.getNode(), 1));
12539 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12540 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12541 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12543 SDValue Res = // Res = 0 or -1.
12544 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12545 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12547 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12548 Res = DAG.getNOT(DL, Res, Res.getValueType());
12550 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12551 if (!N2C || !N2C->isNullValue())
12552 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12557 // Look past (and (setcc_carry (cmp ...)), 1).
12558 if (Cond.getOpcode() == ISD::AND &&
12559 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12560 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12561 if (C && C->getAPIntValue() == 1)
12562 Cond = Cond.getOperand(0);
12565 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12566 // setting operand in place of the X86ISD::SETCC.
12567 unsigned CondOpcode = Cond.getOpcode();
12568 if (CondOpcode == X86ISD::SETCC ||
12569 CondOpcode == X86ISD::SETCC_CARRY) {
12570 CC = Cond.getOperand(0);
12572 SDValue Cmp = Cond.getOperand(1);
12573 unsigned Opc = Cmp.getOpcode();
12574 MVT VT = Op.getSimpleValueType();
12576 bool IllegalFPCMov = false;
12577 if (VT.isFloatingPoint() && !VT.isVector() &&
12578 !isScalarFPTypeInSSEReg(VT)) // FPStack?
12579 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12581 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12582 Opc == X86ISD::BT) { // FIXME
12586 } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12587 CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12588 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12589 Cond.getOperand(0).getValueType() != MVT::i8)) {
12590 SDValue LHS = Cond.getOperand(0);
12591 SDValue RHS = Cond.getOperand(1);
12592 unsigned X86Opcode;
12595 switch (CondOpcode) {
12596 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12597 case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12598 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12599 case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12600 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12601 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12602 default: llvm_unreachable("unexpected overflowing operator");
12604 if (CondOpcode == ISD::UMULO)
12605 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12608 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12610 SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12612 if (CondOpcode == ISD::UMULO)
12613 Cond = X86Op.getValue(2);
12615 Cond = X86Op.getValue(1);
12617 CC = DAG.getConstant(X86Cond, MVT::i8);
12622 // Look pass the truncate if the high bits are known zero.
12623 if (isTruncWithZeroHighBitsInput(Cond, DAG))
12624 Cond = Cond.getOperand(0);
12626 // We know the result of AND is compared against zero. Try to match
12628 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12629 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12630 if (NewSetCC.getNode()) {
12631 CC = NewSetCC.getOperand(0);
12632 Cond = NewSetCC.getOperand(1);
12639 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12640 Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12643 // a < b ? -1 : 0 -> RES = ~setcc_carry
12644 // a < b ? 0 : -1 -> RES = setcc_carry
12645 // a >= b ? -1 : 0 -> RES = setcc_carry
12646 // a >= b ? 0 : -1 -> RES = ~setcc_carry
12647 if (Cond.getOpcode() == X86ISD::SUB) {
12648 Cond = ConvertCmpIfNecessary(Cond, DAG);
12649 unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12651 if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12652 (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12653 SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12654 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12655 if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12656 return DAG.getNOT(DL, Res, Res.getValueType());
12661 // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12662 // widen the cmov and push the truncate through. This avoids introducing a new
12663 // branch during isel and doesn't add any extensions.
12664 if (Op.getValueType() == MVT::i8 &&
12665 Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12666 SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12667 if (T1.getValueType() == T2.getValueType() &&
12668 // Blacklist CopyFromReg to avoid partial register stalls.
12669 T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12670 SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12671 SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12672 return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12676 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12677 // condition is true.
12678 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12679 SDValue Ops[] = { Op2, Op1, CC, Cond };
12680 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12683 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12684 MVT VT = Op->getSimpleValueType(0);
12685 SDValue In = Op->getOperand(0);
12686 MVT InVT = In.getSimpleValueType();
12689 unsigned int NumElts = VT.getVectorNumElements();
12690 if (NumElts != 8 && NumElts != 16)
12693 if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12694 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12696 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12697 assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12699 MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12700 Constant *C = ConstantInt::get(*DAG.getContext(),
12701 APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12703 SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12704 unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12705 SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12706 MachinePointerInfo::getConstantPool(),
12707 false, false, false, Alignment);
12708 SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12709 if (VT.is512BitVector())
12711 return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12714 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12715 SelectionDAG &DAG) {
12716 MVT VT = Op->getSimpleValueType(0);
12717 SDValue In = Op->getOperand(0);
12718 MVT InVT = In.getSimpleValueType();
12721 if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12722 return LowerSIGN_EXTEND_AVX512(Op, DAG);
12724 if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12725 (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12726 (VT != MVT::v16i16 || InVT != MVT::v16i8))
12729 if (Subtarget->hasInt256())
12730 return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12732 // Optimize vectors in AVX mode
12733 // Sign extend v8i16 to v8i32 and
12736 // Divide input vector into two parts
12737 // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12738 // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12739 // concat the vectors to original VT
12741 unsigned NumElems = InVT.getVectorNumElements();
12742 SDValue Undef = DAG.getUNDEF(InVT);
12744 SmallVector<int,8> ShufMask1(NumElems, -1);
12745 for (unsigned i = 0; i != NumElems/2; ++i)
12748 SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12750 SmallVector<int,8> ShufMask2(NumElems, -1);
12751 for (unsigned i = 0; i != NumElems/2; ++i)
12752 ShufMask2[i] = i + NumElems/2;
12754 SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12756 MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12757 VT.getVectorNumElements()/2);
12759 OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12760 OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12762 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12765 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12766 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12767 // from the AND / OR.
12768 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12769 Opc = Op.getOpcode();
12770 if (Opc != ISD::OR && Opc != ISD::AND)
12772 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12773 Op.getOperand(0).hasOneUse() &&
12774 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12775 Op.getOperand(1).hasOneUse());
12778 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12779 // 1 and that the SETCC node has a single use.
12780 static bool isXor1OfSetCC(SDValue Op) {
12781 if (Op.getOpcode() != ISD::XOR)
12783 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12784 if (N1C && N1C->getAPIntValue() == 1) {
12785 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12786 Op.getOperand(0).hasOneUse();
12791 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12792 bool addTest = true;
12793 SDValue Chain = Op.getOperand(0);
12794 SDValue Cond = Op.getOperand(1);
12795 SDValue Dest = Op.getOperand(2);
12798 bool Inverted = false;
12800 if (Cond.getOpcode() == ISD::SETCC) {
12801 // Check for setcc([su]{add,sub,mul}o == 0).
12802 if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12803 isa<ConstantSDNode>(Cond.getOperand(1)) &&
12804 cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12805 Cond.getOperand(0).getResNo() == 1 &&
12806 (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12807 Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12808 Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12809 Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12810 Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12811 Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12813 Cond = Cond.getOperand(0);
12815 SDValue NewCond = LowerSETCC(Cond, DAG);
12816 if (NewCond.getNode())
12821 // FIXME: LowerXALUO doesn't handle these!!
12822 else if (Cond.getOpcode() == X86ISD::ADD ||
12823 Cond.getOpcode() == X86ISD::SUB ||
12824 Cond.getOpcode() == X86ISD::SMUL ||
12825 Cond.getOpcode() == X86ISD::UMUL)
12826 Cond = LowerXALUO(Cond, DAG);
12829 // Look pass (and (setcc_carry (cmp ...)), 1).
12830 if (Cond.getOpcode() == ISD::AND &&
12831 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12832 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12833 if (C && C->getAPIntValue() == 1)
12834 Cond = Cond.getOperand(0);
12837 // If condition flag is set by a X86ISD::CMP, then use it as the condition
12838 // setting operand in place of the X86ISD::SETCC.
12839 unsigned CondOpcode = Cond.getOpcode();
12840 if (CondOpcode == X86ISD::SETCC ||
12841 CondOpcode == X86ISD::SETCC_CARRY) {
12842 CC = Cond.getOperand(0);
12844 SDValue Cmp = Cond.getOperand(1);
12845 unsigned Opc = Cmp.getOpcode();
12846 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12847 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12851 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12855 // These can only come from an arithmetic instruction with overflow,
12856 // e.g. SADDO, UADDO.
12857 Cond = Cond.getNode()->getOperand(1);
12863 CondOpcode = Cond.getOpcode();
12864 if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12865 CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12866 ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12867 Cond.getOperand(0).getValueType() != MVT::i8)) {
12868 SDValue LHS = Cond.getOperand(0);
12869 SDValue RHS = Cond.getOperand(1);
12870 unsigned X86Opcode;
12873 // Keep this in sync with LowerXALUO, otherwise we might create redundant
12874 // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12876 switch (CondOpcode) {
12877 case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12879 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12881 X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12884 X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12885 case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12887 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12889 X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12892 X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12893 case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12894 case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12895 default: llvm_unreachable("unexpected overflowing operator");
12898 X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12899 if (CondOpcode == ISD::UMULO)
12900 VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12903 VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12905 SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12907 if (CondOpcode == ISD::UMULO)
12908 Cond = X86Op.getValue(2);
12910 Cond = X86Op.getValue(1);
12912 CC = DAG.getConstant(X86Cond, MVT::i8);
12916 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12917 SDValue Cmp = Cond.getOperand(0).getOperand(1);
12918 if (CondOpc == ISD::OR) {
12919 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12920 // two branches instead of an explicit OR instruction with a
12922 if (Cmp == Cond.getOperand(1).getOperand(1) &&
12923 isX86LogicalCmp(Cmp)) {
12924 CC = Cond.getOperand(0).getOperand(0);
12925 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12926 Chain, Dest, CC, Cmp);
12927 CC = Cond.getOperand(1).getOperand(0);
12931 } else { // ISD::AND
12932 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12933 // two branches instead of an explicit AND instruction with a
12934 // separate test. However, we only do this if this block doesn't
12935 // have a fall-through edge, because this requires an explicit
12936 // jmp when the condition is false.
12937 if (Cmp == Cond.getOperand(1).getOperand(1) &&
12938 isX86LogicalCmp(Cmp) &&
12939 Op.getNode()->hasOneUse()) {
12940 X86::CondCode CCode =
12941 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12942 CCode = X86::GetOppositeBranchCondition(CCode);
12943 CC = DAG.getConstant(CCode, MVT::i8);
12944 SDNode *User = *Op.getNode()->use_begin();
12945 // Look for an unconditional branch following this conditional branch.
12946 // We need this because we need to reverse the successors in order
12947 // to implement FCMP_OEQ.
12948 if (User->getOpcode() == ISD::BR) {
12949 SDValue FalseBB = User->getOperand(1);
12951 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12952 assert(NewBR == User);
12956 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12957 Chain, Dest, CC, Cmp);
12958 X86::CondCode CCode =
12959 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
12960 CCode = X86::GetOppositeBranchCondition(CCode);
12961 CC = DAG.getConstant(CCode, MVT::i8);
12967 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
12968 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
12969 // It should be transformed during dag combiner except when the condition
12970 // is set by a arithmetics with overflow node.
12971 X86::CondCode CCode =
12972 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12973 CCode = X86::GetOppositeBranchCondition(CCode);
12974 CC = DAG.getConstant(CCode, MVT::i8);
12975 Cond = Cond.getOperand(0).getOperand(1);
12977 } else if (Cond.getOpcode() == ISD::SETCC &&
12978 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
12979 // For FCMP_OEQ, we can emit
12980 // two branches instead of an explicit AND instruction with a
12981 // separate test. However, we only do this if this block doesn't
12982 // have a fall-through edge, because this requires an explicit
12983 // jmp when the condition is false.
12984 if (Op.getNode()->hasOneUse()) {
12985 SDNode *User = *Op.getNode()->use_begin();
12986 // Look for an unconditional branch following this conditional branch.
12987 // We need this because we need to reverse the successors in order
12988 // to implement FCMP_OEQ.
12989 if (User->getOpcode() == ISD::BR) {
12990 SDValue FalseBB = User->getOperand(1);
12992 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12993 assert(NewBR == User);
12997 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12998 Cond.getOperand(0), Cond.getOperand(1));
12999 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13000 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13001 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13002 Chain, Dest, CC, Cmp);
13003 CC = DAG.getConstant(X86::COND_P, MVT::i8);
13008 } else if (Cond.getOpcode() == ISD::SETCC &&
13009 cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13010 // For FCMP_UNE, we can emit
13011 // two branches instead of an explicit AND instruction with a
13012 // separate test. However, we only do this if this block doesn't
13013 // have a fall-through edge, because this requires an explicit
13014 // jmp when the condition is false.
13015 if (Op.getNode()->hasOneUse()) {
13016 SDNode *User = *Op.getNode()->use_begin();
13017 // Look for an unconditional branch following this conditional branch.
13018 // We need this because we need to reverse the successors in order
13019 // to implement FCMP_UNE.
13020 if (User->getOpcode() == ISD::BR) {
13021 SDValue FalseBB = User->getOperand(1);
13023 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13024 assert(NewBR == User);
13027 SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13028 Cond.getOperand(0), Cond.getOperand(1));
13029 Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13030 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13031 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13032 Chain, Dest, CC, Cmp);
13033 CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13043 // Look pass the truncate if the high bits are known zero.
13044 if (isTruncWithZeroHighBitsInput(Cond, DAG))
13045 Cond = Cond.getOperand(0);
13047 // We know the result of AND is compared against zero. Try to match
13049 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13050 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13051 if (NewSetCC.getNode()) {
13052 CC = NewSetCC.getOperand(0);
13053 Cond = NewSetCC.getOperand(1);
13060 X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13061 CC = DAG.getConstant(X86Cond, MVT::i8);
13062 Cond = EmitTest(Cond, X86Cond, dl, DAG);
13064 Cond = ConvertCmpIfNecessary(Cond, DAG);
13065 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13066 Chain, Dest, CC, Cond);
13069 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13070 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13071 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13072 // that the guard pages used by the OS virtual memory manager are allocated in
13073 // correct sequence.
13075 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13076 SelectionDAG &DAG) const {
13077 MachineFunction &MF = DAG.getMachineFunction();
13078 bool SplitStack = MF.shouldSplitStack();
13079 bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13084 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13085 SDNode* Node = Op.getNode();
13087 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13088 assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13089 " not tell us which reg is the stack pointer!");
13090 EVT VT = Node->getValueType(0);
13091 SDValue Tmp1 = SDValue(Node, 0);
13092 SDValue Tmp2 = SDValue(Node, 1);
13093 SDValue Tmp3 = Node->getOperand(2);
13094 SDValue Chain = Tmp1.getOperand(0);
13096 // Chain the dynamic stack allocation so that it doesn't modify the stack
13097 // pointer when other instructions are using the stack.
13098 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13101 SDValue Size = Tmp2.getOperand(1);
13102 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13103 Chain = SP.getValue(1);
13104 unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13105 const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13106 unsigned StackAlign = TFI.getStackAlignment();
13107 Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13108 if (Align > StackAlign)
13109 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13110 DAG.getConstant(-(uint64_t)Align, VT));
13111 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13113 Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13114 DAG.getIntPtrConstant(0, true), SDValue(),
13117 SDValue Ops[2] = { Tmp1, Tmp2 };
13118 return DAG.getMergeValues(Ops, dl);
13122 SDValue Chain = Op.getOperand(0);
13123 SDValue Size = Op.getOperand(1);
13124 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13125 EVT VT = Op.getNode()->getValueType(0);
13127 bool Is64Bit = Subtarget->is64Bit();
13128 EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13131 MachineRegisterInfo &MRI = MF.getRegInfo();
13134 // The 64 bit implementation of segmented stacks needs to clobber both r10
13135 // r11. This makes it impossible to use it along with nested parameters.
13136 const Function *F = MF.getFunction();
13138 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13140 if (I->hasNestAttr())
13141 report_fatal_error("Cannot use segmented stacks with functions that "
13142 "have nested arguments.");
13145 const TargetRegisterClass *AddrRegClass =
13146 getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13147 unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13148 Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13149 SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13150 DAG.getRegister(Vreg, SPTy));
13151 SDValue Ops1[2] = { Value, Chain };
13152 return DAG.getMergeValues(Ops1, dl);
13155 unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13157 Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13158 Flag = Chain.getValue(1);
13159 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13161 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13163 const X86RegisterInfo *RegInfo =
13164 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13165 unsigned SPReg = RegInfo->getStackRegister();
13166 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13167 Chain = SP.getValue(1);
13170 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13171 DAG.getConstant(-(uint64_t)Align, VT));
13172 Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13175 SDValue Ops1[2] = { SP, Chain };
13176 return DAG.getMergeValues(Ops1, dl);
13180 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13181 MachineFunction &MF = DAG.getMachineFunction();
13182 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13184 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13187 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13188 // vastart just stores the address of the VarArgsFrameIndex slot into the
13189 // memory location argument.
13190 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13192 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13193 MachinePointerInfo(SV), false, false, 0);
13197 // gp_offset (0 - 6 * 8)
13198 // fp_offset (48 - 48 + 8 * 16)
13199 // overflow_arg_area (point to parameters coming in memory).
13201 SmallVector<SDValue, 8> MemOps;
13202 SDValue FIN = Op.getOperand(1);
13204 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13205 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13207 FIN, MachinePointerInfo(SV), false, false, 0);
13208 MemOps.push_back(Store);
13211 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13212 FIN, DAG.getIntPtrConstant(4));
13213 Store = DAG.getStore(Op.getOperand(0), DL,
13214 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13216 FIN, MachinePointerInfo(SV, 4), false, false, 0);
13217 MemOps.push_back(Store);
13219 // Store ptr to overflow_arg_area
13220 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13221 FIN, DAG.getIntPtrConstant(4));
13222 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13224 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13225 MachinePointerInfo(SV, 8),
13227 MemOps.push_back(Store);
13229 // Store ptr to reg_save_area.
13230 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13231 FIN, DAG.getIntPtrConstant(8));
13232 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13234 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13235 MachinePointerInfo(SV, 16), false, false, 0);
13236 MemOps.push_back(Store);
13237 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13240 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13241 assert(Subtarget->is64Bit() &&
13242 "LowerVAARG only handles 64-bit va_arg!");
13243 assert((Subtarget->isTargetLinux() ||
13244 Subtarget->isTargetDarwin()) &&
13245 "Unhandled target in LowerVAARG");
13246 assert(Op.getNode()->getNumOperands() == 4);
13247 SDValue Chain = Op.getOperand(0);
13248 SDValue SrcPtr = Op.getOperand(1);
13249 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13250 unsigned Align = Op.getConstantOperandVal(3);
13253 EVT ArgVT = Op.getNode()->getValueType(0);
13254 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13255 uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13258 // Decide which area this value should be read from.
13259 // TODO: Implement the AMD64 ABI in its entirety. This simple
13260 // selection mechanism works only for the basic types.
13261 if (ArgVT == MVT::f80) {
13262 llvm_unreachable("va_arg for f80 not yet implemented");
13263 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13264 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
13265 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13266 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
13268 llvm_unreachable("Unhandled argument type in LowerVAARG");
13271 if (ArgMode == 2) {
13272 // Sanity Check: Make sure using fp_offset makes sense.
13273 assert(!DAG.getTarget().Options.UseSoftFloat &&
13274 !(DAG.getMachineFunction()
13275 .getFunction()->getAttributes()
13276 .hasAttribute(AttributeSet::FunctionIndex,
13277 Attribute::NoImplicitFloat)) &&
13278 Subtarget->hasSSE1());
13281 // Insert VAARG_64 node into the DAG
13282 // VAARG_64 returns two values: Variable Argument Address, Chain
13283 SmallVector<SDValue, 11> InstOps;
13284 InstOps.push_back(Chain);
13285 InstOps.push_back(SrcPtr);
13286 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13287 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13288 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13289 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13290 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13291 VTs, InstOps, MVT::i64,
13292 MachinePointerInfo(SV),
13294 /*Volatile=*/false,
13296 /*WriteMem=*/true);
13297 Chain = VAARG.getValue(1);
13299 // Load the next argument and return it
13300 return DAG.getLoad(ArgVT, dl,
13303 MachinePointerInfo(),
13304 false, false, false, 0);
13307 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13308 SelectionDAG &DAG) {
13309 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13310 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13311 SDValue Chain = Op.getOperand(0);
13312 SDValue DstPtr = Op.getOperand(1);
13313 SDValue SrcPtr = Op.getOperand(2);
13314 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13315 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13318 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13319 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13321 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13324 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13325 // amount is a constant. Takes immediate version of shift as input.
13326 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13327 SDValue SrcOp, uint64_t ShiftAmt,
13328 SelectionDAG &DAG) {
13329 MVT ElementType = VT.getVectorElementType();
13331 // Fold this packed shift into its first operand if ShiftAmt is 0.
13335 // Check for ShiftAmt >= element width
13336 if (ShiftAmt >= ElementType.getSizeInBits()) {
13337 if (Opc == X86ISD::VSRAI)
13338 ShiftAmt = ElementType.getSizeInBits() - 1;
13340 return DAG.getConstant(0, VT);
13343 assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13344 && "Unknown target vector shift-by-constant node");
13346 // Fold this packed vector shift into a build vector if SrcOp is a
13347 // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13348 if (VT == SrcOp.getSimpleValueType() &&
13349 ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13350 SmallVector<SDValue, 8> Elts;
13351 unsigned NumElts = SrcOp->getNumOperands();
13352 ConstantSDNode *ND;
13355 default: llvm_unreachable(nullptr);
13356 case X86ISD::VSHLI:
13357 for (unsigned i=0; i!=NumElts; ++i) {
13358 SDValue CurrentOp = SrcOp->getOperand(i);
13359 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13360 Elts.push_back(CurrentOp);
13363 ND = cast<ConstantSDNode>(CurrentOp);
13364 const APInt &C = ND->getAPIntValue();
13365 Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13368 case X86ISD::VSRLI:
13369 for (unsigned i=0; i!=NumElts; ++i) {
13370 SDValue CurrentOp = SrcOp->getOperand(i);
13371 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13372 Elts.push_back(CurrentOp);
13375 ND = cast<ConstantSDNode>(CurrentOp);
13376 const APInt &C = ND->getAPIntValue();
13377 Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13380 case X86ISD::VSRAI:
13381 for (unsigned i=0; i!=NumElts; ++i) {
13382 SDValue CurrentOp = SrcOp->getOperand(i);
13383 if (CurrentOp->getOpcode() == ISD::UNDEF) {
13384 Elts.push_back(CurrentOp);
13387 ND = cast<ConstantSDNode>(CurrentOp);
13388 const APInt &C = ND->getAPIntValue();
13389 Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13394 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13397 return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13400 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13401 // may or may not be a constant. Takes immediate version of shift as input.
13402 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13403 SDValue SrcOp, SDValue ShAmt,
13404 SelectionDAG &DAG) {
13405 assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13407 // Catch shift-by-constant.
13408 if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13409 return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13410 CShAmt->getZExtValue(), DAG);
13412 // Change opcode to non-immediate version
13414 default: llvm_unreachable("Unknown target vector shift node");
13415 case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13416 case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13417 case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13420 // Need to build a vector containing shift amount
13421 // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13424 ShOps[1] = DAG.getConstant(0, MVT::i32);
13425 ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13426 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13428 // The return type has to be a 128-bit type with the same element
13429 // type as the input type.
13430 MVT EltVT = VT.getVectorElementType();
13431 EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13433 ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13434 return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13437 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13439 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13441 default: return SDValue(); // Don't custom lower most intrinsics.
13442 // Comparison intrinsics.
13443 case Intrinsic::x86_sse_comieq_ss:
13444 case Intrinsic::x86_sse_comilt_ss:
13445 case Intrinsic::x86_sse_comile_ss:
13446 case Intrinsic::x86_sse_comigt_ss:
13447 case Intrinsic::x86_sse_comige_ss:
13448 case Intrinsic::x86_sse_comineq_ss:
13449 case Intrinsic::x86_sse_ucomieq_ss:
13450 case Intrinsic::x86_sse_ucomilt_ss:
13451 case Intrinsic::x86_sse_ucomile_ss:
13452 case Intrinsic::x86_sse_ucomigt_ss:
13453 case Intrinsic::x86_sse_ucomige_ss:
13454 case Intrinsic::x86_sse_ucomineq_ss:
13455 case Intrinsic::x86_sse2_comieq_sd:
13456 case Intrinsic::x86_sse2_comilt_sd:
13457 case Intrinsic::x86_sse2_comile_sd:
13458 case Intrinsic::x86_sse2_comigt_sd:
13459 case Intrinsic::x86_sse2_comige_sd:
13460 case Intrinsic::x86_sse2_comineq_sd:
13461 case Intrinsic::x86_sse2_ucomieq_sd:
13462 case Intrinsic::x86_sse2_ucomilt_sd:
13463 case Intrinsic::x86_sse2_ucomile_sd:
13464 case Intrinsic::x86_sse2_ucomigt_sd:
13465 case Intrinsic::x86_sse2_ucomige_sd:
13466 case Intrinsic::x86_sse2_ucomineq_sd: {
13470 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13471 case Intrinsic::x86_sse_comieq_ss:
13472 case Intrinsic::x86_sse2_comieq_sd:
13473 Opc = X86ISD::COMI;
13476 case Intrinsic::x86_sse_comilt_ss:
13477 case Intrinsic::x86_sse2_comilt_sd:
13478 Opc = X86ISD::COMI;
13481 case Intrinsic::x86_sse_comile_ss:
13482 case Intrinsic::x86_sse2_comile_sd:
13483 Opc = X86ISD::COMI;
13486 case Intrinsic::x86_sse_comigt_ss:
13487 case Intrinsic::x86_sse2_comigt_sd:
13488 Opc = X86ISD::COMI;
13491 case Intrinsic::x86_sse_comige_ss:
13492 case Intrinsic::x86_sse2_comige_sd:
13493 Opc = X86ISD::COMI;
13496 case Intrinsic::x86_sse_comineq_ss:
13497 case Intrinsic::x86_sse2_comineq_sd:
13498 Opc = X86ISD::COMI;
13501 case Intrinsic::x86_sse_ucomieq_ss:
13502 case Intrinsic::x86_sse2_ucomieq_sd:
13503 Opc = X86ISD::UCOMI;
13506 case Intrinsic::x86_sse_ucomilt_ss:
13507 case Intrinsic::x86_sse2_ucomilt_sd:
13508 Opc = X86ISD::UCOMI;
13511 case Intrinsic::x86_sse_ucomile_ss:
13512 case Intrinsic::x86_sse2_ucomile_sd:
13513 Opc = X86ISD::UCOMI;
13516 case Intrinsic::x86_sse_ucomigt_ss:
13517 case Intrinsic::x86_sse2_ucomigt_sd:
13518 Opc = X86ISD::UCOMI;
13521 case Intrinsic::x86_sse_ucomige_ss:
13522 case Intrinsic::x86_sse2_ucomige_sd:
13523 Opc = X86ISD::UCOMI;
13526 case Intrinsic::x86_sse_ucomineq_ss:
13527 case Intrinsic::x86_sse2_ucomineq_sd:
13528 Opc = X86ISD::UCOMI;
13533 SDValue LHS = Op.getOperand(1);
13534 SDValue RHS = Op.getOperand(2);
13535 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13536 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13537 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13538 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13539 DAG.getConstant(X86CC, MVT::i8), Cond);
13540 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13543 // Arithmetic intrinsics.
13544 case Intrinsic::x86_sse2_pmulu_dq:
13545 case Intrinsic::x86_avx2_pmulu_dq:
13546 return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13547 Op.getOperand(1), Op.getOperand(2));
13549 case Intrinsic::x86_sse41_pmuldq:
13550 case Intrinsic::x86_avx2_pmul_dq:
13551 return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13552 Op.getOperand(1), Op.getOperand(2));
13554 case Intrinsic::x86_sse2_pmulhu_w:
13555 case Intrinsic::x86_avx2_pmulhu_w:
13556 return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13557 Op.getOperand(1), Op.getOperand(2));
13559 case Intrinsic::x86_sse2_pmulh_w:
13560 case Intrinsic::x86_avx2_pmulh_w:
13561 return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13562 Op.getOperand(1), Op.getOperand(2));
13564 // SSE2/AVX2 sub with unsigned saturation intrinsics
13565 case Intrinsic::x86_sse2_psubus_b:
13566 case Intrinsic::x86_sse2_psubus_w:
13567 case Intrinsic::x86_avx2_psubus_b:
13568 case Intrinsic::x86_avx2_psubus_w:
13569 return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13570 Op.getOperand(1), Op.getOperand(2));
13572 // SSE3/AVX horizontal add/sub intrinsics
13573 case Intrinsic::x86_sse3_hadd_ps:
13574 case Intrinsic::x86_sse3_hadd_pd:
13575 case Intrinsic::x86_avx_hadd_ps_256:
13576 case Intrinsic::x86_avx_hadd_pd_256:
13577 case Intrinsic::x86_sse3_hsub_ps:
13578 case Intrinsic::x86_sse3_hsub_pd:
13579 case Intrinsic::x86_avx_hsub_ps_256:
13580 case Intrinsic::x86_avx_hsub_pd_256:
13581 case Intrinsic::x86_ssse3_phadd_w_128:
13582 case Intrinsic::x86_ssse3_phadd_d_128:
13583 case Intrinsic::x86_avx2_phadd_w:
13584 case Intrinsic::x86_avx2_phadd_d:
13585 case Intrinsic::x86_ssse3_phsub_w_128:
13586 case Intrinsic::x86_ssse3_phsub_d_128:
13587 case Intrinsic::x86_avx2_phsub_w:
13588 case Intrinsic::x86_avx2_phsub_d: {
13591 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13592 case Intrinsic::x86_sse3_hadd_ps:
13593 case Intrinsic::x86_sse3_hadd_pd:
13594 case Intrinsic::x86_avx_hadd_ps_256:
13595 case Intrinsic::x86_avx_hadd_pd_256:
13596 Opcode = X86ISD::FHADD;
13598 case Intrinsic::x86_sse3_hsub_ps:
13599 case Intrinsic::x86_sse3_hsub_pd:
13600 case Intrinsic::x86_avx_hsub_ps_256:
13601 case Intrinsic::x86_avx_hsub_pd_256:
13602 Opcode = X86ISD::FHSUB;
13604 case Intrinsic::x86_ssse3_phadd_w_128:
13605 case Intrinsic::x86_ssse3_phadd_d_128:
13606 case Intrinsic::x86_avx2_phadd_w:
13607 case Intrinsic::x86_avx2_phadd_d:
13608 Opcode = X86ISD::HADD;
13610 case Intrinsic::x86_ssse3_phsub_w_128:
13611 case Intrinsic::x86_ssse3_phsub_d_128:
13612 case Intrinsic::x86_avx2_phsub_w:
13613 case Intrinsic::x86_avx2_phsub_d:
13614 Opcode = X86ISD::HSUB;
13617 return DAG.getNode(Opcode, dl, Op.getValueType(),
13618 Op.getOperand(1), Op.getOperand(2));
13621 // SSE2/SSE41/AVX2 integer max/min intrinsics.
13622 case Intrinsic::x86_sse2_pmaxu_b:
13623 case Intrinsic::x86_sse41_pmaxuw:
13624 case Intrinsic::x86_sse41_pmaxud:
13625 case Intrinsic::x86_avx2_pmaxu_b:
13626 case Intrinsic::x86_avx2_pmaxu_w:
13627 case Intrinsic::x86_avx2_pmaxu_d:
13628 case Intrinsic::x86_sse2_pminu_b:
13629 case Intrinsic::x86_sse41_pminuw:
13630 case Intrinsic::x86_sse41_pminud:
13631 case Intrinsic::x86_avx2_pminu_b:
13632 case Intrinsic::x86_avx2_pminu_w:
13633 case Intrinsic::x86_avx2_pminu_d:
13634 case Intrinsic::x86_sse41_pmaxsb:
13635 case Intrinsic::x86_sse2_pmaxs_w:
13636 case Intrinsic::x86_sse41_pmaxsd:
13637 case Intrinsic::x86_avx2_pmaxs_b:
13638 case Intrinsic::x86_avx2_pmaxs_w:
13639 case Intrinsic::x86_avx2_pmaxs_d:
13640 case Intrinsic::x86_sse41_pminsb:
13641 case Intrinsic::x86_sse2_pmins_w:
13642 case Intrinsic::x86_sse41_pminsd:
13643 case Intrinsic::x86_avx2_pmins_b:
13644 case Intrinsic::x86_avx2_pmins_w:
13645 case Intrinsic::x86_avx2_pmins_d: {
13648 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13649 case Intrinsic::x86_sse2_pmaxu_b:
13650 case Intrinsic::x86_sse41_pmaxuw:
13651 case Intrinsic::x86_sse41_pmaxud:
13652 case Intrinsic::x86_avx2_pmaxu_b:
13653 case Intrinsic::x86_avx2_pmaxu_w:
13654 case Intrinsic::x86_avx2_pmaxu_d:
13655 Opcode = X86ISD::UMAX;
13657 case Intrinsic::x86_sse2_pminu_b:
13658 case Intrinsic::x86_sse41_pminuw:
13659 case Intrinsic::x86_sse41_pminud:
13660 case Intrinsic::x86_avx2_pminu_b:
13661 case Intrinsic::x86_avx2_pminu_w:
13662 case Intrinsic::x86_avx2_pminu_d:
13663 Opcode = X86ISD::UMIN;
13665 case Intrinsic::x86_sse41_pmaxsb:
13666 case Intrinsic::x86_sse2_pmaxs_w:
13667 case Intrinsic::x86_sse41_pmaxsd:
13668 case Intrinsic::x86_avx2_pmaxs_b:
13669 case Intrinsic::x86_avx2_pmaxs_w:
13670 case Intrinsic::x86_avx2_pmaxs_d:
13671 Opcode = X86ISD::SMAX;
13673 case Intrinsic::x86_sse41_pminsb:
13674 case Intrinsic::x86_sse2_pmins_w:
13675 case Intrinsic::x86_sse41_pminsd:
13676 case Intrinsic::x86_avx2_pmins_b:
13677 case Intrinsic::x86_avx2_pmins_w:
13678 case Intrinsic::x86_avx2_pmins_d:
13679 Opcode = X86ISD::SMIN;
13682 return DAG.getNode(Opcode, dl, Op.getValueType(),
13683 Op.getOperand(1), Op.getOperand(2));
13686 // SSE/SSE2/AVX floating point max/min intrinsics.
13687 case Intrinsic::x86_sse_max_ps:
13688 case Intrinsic::x86_sse2_max_pd:
13689 case Intrinsic::x86_avx_max_ps_256:
13690 case Intrinsic::x86_avx_max_pd_256:
13691 case Intrinsic::x86_sse_min_ps:
13692 case Intrinsic::x86_sse2_min_pd:
13693 case Intrinsic::x86_avx_min_ps_256:
13694 case Intrinsic::x86_avx_min_pd_256: {
13697 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13698 case Intrinsic::x86_sse_max_ps:
13699 case Intrinsic::x86_sse2_max_pd:
13700 case Intrinsic::x86_avx_max_ps_256:
13701 case Intrinsic::x86_avx_max_pd_256:
13702 Opcode = X86ISD::FMAX;
13704 case Intrinsic::x86_sse_min_ps:
13705 case Intrinsic::x86_sse2_min_pd:
13706 case Intrinsic::x86_avx_min_ps_256:
13707 case Intrinsic::x86_avx_min_pd_256:
13708 Opcode = X86ISD::FMIN;
13711 return DAG.getNode(Opcode, dl, Op.getValueType(),
13712 Op.getOperand(1), Op.getOperand(2));
13715 // AVX2 variable shift intrinsics
13716 case Intrinsic::x86_avx2_psllv_d:
13717 case Intrinsic::x86_avx2_psllv_q:
13718 case Intrinsic::x86_avx2_psllv_d_256:
13719 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:
13724 case Intrinsic::x86_avx2_psrav_d:
13725 case Intrinsic::x86_avx2_psrav_d_256: {
13728 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13729 case Intrinsic::x86_avx2_psllv_d:
13730 case Intrinsic::x86_avx2_psllv_q:
13731 case Intrinsic::x86_avx2_psllv_d_256:
13732 case Intrinsic::x86_avx2_psllv_q_256:
13735 case Intrinsic::x86_avx2_psrlv_d:
13736 case Intrinsic::x86_avx2_psrlv_q:
13737 case Intrinsic::x86_avx2_psrlv_d_256:
13738 case Intrinsic::x86_avx2_psrlv_q_256:
13741 case Intrinsic::x86_avx2_psrav_d:
13742 case Intrinsic::x86_avx2_psrav_d_256:
13746 return DAG.getNode(Opcode, dl, Op.getValueType(),
13747 Op.getOperand(1), Op.getOperand(2));
13750 case Intrinsic::x86_sse2_packssdw_128:
13751 case Intrinsic::x86_sse2_packsswb_128:
13752 case Intrinsic::x86_avx2_packssdw:
13753 case Intrinsic::x86_avx2_packsswb:
13754 return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13755 Op.getOperand(1), Op.getOperand(2));
13757 case Intrinsic::x86_sse2_packuswb_128:
13758 case Intrinsic::x86_sse41_packusdw:
13759 case Intrinsic::x86_avx2_packuswb:
13760 case Intrinsic::x86_avx2_packusdw:
13761 return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13762 Op.getOperand(1), Op.getOperand(2));
13764 case Intrinsic::x86_ssse3_pshuf_b_128:
13765 case Intrinsic::x86_avx2_pshuf_b:
13766 return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13767 Op.getOperand(1), Op.getOperand(2));
13769 case Intrinsic::x86_sse2_pshuf_d:
13770 return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13771 Op.getOperand(1), Op.getOperand(2));
13773 case Intrinsic::x86_sse2_pshufl_w:
13774 return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13775 Op.getOperand(1), Op.getOperand(2));
13777 case Intrinsic::x86_sse2_pshufh_w:
13778 return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13779 Op.getOperand(1), Op.getOperand(2));
13781 case Intrinsic::x86_ssse3_psign_b_128:
13782 case Intrinsic::x86_ssse3_psign_w_128:
13783 case Intrinsic::x86_ssse3_psign_d_128:
13784 case Intrinsic::x86_avx2_psign_b:
13785 case Intrinsic::x86_avx2_psign_w:
13786 case Intrinsic::x86_avx2_psign_d:
13787 return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13788 Op.getOperand(1), Op.getOperand(2));
13790 case Intrinsic::x86_sse41_insertps:
13791 return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13792 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13794 case Intrinsic::x86_avx_vperm2f128_ps_256:
13795 case Intrinsic::x86_avx_vperm2f128_pd_256:
13796 case Intrinsic::x86_avx_vperm2f128_si_256:
13797 case Intrinsic::x86_avx2_vperm2i128:
13798 return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13799 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13801 case Intrinsic::x86_avx2_permd:
13802 case Intrinsic::x86_avx2_permps:
13803 // Operands intentionally swapped. Mask is last operand to intrinsic,
13804 // but second operand for node/instruction.
13805 return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13806 Op.getOperand(2), Op.getOperand(1));
13808 case Intrinsic::x86_sse_sqrt_ps:
13809 case Intrinsic::x86_sse2_sqrt_pd:
13810 case Intrinsic::x86_avx_sqrt_ps_256:
13811 case Intrinsic::x86_avx_sqrt_pd_256:
13812 return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13814 // ptest and testp intrinsics. The intrinsic these come from are designed to
13815 // return an integer value, not just an instruction so lower it to the ptest
13816 // or testp pattern and a setcc for the result.
13817 case Intrinsic::x86_sse41_ptestz:
13818 case Intrinsic::x86_sse41_ptestc:
13819 case Intrinsic::x86_sse41_ptestnzc:
13820 case Intrinsic::x86_avx_ptestz_256:
13821 case Intrinsic::x86_avx_ptestc_256:
13822 case Intrinsic::x86_avx_ptestnzc_256:
13823 case Intrinsic::x86_avx_vtestz_ps:
13824 case Intrinsic::x86_avx_vtestc_ps:
13825 case Intrinsic::x86_avx_vtestnzc_ps:
13826 case Intrinsic::x86_avx_vtestz_pd:
13827 case Intrinsic::x86_avx_vtestc_pd:
13828 case Intrinsic::x86_avx_vtestnzc_pd:
13829 case Intrinsic::x86_avx_vtestz_ps_256:
13830 case Intrinsic::x86_avx_vtestc_ps_256:
13831 case Intrinsic::x86_avx_vtestnzc_ps_256:
13832 case Intrinsic::x86_avx_vtestz_pd_256:
13833 case Intrinsic::x86_avx_vtestc_pd_256:
13834 case Intrinsic::x86_avx_vtestnzc_pd_256: {
13835 bool IsTestPacked = false;
13838 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13839 case Intrinsic::x86_avx_vtestz_ps:
13840 case Intrinsic::x86_avx_vtestz_pd:
13841 case Intrinsic::x86_avx_vtestz_ps_256:
13842 case Intrinsic::x86_avx_vtestz_pd_256:
13843 IsTestPacked = true; // Fallthrough
13844 case Intrinsic::x86_sse41_ptestz:
13845 case Intrinsic::x86_avx_ptestz_256:
13847 X86CC = X86::COND_E;
13849 case Intrinsic::x86_avx_vtestc_ps:
13850 case Intrinsic::x86_avx_vtestc_pd:
13851 case Intrinsic::x86_avx_vtestc_ps_256:
13852 case Intrinsic::x86_avx_vtestc_pd_256:
13853 IsTestPacked = true; // Fallthrough
13854 case Intrinsic::x86_sse41_ptestc:
13855 case Intrinsic::x86_avx_ptestc_256:
13857 X86CC = X86::COND_B;
13859 case Intrinsic::x86_avx_vtestnzc_ps:
13860 case Intrinsic::x86_avx_vtestnzc_pd:
13861 case Intrinsic::x86_avx_vtestnzc_ps_256:
13862 case Intrinsic::x86_avx_vtestnzc_pd_256:
13863 IsTestPacked = true; // Fallthrough
13864 case Intrinsic::x86_sse41_ptestnzc:
13865 case Intrinsic::x86_avx_ptestnzc_256:
13867 X86CC = X86::COND_A;
13871 SDValue LHS = Op.getOperand(1);
13872 SDValue RHS = Op.getOperand(2);
13873 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13874 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13875 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13876 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13877 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13879 case Intrinsic::x86_avx512_kortestz_w:
13880 case Intrinsic::x86_avx512_kortestc_w: {
13881 unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13882 SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13883 SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13884 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13885 SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13886 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13887 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13890 // SSE/AVX shift intrinsics
13891 case Intrinsic::x86_sse2_psll_w:
13892 case Intrinsic::x86_sse2_psll_d:
13893 case Intrinsic::x86_sse2_psll_q:
13894 case Intrinsic::x86_avx2_psll_w:
13895 case Intrinsic::x86_avx2_psll_d:
13896 case Intrinsic::x86_avx2_psll_q:
13897 case Intrinsic::x86_sse2_psrl_w:
13898 case Intrinsic::x86_sse2_psrl_d:
13899 case Intrinsic::x86_sse2_psrl_q:
13900 case Intrinsic::x86_avx2_psrl_w:
13901 case Intrinsic::x86_avx2_psrl_d:
13902 case Intrinsic::x86_avx2_psrl_q:
13903 case Intrinsic::x86_sse2_psra_w:
13904 case Intrinsic::x86_sse2_psra_d:
13905 case Intrinsic::x86_avx2_psra_w:
13906 case Intrinsic::x86_avx2_psra_d: {
13909 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13910 case Intrinsic::x86_sse2_psll_w:
13911 case Intrinsic::x86_sse2_psll_d:
13912 case Intrinsic::x86_sse2_psll_q:
13913 case Intrinsic::x86_avx2_psll_w:
13914 case Intrinsic::x86_avx2_psll_d:
13915 case Intrinsic::x86_avx2_psll_q:
13916 Opcode = X86ISD::VSHL;
13918 case Intrinsic::x86_sse2_psrl_w:
13919 case Intrinsic::x86_sse2_psrl_d:
13920 case Intrinsic::x86_sse2_psrl_q:
13921 case Intrinsic::x86_avx2_psrl_w:
13922 case Intrinsic::x86_avx2_psrl_d:
13923 case Intrinsic::x86_avx2_psrl_q:
13924 Opcode = X86ISD::VSRL;
13926 case Intrinsic::x86_sse2_psra_w:
13927 case Intrinsic::x86_sse2_psra_d:
13928 case Intrinsic::x86_avx2_psra_w:
13929 case Intrinsic::x86_avx2_psra_d:
13930 Opcode = X86ISD::VSRA;
13933 return DAG.getNode(Opcode, dl, Op.getValueType(),
13934 Op.getOperand(1), Op.getOperand(2));
13937 // SSE/AVX immediate shift intrinsics
13938 case Intrinsic::x86_sse2_pslli_w:
13939 case Intrinsic::x86_sse2_pslli_d:
13940 case Intrinsic::x86_sse2_pslli_q:
13941 case Intrinsic::x86_avx2_pslli_w:
13942 case Intrinsic::x86_avx2_pslli_d:
13943 case Intrinsic::x86_avx2_pslli_q:
13944 case Intrinsic::x86_sse2_psrli_w:
13945 case Intrinsic::x86_sse2_psrli_d:
13946 case Intrinsic::x86_sse2_psrli_q:
13947 case Intrinsic::x86_avx2_psrli_w:
13948 case Intrinsic::x86_avx2_psrli_d:
13949 case Intrinsic::x86_avx2_psrli_q:
13950 case Intrinsic::x86_sse2_psrai_w:
13951 case Intrinsic::x86_sse2_psrai_d:
13952 case Intrinsic::x86_avx2_psrai_w:
13953 case Intrinsic::x86_avx2_psrai_d: {
13956 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13957 case Intrinsic::x86_sse2_pslli_w:
13958 case Intrinsic::x86_sse2_pslli_d:
13959 case Intrinsic::x86_sse2_pslli_q:
13960 case Intrinsic::x86_avx2_pslli_w:
13961 case Intrinsic::x86_avx2_pslli_d:
13962 case Intrinsic::x86_avx2_pslli_q:
13963 Opcode = X86ISD::VSHLI;
13965 case Intrinsic::x86_sse2_psrli_w:
13966 case Intrinsic::x86_sse2_psrli_d:
13967 case Intrinsic::x86_sse2_psrli_q:
13968 case Intrinsic::x86_avx2_psrli_w:
13969 case Intrinsic::x86_avx2_psrli_d:
13970 case Intrinsic::x86_avx2_psrli_q:
13971 Opcode = X86ISD::VSRLI;
13973 case Intrinsic::x86_sse2_psrai_w:
13974 case Intrinsic::x86_sse2_psrai_d:
13975 case Intrinsic::x86_avx2_psrai_w:
13976 case Intrinsic::x86_avx2_psrai_d:
13977 Opcode = X86ISD::VSRAI;
13980 return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
13981 Op.getOperand(1), Op.getOperand(2), DAG);
13984 case Intrinsic::x86_sse42_pcmpistria128:
13985 case Intrinsic::x86_sse42_pcmpestria128:
13986 case Intrinsic::x86_sse42_pcmpistric128:
13987 case Intrinsic::x86_sse42_pcmpestric128:
13988 case Intrinsic::x86_sse42_pcmpistrio128:
13989 case Intrinsic::x86_sse42_pcmpestrio128:
13990 case Intrinsic::x86_sse42_pcmpistris128:
13991 case Intrinsic::x86_sse42_pcmpestris128:
13992 case Intrinsic::x86_sse42_pcmpistriz128:
13993 case Intrinsic::x86_sse42_pcmpestriz128: {
13997 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
13998 case Intrinsic::x86_sse42_pcmpistria128:
13999 Opcode = X86ISD::PCMPISTRI;
14000 X86CC = X86::COND_A;
14002 case Intrinsic::x86_sse42_pcmpestria128:
14003 Opcode = X86ISD::PCMPESTRI;
14004 X86CC = X86::COND_A;
14006 case Intrinsic::x86_sse42_pcmpistric128:
14007 Opcode = X86ISD::PCMPISTRI;
14008 X86CC = X86::COND_B;
14010 case Intrinsic::x86_sse42_pcmpestric128:
14011 Opcode = X86ISD::PCMPESTRI;
14012 X86CC = X86::COND_B;
14014 case Intrinsic::x86_sse42_pcmpistrio128:
14015 Opcode = X86ISD::PCMPISTRI;
14016 X86CC = X86::COND_O;
14018 case Intrinsic::x86_sse42_pcmpestrio128:
14019 Opcode = X86ISD::PCMPESTRI;
14020 X86CC = X86::COND_O;
14022 case Intrinsic::x86_sse42_pcmpistris128:
14023 Opcode = X86ISD::PCMPISTRI;
14024 X86CC = X86::COND_S;
14026 case Intrinsic::x86_sse42_pcmpestris128:
14027 Opcode = X86ISD::PCMPESTRI;
14028 X86CC = X86::COND_S;
14030 case Intrinsic::x86_sse42_pcmpistriz128:
14031 Opcode = X86ISD::PCMPISTRI;
14032 X86CC = X86::COND_E;
14034 case Intrinsic::x86_sse42_pcmpestriz128:
14035 Opcode = X86ISD::PCMPESTRI;
14036 X86CC = X86::COND_E;
14039 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14040 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14041 SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14042 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14043 DAG.getConstant(X86CC, MVT::i8),
14044 SDValue(PCMP.getNode(), 1));
14045 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14048 case Intrinsic::x86_sse42_pcmpistri128:
14049 case Intrinsic::x86_sse42_pcmpestri128: {
14051 if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14052 Opcode = X86ISD::PCMPISTRI;
14054 Opcode = X86ISD::PCMPESTRI;
14056 SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14057 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14058 return DAG.getNode(Opcode, dl, VTs, NewOps);
14060 case Intrinsic::x86_fma_vfmadd_ps:
14061 case Intrinsic::x86_fma_vfmadd_pd:
14062 case Intrinsic::x86_fma_vfmsub_ps:
14063 case Intrinsic::x86_fma_vfmsub_pd:
14064 case Intrinsic::x86_fma_vfnmadd_ps:
14065 case Intrinsic::x86_fma_vfnmadd_pd:
14066 case Intrinsic::x86_fma_vfnmsub_ps:
14067 case Intrinsic::x86_fma_vfnmsub_pd:
14068 case Intrinsic::x86_fma_vfmaddsub_ps:
14069 case Intrinsic::x86_fma_vfmaddsub_pd:
14070 case Intrinsic::x86_fma_vfmsubadd_ps:
14071 case Intrinsic::x86_fma_vfmsubadd_pd:
14072 case Intrinsic::x86_fma_vfmadd_ps_256:
14073 case Intrinsic::x86_fma_vfmadd_pd_256:
14074 case Intrinsic::x86_fma_vfmsub_ps_256:
14075 case Intrinsic::x86_fma_vfmsub_pd_256:
14076 case Intrinsic::x86_fma_vfnmadd_ps_256:
14077 case Intrinsic::x86_fma_vfnmadd_pd_256:
14078 case Intrinsic::x86_fma_vfnmsub_ps_256:
14079 case Intrinsic::x86_fma_vfnmsub_pd_256:
14080 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14081 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14082 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14083 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14084 case Intrinsic::x86_fma_vfmadd_ps_512:
14085 case Intrinsic::x86_fma_vfmadd_pd_512:
14086 case Intrinsic::x86_fma_vfmsub_ps_512:
14087 case Intrinsic::x86_fma_vfmsub_pd_512:
14088 case Intrinsic::x86_fma_vfnmadd_ps_512:
14089 case Intrinsic::x86_fma_vfnmadd_pd_512:
14090 case Intrinsic::x86_fma_vfnmsub_ps_512:
14091 case Intrinsic::x86_fma_vfnmsub_pd_512:
14092 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14093 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14094 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14095 case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14098 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
14099 case Intrinsic::x86_fma_vfmadd_ps:
14100 case Intrinsic::x86_fma_vfmadd_pd:
14101 case Intrinsic::x86_fma_vfmadd_ps_256:
14102 case Intrinsic::x86_fma_vfmadd_pd_256:
14103 case Intrinsic::x86_fma_vfmadd_ps_512:
14104 case Intrinsic::x86_fma_vfmadd_pd_512:
14105 Opc = X86ISD::FMADD;
14107 case Intrinsic::x86_fma_vfmsub_ps:
14108 case Intrinsic::x86_fma_vfmsub_pd:
14109 case Intrinsic::x86_fma_vfmsub_ps_256:
14110 case Intrinsic::x86_fma_vfmsub_pd_256:
14111 case Intrinsic::x86_fma_vfmsub_ps_512:
14112 case Intrinsic::x86_fma_vfmsub_pd_512:
14113 Opc = X86ISD::FMSUB;
14115 case Intrinsic::x86_fma_vfnmadd_ps:
14116 case Intrinsic::x86_fma_vfnmadd_pd:
14117 case Intrinsic::x86_fma_vfnmadd_ps_256:
14118 case Intrinsic::x86_fma_vfnmadd_pd_256:
14119 case Intrinsic::x86_fma_vfnmadd_ps_512:
14120 case Intrinsic::x86_fma_vfnmadd_pd_512:
14121 Opc = X86ISD::FNMADD;
14123 case Intrinsic::x86_fma_vfnmsub_ps:
14124 case Intrinsic::x86_fma_vfnmsub_pd:
14125 case Intrinsic::x86_fma_vfnmsub_ps_256:
14126 case Intrinsic::x86_fma_vfnmsub_pd_256:
14127 case Intrinsic::x86_fma_vfnmsub_ps_512:
14128 case Intrinsic::x86_fma_vfnmsub_pd_512:
14129 Opc = X86ISD::FNMSUB;
14131 case Intrinsic::x86_fma_vfmaddsub_ps:
14132 case Intrinsic::x86_fma_vfmaddsub_pd:
14133 case Intrinsic::x86_fma_vfmaddsub_ps_256:
14134 case Intrinsic::x86_fma_vfmaddsub_pd_256:
14135 case Intrinsic::x86_fma_vfmaddsub_ps_512:
14136 case Intrinsic::x86_fma_vfmaddsub_pd_512:
14137 Opc = X86ISD::FMADDSUB;
14139 case Intrinsic::x86_fma_vfmsubadd_ps:
14140 case Intrinsic::x86_fma_vfmsubadd_pd:
14141 case Intrinsic::x86_fma_vfmsubadd_ps_256:
14142 case Intrinsic::x86_fma_vfmsubadd_pd_256:
14143 case Intrinsic::x86_fma_vfmsubadd_ps_512:
14144 case Intrinsic::x86_fma_vfmsubadd_pd_512:
14145 Opc = X86ISD::FMSUBADD;
14149 return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14150 Op.getOperand(2), Op.getOperand(3));
14155 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14156 SDValue Src, SDValue Mask, SDValue Base,
14157 SDValue Index, SDValue ScaleOp, SDValue Chain,
14158 const X86Subtarget * Subtarget) {
14160 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14161 assert(C && "Invalid scale type");
14162 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14163 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14164 Index.getSimpleValueType().getVectorNumElements());
14166 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14168 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14170 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14171 SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14172 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14173 SDValue Segment = DAG.getRegister(0, MVT::i32);
14174 if (Src.getOpcode() == ISD::UNDEF)
14175 Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14176 SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14177 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14178 SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14179 return DAG.getMergeValues(RetOps, dl);
14182 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14183 SDValue Src, SDValue Mask, SDValue Base,
14184 SDValue Index, SDValue ScaleOp, SDValue Chain) {
14186 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14187 assert(C && "Invalid scale type");
14188 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14189 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14190 SDValue Segment = DAG.getRegister(0, MVT::i32);
14191 EVT MaskVT = MVT::getVectorVT(MVT::i1,
14192 Index.getSimpleValueType().getVectorNumElements());
14194 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14196 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14198 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14199 SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14200 SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14201 SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14202 return SDValue(Res, 1);
14205 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14206 SDValue Mask, SDValue Base, SDValue Index,
14207 SDValue ScaleOp, SDValue Chain) {
14209 ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14210 assert(C && "Invalid scale type");
14211 SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14212 SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14213 SDValue Segment = DAG.getRegister(0, MVT::i32);
14215 MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14217 ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14219 MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14221 MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14222 //SDVTList VTs = DAG.getVTList(MVT::Other);
14223 SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14224 SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14225 return SDValue(Res, 0);
14228 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14229 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14230 // also used to custom lower READCYCLECOUNTER nodes.
14231 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14232 SelectionDAG &DAG, const X86Subtarget *Subtarget,
14233 SmallVectorImpl<SDValue> &Results) {
14234 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14235 SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14238 // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14239 // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14240 // and the EAX register is loaded with the low-order 32 bits.
14241 if (Subtarget->is64Bit()) {
14242 LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14243 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14246 LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14247 HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14250 SDValue Chain = HI.getValue(1);
14252 if (Opcode == X86ISD::RDTSCP_DAG) {
14253 assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14255 // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14256 // the ECX register. Add 'ecx' explicitly to the chain.
14257 SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14259 // Explicitly store the content of ECX at the location passed in input
14260 // to the 'rdtscp' intrinsic.
14261 Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14262 MachinePointerInfo(), false, false, 0);
14265 if (Subtarget->is64Bit()) {
14266 // The EDX register is loaded with the high-order 32 bits of the MSR, and
14267 // the EAX register is loaded with the low-order 32 bits.
14268 SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14269 DAG.getConstant(32, MVT::i8));
14270 Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14271 Results.push_back(Chain);
14275 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14276 SDValue Ops[] = { LO, HI };
14277 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14278 Results.push_back(Pair);
14279 Results.push_back(Chain);
14282 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14283 SelectionDAG &DAG) {
14284 SmallVector<SDValue, 2> Results;
14286 getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14288 return DAG.getMergeValues(Results, DL);
14291 enum IntrinsicType {
14292 GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
14295 struct IntrinsicData {
14296 IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14297 :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14298 IntrinsicType Type;
14303 std::map < unsigned, IntrinsicData> IntrMap;
14304 static void InitIntinsicsMap() {
14305 static bool Initialized = false;
14308 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14309 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14310 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14311 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14312 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14313 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14314 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14315 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14316 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14317 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14318 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512,
14319 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14320 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512,
14321 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14322 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512,
14323 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14324 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512,
14325 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14327 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14328 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14329 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512,
14330 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14331 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512,
14332 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14333 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512,
14334 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14335 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512,
14336 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14337 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512,
14338 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14339 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512,
14340 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14341 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512,
14342 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14344 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512,
14345 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14346 X86::VGATHERPF1QPSm)));
14347 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512,
14348 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14349 X86::VGATHERPF1QPDm)));
14350 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512,
14351 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14352 X86::VGATHERPF1DPDm)));
14353 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512,
14354 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14355 X86::VGATHERPF1DPSm)));
14356 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512,
14357 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14358 X86::VSCATTERPF1QPSm)));
14359 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512,
14360 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14361 X86::VSCATTERPF1QPDm)));
14362 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512,
14363 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14364 X86::VSCATTERPF1DPDm)));
14365 IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512,
14366 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14367 X86::VSCATTERPF1DPSm)));
14368 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14369 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14370 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14371 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14372 IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14373 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14374 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14375 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14376 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14377 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14378 IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14379 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14380 IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14381 IntrinsicData(XTEST, X86ISD::XTEST, 0)));
14382 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14383 IntrinsicData(RDTSC, X86ISD::RDTSC_DAG, 0)));
14384 IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14385 IntrinsicData(RDTSC, X86ISD::RDTSCP_DAG, 0)));
14386 Initialized = true;
14389 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14390 SelectionDAG &DAG) {
14391 InitIntinsicsMap();
14392 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14393 std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14394 if (itr == IntrMap.end())
14398 IntrinsicData Intr = itr->second;
14399 switch(Intr.Type) {
14402 // Emit the node with the right value type.
14403 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14404 SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14406 // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14407 // Otherwise return the value from Rand, which is always 0, casted to i32.
14408 SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14409 DAG.getConstant(1, Op->getValueType(1)),
14410 DAG.getConstant(X86::COND_B, MVT::i32),
14411 SDValue(Result.getNode(), 1) };
14412 SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14413 DAG.getVTList(Op->getValueType(1), MVT::Glue),
14416 // Return { result, isValid, chain }.
14417 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14418 SDValue(Result.getNode(), 2));
14421 //gather(v1, mask, index, base, scale);
14422 SDValue Chain = Op.getOperand(0);
14423 SDValue Src = Op.getOperand(2);
14424 SDValue Base = Op.getOperand(3);
14425 SDValue Index = Op.getOperand(4);
14426 SDValue Mask = Op.getOperand(5);
14427 SDValue Scale = Op.getOperand(6);
14428 return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14432 //scatter(base, mask, index, v1, scale);
14433 SDValue Chain = Op.getOperand(0);
14434 SDValue Base = Op.getOperand(2);
14435 SDValue Mask = Op.getOperand(3);
14436 SDValue Index = Op.getOperand(4);
14437 SDValue Src = Op.getOperand(5);
14438 SDValue Scale = Op.getOperand(6);
14439 return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14442 SDValue Hint = Op.getOperand(6);
14444 if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14445 (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14446 llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14447 unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14448 SDValue Chain = Op.getOperand(0);
14449 SDValue Mask = Op.getOperand(2);
14450 SDValue Index = Op.getOperand(3);
14451 SDValue Base = Op.getOperand(4);
14452 SDValue Scale = Op.getOperand(5);
14453 return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14455 // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14457 SmallVector<SDValue, 2> Results;
14458 getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14459 return DAG.getMergeValues(Results, dl);
14461 // XTEST intrinsics.
14463 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14464 SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14465 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14466 DAG.getConstant(X86::COND_NE, MVT::i8),
14468 SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14469 return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14470 Ret, SDValue(InTrans.getNode(), 1));
14473 llvm_unreachable("Unknown Intrinsic Type");
14476 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14477 SelectionDAG &DAG) const {
14478 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14479 MFI->setReturnAddressIsTaken(true);
14481 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14484 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14486 EVT PtrVT = getPointerTy();
14489 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14490 const X86RegisterInfo *RegInfo =
14491 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14492 SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14493 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14494 DAG.getNode(ISD::ADD, dl, PtrVT,
14495 FrameAddr, Offset),
14496 MachinePointerInfo(), false, false, false, 0);
14499 // Just load the return address.
14500 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14501 return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14502 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14505 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14506 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14507 MFI->setFrameAddressIsTaken(true);
14509 EVT VT = Op.getValueType();
14510 SDLoc dl(Op); // FIXME probably not meaningful
14511 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14512 const X86RegisterInfo *RegInfo =
14513 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14514 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14515 assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14516 (FrameReg == X86::EBP && VT == MVT::i32)) &&
14517 "Invalid Frame Register!");
14518 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14520 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14521 MachinePointerInfo(),
14522 false, false, false, 0);
14526 // FIXME? Maybe this could be a TableGen attribute on some registers and
14527 // this table could be generated automatically from RegInfo.
14528 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14530 unsigned Reg = StringSwitch<unsigned>(RegName)
14531 .Case("esp", X86::ESP)
14532 .Case("rsp", X86::RSP)
14536 report_fatal_error("Invalid register name global variable");
14539 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14540 SelectionDAG &DAG) const {
14541 const X86RegisterInfo *RegInfo =
14542 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14543 return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14546 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14547 SDValue Chain = Op.getOperand(0);
14548 SDValue Offset = Op.getOperand(1);
14549 SDValue Handler = Op.getOperand(2);
14552 EVT PtrVT = getPointerTy();
14553 const X86RegisterInfo *RegInfo =
14554 static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14555 unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14556 assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14557 (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14558 "Invalid Frame Register!");
14559 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14560 unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14562 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14563 DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14564 StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14565 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14567 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14569 return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14570 DAG.getRegister(StoreAddrReg, PtrVT));
14573 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14574 SelectionDAG &DAG) const {
14576 return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14577 DAG.getVTList(MVT::i32, MVT::Other),
14578 Op.getOperand(0), Op.getOperand(1));
14581 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14582 SelectionDAG &DAG) const {
14584 return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14585 Op.getOperand(0), Op.getOperand(1));
14588 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14589 return Op.getOperand(0);
14592 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14593 SelectionDAG &DAG) const {
14594 SDValue Root = Op.getOperand(0);
14595 SDValue Trmp = Op.getOperand(1); // trampoline
14596 SDValue FPtr = Op.getOperand(2); // nested function
14597 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14600 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14601 const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14603 if (Subtarget->is64Bit()) {
14604 SDValue OutChains[6];
14606 // Large code-model.
14607 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
14608 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14610 const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14611 const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14613 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14615 // Load the pointer to the nested function into R11.
14616 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14617 SDValue Addr = Trmp;
14618 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14619 Addr, MachinePointerInfo(TrmpAddr),
14622 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14623 DAG.getConstant(2, MVT::i64));
14624 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14625 MachinePointerInfo(TrmpAddr, 2),
14628 // Load the 'nest' parameter value into R10.
14629 // R10 is specified in X86CallingConv.td
14630 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14631 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14632 DAG.getConstant(10, MVT::i64));
14633 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14634 Addr, MachinePointerInfo(TrmpAddr, 10),
14637 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14638 DAG.getConstant(12, MVT::i64));
14639 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14640 MachinePointerInfo(TrmpAddr, 12),
14643 // Jump to the nested function.
14644 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14645 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14646 DAG.getConstant(20, MVT::i64));
14647 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14648 Addr, MachinePointerInfo(TrmpAddr, 20),
14651 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14652 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14653 DAG.getConstant(22, MVT::i64));
14654 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14655 MachinePointerInfo(TrmpAddr, 22),
14658 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14660 const Function *Func =
14661 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14662 CallingConv::ID CC = Func->getCallingConv();
14667 llvm_unreachable("Unsupported calling convention");
14668 case CallingConv::C:
14669 case CallingConv::X86_StdCall: {
14670 // Pass 'nest' parameter in ECX.
14671 // Must be kept in sync with X86CallingConv.td
14672 NestReg = X86::ECX;
14674 // Check that ECX wasn't needed by an 'inreg' parameter.
14675 FunctionType *FTy = Func->getFunctionType();
14676 const AttributeSet &Attrs = Func->getAttributes();
14678 if (!Attrs.isEmpty() && !Func->isVarArg()) {
14679 unsigned InRegCount = 0;
14682 for (FunctionType::param_iterator I = FTy->param_begin(),
14683 E = FTy->param_end(); I != E; ++I, ++Idx)
14684 if (Attrs.hasAttribute(Idx, Attribute::InReg))
14685 // FIXME: should only count parameters that are lowered to integers.
14686 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14688 if (InRegCount > 2) {
14689 report_fatal_error("Nest register in use - reduce number of inreg"
14695 case CallingConv::X86_FastCall:
14696 case CallingConv::X86_ThisCall:
14697 case CallingConv::Fast:
14698 // Pass 'nest' parameter in EAX.
14699 // Must be kept in sync with X86CallingConv.td
14700 NestReg = X86::EAX;
14704 SDValue OutChains[4];
14705 SDValue Addr, Disp;
14707 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14708 DAG.getConstant(10, MVT::i32));
14709 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14711 // This is storing the opcode for MOV32ri.
14712 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14713 const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14714 OutChains[0] = DAG.getStore(Root, dl,
14715 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14716 Trmp, MachinePointerInfo(TrmpAddr),
14719 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14720 DAG.getConstant(1, MVT::i32));
14721 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14722 MachinePointerInfo(TrmpAddr, 1),
14725 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14726 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14727 DAG.getConstant(5, MVT::i32));
14728 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14729 MachinePointerInfo(TrmpAddr, 5),
14732 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14733 DAG.getConstant(6, MVT::i32));
14734 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14735 MachinePointerInfo(TrmpAddr, 6),
14738 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14742 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14743 SelectionDAG &DAG) const {
14745 The rounding mode is in bits 11:10 of FPSR, and has the following
14747 00 Round to nearest
14752 FLT_ROUNDS, on the other hand, expects the following:
14759 To perform the conversion, we do:
14760 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14763 MachineFunction &MF = DAG.getMachineFunction();
14764 const TargetMachine &TM = MF.getTarget();
14765 const TargetFrameLowering &TFI = *TM.getFrameLowering();
14766 unsigned StackAlignment = TFI.getStackAlignment();
14767 MVT VT = Op.getSimpleValueType();
14770 // Save FP Control Word to stack slot
14771 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14772 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14774 MachineMemOperand *MMO =
14775 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14776 MachineMemOperand::MOStore, 2, 2);
14778 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14779 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14780 DAG.getVTList(MVT::Other),
14781 Ops, MVT::i16, MMO);
14783 // Load FP Control Word from stack slot
14784 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14785 MachinePointerInfo(), false, false, false, 0);
14787 // Transform as necessary
14789 DAG.getNode(ISD::SRL, DL, MVT::i16,
14790 DAG.getNode(ISD::AND, DL, MVT::i16,
14791 CWD, DAG.getConstant(0x800, MVT::i16)),
14792 DAG.getConstant(11, MVT::i8));
14794 DAG.getNode(ISD::SRL, DL, MVT::i16,
14795 DAG.getNode(ISD::AND, DL, MVT::i16,
14796 CWD, DAG.getConstant(0x400, MVT::i16)),
14797 DAG.getConstant(9, MVT::i8));
14800 DAG.getNode(ISD::AND, DL, MVT::i16,
14801 DAG.getNode(ISD::ADD, DL, MVT::i16,
14802 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14803 DAG.getConstant(1, MVT::i16)),
14804 DAG.getConstant(3, MVT::i16));
14806 return DAG.getNode((VT.getSizeInBits() < 16 ?
14807 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14810 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14811 MVT VT = Op.getSimpleValueType();
14813 unsigned NumBits = VT.getSizeInBits();
14816 Op = Op.getOperand(0);
14817 if (VT == MVT::i8) {
14818 // Zero extend to i32 since there is not an i8 bsr.
14820 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14823 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14824 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14825 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14827 // If src is zero (i.e. bsr sets ZF), returns NumBits.
14830 DAG.getConstant(NumBits+NumBits-1, OpVT),
14831 DAG.getConstant(X86::COND_E, MVT::i8),
14834 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14836 // Finally xor with NumBits-1.
14837 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14840 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14844 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14845 MVT VT = Op.getSimpleValueType();
14847 unsigned NumBits = VT.getSizeInBits();
14850 Op = Op.getOperand(0);
14851 if (VT == MVT::i8) {
14852 // Zero extend to i32 since there is not an i8 bsr.
14854 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14857 // Issue a bsr (scan bits in reverse).
14858 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14859 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14861 // And xor with NumBits-1.
14862 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14865 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14869 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14870 MVT VT = Op.getSimpleValueType();
14871 unsigned NumBits = VT.getSizeInBits();
14873 Op = Op.getOperand(0);
14875 // Issue a bsf (scan bits forward) which also sets EFLAGS.
14876 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14877 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14879 // If src is zero (i.e. bsf sets ZF), returns NumBits.
14882 DAG.getConstant(NumBits, VT),
14883 DAG.getConstant(X86::COND_E, MVT::i8),
14886 return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
14889 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
14890 // ones, and then concatenate the result back.
14891 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
14892 MVT VT = Op.getSimpleValueType();
14894 assert(VT.is256BitVector() && VT.isInteger() &&
14895 "Unsupported value type for operation");
14897 unsigned NumElems = VT.getVectorNumElements();
14900 // Extract the LHS vectors
14901 SDValue LHS = Op.getOperand(0);
14902 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14903 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14905 // Extract the RHS vectors
14906 SDValue RHS = Op.getOperand(1);
14907 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14908 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14910 MVT EltVT = VT.getVectorElementType();
14911 MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14913 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14914 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
14915 DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
14918 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
14919 assert(Op.getSimpleValueType().is256BitVector() &&
14920 Op.getSimpleValueType().isInteger() &&
14921 "Only handle AVX 256-bit vector integer operation");
14922 return Lower256IntArith(Op, DAG);
14925 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
14926 assert(Op.getSimpleValueType().is256BitVector() &&
14927 Op.getSimpleValueType().isInteger() &&
14928 "Only handle AVX 256-bit vector integer operation");
14929 return Lower256IntArith(Op, DAG);
14932 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
14933 SelectionDAG &DAG) {
14935 MVT VT = Op.getSimpleValueType();
14937 // Decompose 256-bit ops into smaller 128-bit ops.
14938 if (VT.is256BitVector() && !Subtarget->hasInt256())
14939 return Lower256IntArith(Op, DAG);
14941 SDValue A = Op.getOperand(0);
14942 SDValue B = Op.getOperand(1);
14944 // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
14945 if (VT == MVT::v4i32) {
14946 assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
14947 "Should not custom lower when pmuldq is available!");
14949 // Extract the odd parts.
14950 static const int UnpackMask[] = { 1, -1, 3, -1 };
14951 SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
14952 SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
14954 // Multiply the even parts.
14955 SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
14956 // Now multiply odd parts.
14957 SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
14959 Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
14960 Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
14962 // Merge the two vectors back together with a shuffle. This expands into 2
14964 static const int ShufMask[] = { 0, 4, 2, 6 };
14965 return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
14968 assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
14969 "Only know how to lower V2I64/V4I64/V8I64 multiply");
14971 // Ahi = psrlqi(a, 32);
14972 // Bhi = psrlqi(b, 32);
14974 // AloBlo = pmuludq(a, b);
14975 // AloBhi = pmuludq(a, Bhi);
14976 // AhiBlo = pmuludq(Ahi, b);
14978 // AloBhi = psllqi(AloBhi, 32);
14979 // AhiBlo = psllqi(AhiBlo, 32);
14980 // return AloBlo + AloBhi + AhiBlo;
14982 SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
14983 SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
14985 // Bit cast to 32-bit vectors for MULUDQ
14986 EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
14987 (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
14988 A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
14989 B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
14990 Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
14991 Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
14993 SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
14994 SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
14995 SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
14997 AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
14998 AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15000 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15001 return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15004 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15005 assert(Subtarget->isTargetWin64() && "Unexpected target");
15006 EVT VT = Op.getValueType();
15007 assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15008 "Unexpected return type for lowering");
15012 switch (Op->getOpcode()) {
15013 default: llvm_unreachable("Unexpected request for libcall!");
15014 case ISD::SDIV: isSigned = true; LC = RTLIB::SDIV_I128; break;
15015 case ISD::UDIV: isSigned = false; LC = RTLIB::UDIV_I128; break;
15016 case ISD::SREM: isSigned = true; LC = RTLIB::SREM_I128; break;
15017 case ISD::UREM: isSigned = false; LC = RTLIB::UREM_I128; break;
15018 case ISD::SDIVREM: isSigned = true; LC = RTLIB::SDIVREM_I128; break;
15019 case ISD::UDIVREM: isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15023 SDValue InChain = DAG.getEntryNode();
15025 TargetLowering::ArgListTy Args;
15026 TargetLowering::ArgListEntry Entry;
15027 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15028 EVT ArgVT = Op->getOperand(i).getValueType();
15029 assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15030 "Unexpected argument type for lowering");
15031 SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15032 Entry.Node = StackPtr;
15033 InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15035 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15036 Entry.Ty = PointerType::get(ArgTy,0);
15037 Entry.isSExt = false;
15038 Entry.isZExt = false;
15039 Args.push_back(Entry);
15042 SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15045 TargetLowering::CallLoweringInfo CLI(DAG);
15046 CLI.setDebugLoc(dl).setChain(InChain)
15047 .setCallee(getLibcallCallingConv(LC),
15048 static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15050 .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15052 std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15053 return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15056 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15057 SelectionDAG &DAG) {
15058 SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15059 EVT VT = Op0.getValueType();
15062 assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15063 (VT == MVT::v8i32 && Subtarget->hasInt256()));
15065 // Get the high parts.
15066 const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
15067 SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15068 SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15070 // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15072 MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15073 bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15075 (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15076 SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15077 DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15078 SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15079 DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
15081 // Shuffle it back into the right order.
15082 const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
15083 SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15084 const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
15085 SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15087 // If we have a signed multiply but no PMULDQ fix up the high parts of a
15088 // unsigned multiply.
15089 if (IsSigned && !Subtarget->hasSSE41()) {
15091 DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15092 SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15093 DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15094 SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15095 DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15097 SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15098 Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15101 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
15104 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15105 const X86Subtarget *Subtarget) {
15106 MVT VT = Op.getSimpleValueType();
15108 SDValue R = Op.getOperand(0);
15109 SDValue Amt = Op.getOperand(1);
15111 // Optimize shl/srl/sra with constant shift amount.
15112 if (isSplatVector(Amt.getNode())) {
15113 SDValue SclrAmt = Amt->getOperand(0);
15114 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
15115 uint64_t ShiftAmt = C->getZExtValue();
15117 if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15118 (Subtarget->hasInt256() &&
15119 (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15120 (Subtarget->hasAVX512() &&
15121 (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15122 if (Op.getOpcode() == ISD::SHL)
15123 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15125 if (Op.getOpcode() == ISD::SRL)
15126 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15128 if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15129 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15133 if (VT == MVT::v16i8) {
15134 if (Op.getOpcode() == ISD::SHL) {
15135 // Make a large shift.
15136 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15137 MVT::v8i16, R, ShiftAmt,
15139 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15140 // Zero out the rightmost bits.
15141 SmallVector<SDValue, 16> V(16,
15142 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15144 return DAG.getNode(ISD::AND, dl, VT, SHL,
15145 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15147 if (Op.getOpcode() == ISD::SRL) {
15148 // Make a large shift.
15149 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15150 MVT::v8i16, R, ShiftAmt,
15152 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15153 // Zero out the leftmost bits.
15154 SmallVector<SDValue, 16> V(16,
15155 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15157 return DAG.getNode(ISD::AND, dl, VT, SRL,
15158 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15160 if (Op.getOpcode() == ISD::SRA) {
15161 if (ShiftAmt == 7) {
15162 // R s>> 7 === R s< 0
15163 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15164 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15167 // R s>> a === ((R u>> a) ^ m) - m
15168 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15169 SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15171 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15172 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15173 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15176 llvm_unreachable("Unknown shift opcode.");
15179 if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15180 if (Op.getOpcode() == ISD::SHL) {
15181 // Make a large shift.
15182 SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15183 MVT::v16i16, R, ShiftAmt,
15185 SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15186 // Zero out the rightmost bits.
15187 SmallVector<SDValue, 32> V(32,
15188 DAG.getConstant(uint8_t(-1U << ShiftAmt),
15190 return DAG.getNode(ISD::AND, dl, VT, SHL,
15191 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15193 if (Op.getOpcode() == ISD::SRL) {
15194 // Make a large shift.
15195 SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15196 MVT::v16i16, R, ShiftAmt,
15198 SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15199 // Zero out the leftmost bits.
15200 SmallVector<SDValue, 32> V(32,
15201 DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15203 return DAG.getNode(ISD::AND, dl, VT, SRL,
15204 DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15206 if (Op.getOpcode() == ISD::SRA) {
15207 if (ShiftAmt == 7) {
15208 // R s>> 7 === R s< 0
15209 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15210 return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15213 // R s>> a === ((R u>> a) ^ m) - m
15214 SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15215 SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15217 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15218 Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15219 Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15222 llvm_unreachable("Unknown shift opcode.");
15227 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15228 if (!Subtarget->is64Bit() &&
15229 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15230 Amt.getOpcode() == ISD::BITCAST &&
15231 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15232 Amt = Amt.getOperand(0);
15233 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15234 VT.getVectorNumElements();
15235 unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15236 uint64_t ShiftAmt = 0;
15237 for (unsigned i = 0; i != Ratio; ++i) {
15238 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15242 ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15244 // Check remaining shift amounts.
15245 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15246 uint64_t ShAmt = 0;
15247 for (unsigned j = 0; j != Ratio; ++j) {
15248 ConstantSDNode *C =
15249 dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15253 ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15255 if (ShAmt != ShiftAmt)
15258 switch (Op.getOpcode()) {
15260 llvm_unreachable("Unknown shift opcode!");
15262 return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15265 return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15268 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15276 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15277 const X86Subtarget* Subtarget) {
15278 MVT VT = Op.getSimpleValueType();
15280 SDValue R = Op.getOperand(0);
15281 SDValue Amt = Op.getOperand(1);
15283 if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15284 VT == MVT::v4i32 || VT == MVT::v8i16 ||
15285 (Subtarget->hasInt256() &&
15286 ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15287 VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15288 (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15290 EVT EltVT = VT.getVectorElementType();
15292 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15293 unsigned NumElts = VT.getVectorNumElements();
15295 for (i = 0; i != NumElts; ++i) {
15296 if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15300 for (j = i; j != NumElts; ++j) {
15301 SDValue Arg = Amt.getOperand(j);
15302 if (Arg.getOpcode() == ISD::UNDEF) continue;
15303 if (Arg != Amt.getOperand(i))
15306 if (i != NumElts && j == NumElts)
15307 BaseShAmt = Amt.getOperand(i);
15309 if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15310 Amt = Amt.getOperand(0);
15311 if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15312 cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15313 SDValue InVec = Amt.getOperand(0);
15314 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15315 unsigned NumElts = InVec.getValueType().getVectorNumElements();
15317 for (; i != NumElts; ++i) {
15318 SDValue Arg = InVec.getOperand(i);
15319 if (Arg.getOpcode() == ISD::UNDEF) continue;
15323 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15324 if (ConstantSDNode *C =
15325 dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15326 unsigned SplatIdx =
15327 cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15328 if (C->getZExtValue() == SplatIdx)
15329 BaseShAmt = InVec.getOperand(1);
15332 if (!BaseShAmt.getNode())
15333 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15334 DAG.getIntPtrConstant(0));
15338 if (BaseShAmt.getNode()) {
15339 if (EltVT.bitsGT(MVT::i32))
15340 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15341 else if (EltVT.bitsLT(MVT::i32))
15342 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15344 switch (Op.getOpcode()) {
15346 llvm_unreachable("Unknown shift opcode!");
15348 switch (VT.SimpleTy) {
15349 default: return SDValue();
15358 return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15361 switch (VT.SimpleTy) {
15362 default: return SDValue();
15369 return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15372 switch (VT.SimpleTy) {
15373 default: return SDValue();
15382 return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15388 // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15389 if (!Subtarget->is64Bit() &&
15390 (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15391 (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15392 Amt.getOpcode() == ISD::BITCAST &&
15393 Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15394 Amt = Amt.getOperand(0);
15395 unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15396 VT.getVectorNumElements();
15397 std::vector<SDValue> Vals(Ratio);
15398 for (unsigned i = 0; i != Ratio; ++i)
15399 Vals[i] = Amt.getOperand(i);
15400 for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15401 for (unsigned j = 0; j != Ratio; ++j)
15402 if (Vals[j] != Amt.getOperand(i + j))
15405 switch (Op.getOpcode()) {
15407 llvm_unreachable("Unknown shift opcode!");
15409 return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15411 return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15413 return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15420 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15421 SelectionDAG &DAG) {
15423 MVT VT = Op.getSimpleValueType();
15425 SDValue R = Op.getOperand(0);
15426 SDValue Amt = Op.getOperand(1);
15429 if (!Subtarget->hasSSE2())
15432 V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15436 V = LowerScalarVariableShift(Op, DAG, Subtarget);
15440 if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15442 // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15443 if (Subtarget->hasInt256()) {
15444 if (Op.getOpcode() == ISD::SRL &&
15445 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15446 VT == MVT::v4i64 || VT == MVT::v8i32))
15448 if (Op.getOpcode() == ISD::SHL &&
15449 (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15450 VT == MVT::v4i64 || VT == MVT::v8i32))
15452 if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15456 // If possible, lower this packed shift into a vector multiply instead of
15457 // expanding it into a sequence of scalar shifts.
15458 // Do this only if the vector shift count is a constant build_vector.
15459 if (Op.getOpcode() == ISD::SHL &&
15460 (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15461 (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15462 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15463 SmallVector<SDValue, 8> Elts;
15464 EVT SVT = VT.getScalarType();
15465 unsigned SVTBits = SVT.getSizeInBits();
15466 const APInt &One = APInt(SVTBits, 1);
15467 unsigned NumElems = VT.getVectorNumElements();
15469 for (unsigned i=0; i !=NumElems; ++i) {
15470 SDValue Op = Amt->getOperand(i);
15471 if (Op->getOpcode() == ISD::UNDEF) {
15472 Elts.push_back(Op);
15476 ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15477 const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15478 uint64_t ShAmt = C.getZExtValue();
15479 if (ShAmt >= SVTBits) {
15480 Elts.push_back(DAG.getUNDEF(SVT));
15483 Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15485 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15486 return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15489 // Lower SHL with variable shift amount.
15490 if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15491 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15493 Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15494 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15495 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15496 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15499 // If possible, lower this shift as a sequence of two shifts by
15500 // constant plus a MOVSS/MOVSD instead of scalarizing it.
15502 // (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15504 // Could be rewritten as:
15505 // (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15507 // The advantage is that the two shifts from the example would be
15508 // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15509 // the vector shift into four scalar shifts plus four pairs of vector
15511 if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15512 ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15513 unsigned TargetOpcode = X86ISD::MOVSS;
15514 bool CanBeSimplified;
15515 // The splat value for the first packed shift (the 'X' from the example).
15516 SDValue Amt1 = Amt->getOperand(0);
15517 // The splat value for the second packed shift (the 'Y' from the example).
15518 SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15519 Amt->getOperand(2);
15521 // See if it is possible to replace this node with a sequence of
15522 // two shifts followed by a MOVSS/MOVSD
15523 if (VT == MVT::v4i32) {
15524 // Check if it is legal to use a MOVSS.
15525 CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15526 Amt2 == Amt->getOperand(3);
15527 if (!CanBeSimplified) {
15528 // Otherwise, check if we can still simplify this node using a MOVSD.
15529 CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15530 Amt->getOperand(2) == Amt->getOperand(3);
15531 TargetOpcode = X86ISD::MOVSD;
15532 Amt2 = Amt->getOperand(2);
15535 // Do similar checks for the case where the machine value type
15537 CanBeSimplified = Amt1 == Amt->getOperand(1);
15538 for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15539 CanBeSimplified = Amt2 == Amt->getOperand(i);
15541 if (!CanBeSimplified) {
15542 TargetOpcode = X86ISD::MOVSD;
15543 CanBeSimplified = true;
15544 Amt2 = Amt->getOperand(4);
15545 for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15546 CanBeSimplified = Amt1 == Amt->getOperand(i);
15547 for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15548 CanBeSimplified = Amt2 == Amt->getOperand(j);
15552 if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15553 isa<ConstantSDNode>(Amt2)) {
15554 // Replace this node with two shifts followed by a MOVSS/MOVSD.
15555 EVT CastVT = MVT::v4i32;
15557 DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15558 SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15560 DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15561 SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15562 if (TargetOpcode == X86ISD::MOVSD)
15563 CastVT = MVT::v2i64;
15564 SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15565 SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15566 SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15568 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15572 if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15573 assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15576 Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15577 Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15579 // Turn 'a' into a mask suitable for VSELECT
15580 SDValue VSelM = DAG.getConstant(0x80, VT);
15581 SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15582 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15584 SDValue CM1 = DAG.getConstant(0x0f, VT);
15585 SDValue CM2 = DAG.getConstant(0x3f, VT);
15587 // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15588 SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15589 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15590 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15591 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15594 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15595 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15596 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15598 // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15599 M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15600 M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15601 M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15602 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15605 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15606 OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15607 OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15609 // return VSELECT(r, r+r, a);
15610 R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15611 DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15615 // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15616 // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15617 // solution better.
15618 if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15619 MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15621 Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15622 R = DAG.getNode(ExtOpc, dl, NewVT, R);
15623 Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15624 return DAG.getNode(ISD::TRUNCATE, dl, VT,
15625 DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15628 // Decompose 256-bit shifts into smaller 128-bit shifts.
15629 if (VT.is256BitVector()) {
15630 unsigned NumElems = VT.getVectorNumElements();
15631 MVT EltVT = VT.getVectorElementType();
15632 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15634 // Extract the two vectors
15635 SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15636 SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15638 // Recreate the shift amount vectors
15639 SDValue Amt1, Amt2;
15640 if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15641 // Constant shift amount
15642 SmallVector<SDValue, 4> Amt1Csts;
15643 SmallVector<SDValue, 4> Amt2Csts;
15644 for (unsigned i = 0; i != NumElems/2; ++i)
15645 Amt1Csts.push_back(Amt->getOperand(i));
15646 for (unsigned i = NumElems/2; i != NumElems; ++i)
15647 Amt2Csts.push_back(Amt->getOperand(i));
15649 Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15650 Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15652 // Variable shift amount
15653 Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15654 Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15657 // Issue new vector shifts for the smaller types
15658 V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15659 V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15661 // Concatenate the result back
15662 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15668 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15669 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15670 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15671 // looks for this combo and may remove the "setcc" instruction if the "setcc"
15672 // has only one use.
15673 SDNode *N = Op.getNode();
15674 SDValue LHS = N->getOperand(0);
15675 SDValue RHS = N->getOperand(1);
15676 unsigned BaseOp = 0;
15679 switch (Op.getOpcode()) {
15680 default: llvm_unreachable("Unknown ovf instruction!");
15682 // A subtract of one will be selected as a INC. Note that INC doesn't
15683 // set CF, so we can't do this for UADDO.
15684 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15686 BaseOp = X86ISD::INC;
15687 Cond = X86::COND_O;
15690 BaseOp = X86ISD::ADD;
15691 Cond = X86::COND_O;
15694 BaseOp = X86ISD::ADD;
15695 Cond = X86::COND_B;
15698 // A subtract of one will be selected as a DEC. Note that DEC doesn't
15699 // set CF, so we can't do this for USUBO.
15700 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15702 BaseOp = X86ISD::DEC;
15703 Cond = X86::COND_O;
15706 BaseOp = X86ISD::SUB;
15707 Cond = X86::COND_O;
15710 BaseOp = X86ISD::SUB;
15711 Cond = X86::COND_B;
15714 BaseOp = X86ISD::SMUL;
15715 Cond = X86::COND_O;
15717 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15718 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15720 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15723 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15724 DAG.getConstant(X86::COND_O, MVT::i32),
15725 SDValue(Sum.getNode(), 2));
15727 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15731 // Also sets EFLAGS.
15732 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15733 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15736 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15737 DAG.getConstant(Cond, MVT::i32),
15738 SDValue(Sum.getNode(), 1));
15740 return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15743 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15744 SelectionDAG &DAG) const {
15746 EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15747 MVT VT = Op.getSimpleValueType();
15749 if (!Subtarget->hasSSE2() || !VT.isVector())
15752 unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15753 ExtraVT.getScalarType().getSizeInBits();
15755 switch (VT.SimpleTy) {
15756 default: return SDValue();
15759 if (!Subtarget->hasFp256())
15761 if (!Subtarget->hasInt256()) {
15762 // needs to be split
15763 unsigned NumElems = VT.getVectorNumElements();
15765 // Extract the LHS vectors
15766 SDValue LHS = Op.getOperand(0);
15767 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15768 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15770 MVT EltVT = VT.getVectorElementType();
15771 EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15773 EVT ExtraEltVT = ExtraVT.getVectorElementType();
15774 unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15775 ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15777 SDValue Extra = DAG.getValueType(ExtraVT);
15779 LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15780 LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15782 return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15787 SDValue Op0 = Op.getOperand(0);
15788 SDValue Op00 = Op0.getOperand(0);
15790 // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15791 if (Op0.getOpcode() == ISD::BITCAST &&
15792 Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15793 // (sext (vzext x)) -> (vsext x)
15794 Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15795 if (Tmp1.getNode()) {
15796 EVT ExtraEltVT = ExtraVT.getVectorElementType();
15797 // This folding is only valid when the in-reg type is a vector of i8,
15799 if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15800 ExtraEltVT == MVT::i32) {
15801 SDValue Tmp1Op0 = Tmp1.getOperand(0);
15802 assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15803 "This optimization is invalid without a VZEXT.");
15804 return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15810 // If the above didn't work, then just use Shift-Left + Shift-Right.
15811 Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15813 return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15819 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15820 SelectionDAG &DAG) {
15822 AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15823 cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15824 SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15825 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15827 // The only fence that needs an instruction is a sequentially-consistent
15828 // cross-thread fence.
15829 if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15830 // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15831 // no-sse2). There isn't any reason to disable it if the target processor
15833 if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15834 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15836 SDValue Chain = Op.getOperand(0);
15837 SDValue Zero = DAG.getConstant(0, MVT::i32);
15839 DAG.getRegister(X86::ESP, MVT::i32), // Base
15840 DAG.getTargetConstant(1, MVT::i8), // Scale
15841 DAG.getRegister(0, MVT::i32), // Index
15842 DAG.getTargetConstant(0, MVT::i32), // Disp
15843 DAG.getRegister(0, MVT::i32), // Segment.
15847 SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15848 return SDValue(Res, 0);
15851 // MEMBARRIER is a compiler barrier; it codegens to a no-op.
15852 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
15855 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
15856 SelectionDAG &DAG) {
15857 MVT T = Op.getSimpleValueType();
15861 switch(T.SimpleTy) {
15862 default: llvm_unreachable("Invalid value type!");
15863 case MVT::i8: Reg = X86::AL; size = 1; break;
15864 case MVT::i16: Reg = X86::AX; size = 2; break;
15865 case MVT::i32: Reg = X86::EAX; size = 4; break;
15867 assert(Subtarget->is64Bit() && "Node not type legal!");
15868 Reg = X86::RAX; size = 8;
15871 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
15872 Op.getOperand(2), SDValue());
15873 SDValue Ops[] = { cpIn.getValue(0),
15876 DAG.getTargetConstant(size, MVT::i8),
15877 cpIn.getValue(1) };
15878 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15879 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
15880 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
15884 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
15885 SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
15886 MVT::i32, cpOut.getValue(2));
15887 SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
15888 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15890 DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
15891 DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
15892 DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
15896 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
15897 SelectionDAG &DAG) {
15898 MVT SrcVT = Op.getOperand(0).getSimpleValueType();
15899 MVT DstVT = Op.getSimpleValueType();
15901 if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
15902 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15903 if (DstVT != MVT::f64)
15904 // This conversion needs to be expanded.
15907 SDValue InVec = Op->getOperand(0);
15909 unsigned NumElts = SrcVT.getVectorNumElements();
15910 EVT SVT = SrcVT.getVectorElementType();
15912 // Widen the vector in input in the case of MVT::v2i32.
15913 // Example: from MVT::v2i32 to MVT::v4i32.
15914 SmallVector<SDValue, 16> Elts;
15915 for (unsigned i = 0, e = NumElts; i != e; ++i)
15916 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
15917 DAG.getIntPtrConstant(i)));
15919 // Explicitly mark the extra elements as Undef.
15920 SDValue Undef = DAG.getUNDEF(SVT);
15921 for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
15922 Elts.push_back(Undef);
15924 EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15925 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
15926 SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
15927 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
15928 DAG.getIntPtrConstant(0));
15931 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
15932 Subtarget->hasMMX() && "Unexpected custom BITCAST");
15933 assert((DstVT == MVT::i64 ||
15934 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
15935 "Unexpected custom BITCAST");
15936 // i64 <=> MMX conversions are Legal.
15937 if (SrcVT==MVT::i64 && DstVT.isVector())
15939 if (DstVT==MVT::i64 && SrcVT.isVector())
15941 // MMX <=> MMX conversions are Legal.
15942 if (SrcVT.isVector() && DstVT.isVector())
15944 // All other conversions need to be expanded.
15948 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
15949 SDNode *Node = Op.getNode();
15951 EVT T = Node->getValueType(0);
15952 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
15953 DAG.getConstant(0, T), Node->getOperand(2));
15954 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
15955 cast<AtomicSDNode>(Node)->getMemoryVT(),
15956 Node->getOperand(0),
15957 Node->getOperand(1), negOp,
15958 cast<AtomicSDNode>(Node)->getMemOperand(),
15959 cast<AtomicSDNode>(Node)->getOrdering(),
15960 cast<AtomicSDNode>(Node)->getSynchScope());
15963 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
15964 SDNode *Node = Op.getNode();
15966 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
15968 // Convert seq_cst store -> xchg
15969 // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
15970 // FIXME: On 32-bit, store -> fist or movq would be more efficient
15971 // (The only way to get a 16-byte store is cmpxchg16b)
15972 // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
15973 if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
15974 !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
15975 SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
15976 cast<AtomicSDNode>(Node)->getMemoryVT(),
15977 Node->getOperand(0),
15978 Node->getOperand(1), Node->getOperand(2),
15979 cast<AtomicSDNode>(Node)->getMemOperand(),
15980 cast<AtomicSDNode>(Node)->getOrdering(),
15981 cast<AtomicSDNode>(Node)->getSynchScope());
15982 return Swap.getValue(1);
15984 // Other atomic stores have a simple pattern.
15988 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
15989 EVT VT = Op.getNode()->getSimpleValueType(0);
15991 // Let legalize expand this if it isn't a legal type yet.
15992 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
15995 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15998 bool ExtraOp = false;
15999 switch (Op.getOpcode()) {
16000 default: llvm_unreachable("Invalid code");
16001 case ISD::ADDC: Opc = X86ISD::ADD; break;
16002 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16003 case ISD::SUBC: Opc = X86ISD::SUB; break;
16004 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16008 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16010 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16011 Op.getOperand(1), Op.getOperand(2));
16014 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16015 SelectionDAG &DAG) {
16016 assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16018 // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16019 // which returns the values as { float, float } (in XMM0) or
16020 // { double, double } (which is returned in XMM0, XMM1).
16022 SDValue Arg = Op.getOperand(0);
16023 EVT ArgVT = Arg.getValueType();
16024 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16026 TargetLowering::ArgListTy Args;
16027 TargetLowering::ArgListEntry Entry;
16031 Entry.isSExt = false;
16032 Entry.isZExt = false;
16033 Args.push_back(Entry);
16035 bool isF64 = ArgVT == MVT::f64;
16036 // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16037 // the small struct {f32, f32} is returned in (eax, edx). For f64,
16038 // the results are returned via SRet in memory.
16039 const char *LibcallName = isF64 ? "__sincos_stret" : "__sincosf_stret";
16040 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16041 SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16043 Type *RetTy = isF64
16044 ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16045 : (Type*)VectorType::get(ArgTy, 4);
16047 TargetLowering::CallLoweringInfo CLI(DAG);
16048 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16049 .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
16051 std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16054 // Returned in xmm0 and xmm1.
16055 return CallResult.first;
16057 // Returned in bits 0:31 and 32:64 xmm0.
16058 SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16059 CallResult.first, DAG.getIntPtrConstant(0));
16060 SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16061 CallResult.first, DAG.getIntPtrConstant(1));
16062 SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16063 return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16066 /// LowerOperation - Provide custom lowering hooks for some operations.
16068 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16069 switch (Op.getOpcode()) {
16070 default: llvm_unreachable("Should not custom lower this!");
16071 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op,DAG);
16072 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16073 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16074 return LowerCMP_SWAP(Op, Subtarget, DAG);
16075 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
16076 case ISD::ATOMIC_STORE: return LowerATOMIC_STORE(Op,DAG);
16077 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
16078 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
16079 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
16080 case ISD::VSELECT: return LowerVSELECT(Op, DAG);
16081 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16082 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
16083 case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16084 case ISD::INSERT_SUBVECTOR: return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16085 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
16086 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
16087 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
16088 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
16089 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
16090 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
16091 case ISD::SHL_PARTS:
16092 case ISD::SRA_PARTS:
16093 case ISD::SRL_PARTS: return LowerShiftParts(Op, DAG);
16094 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
16095 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
16096 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
16097 case ISD::ZERO_EXTEND: return LowerZERO_EXTEND(Op, Subtarget, DAG);
16098 case ISD::SIGN_EXTEND: return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16099 case ISD::ANY_EXTEND: return LowerANY_EXTEND(Op, Subtarget, DAG);
16100 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
16101 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
16102 case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
16103 case ISD::FABS: return LowerFABS(Op, DAG);
16104 case ISD::FNEG: return LowerFNEG(Op, DAG);
16105 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
16106 case ISD::FGETSIGN: return LowerFGETSIGN(Op, DAG);
16107 case ISD::SETCC: return LowerSETCC(Op, DAG);
16108 case ISD::SELECT: return LowerSELECT(Op, DAG);
16109 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
16110 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
16111 case ISD::VASTART: return LowerVASTART(Op, DAG);
16112 case ISD::VAARG: return LowerVAARG(Op, DAG);
16113 case ISD::VACOPY: return LowerVACOPY(Op, Subtarget, DAG);
16114 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16115 case ISD::INTRINSIC_VOID:
16116 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16117 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
16118 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
16119 case ISD::FRAME_TO_ARGS_OFFSET:
16120 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16121 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16122 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
16123 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
16124 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
16125 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
16126 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
16127 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
16128 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
16129 case ISD::CTLZ_ZERO_UNDEF: return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16130 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
16131 case ISD::MUL: return LowerMUL(Op, Subtarget, DAG);
16132 case ISD::UMUL_LOHI:
16133 case ISD::SMUL_LOHI: return LowerMUL_LOHI(Op, Subtarget, DAG);
16136 case ISD::SHL: return LowerShift(Op, Subtarget, DAG);
16142 case ISD::UMULO: return LowerXALUO(Op, DAG);
16143 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16144 case ISD::BITCAST: return LowerBITCAST(Op, Subtarget, DAG);
16148 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16149 case ISD::ADD: return LowerADD(Op, DAG);
16150 case ISD::SUB: return LowerSUB(Op, DAG);
16151 case ISD::FSINCOS: return LowerFSINCOS(Op, Subtarget, DAG);
16155 static void ReplaceATOMIC_LOAD(SDNode *Node,
16156 SmallVectorImpl<SDValue> &Results,
16157 SelectionDAG &DAG) {
16159 EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16161 // Convert wide load -> cmpxchg8b/cmpxchg16b
16162 // FIXME: On 32-bit, load -> fild or movq would be more efficient
16163 // (The only way to get a 16-byte load is cmpxchg16b)
16164 // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16165 SDValue Zero = DAG.getConstant(0, VT);
16166 SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16168 DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16169 Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16170 cast<AtomicSDNode>(Node)->getMemOperand(),
16171 cast<AtomicSDNode>(Node)->getOrdering(),
16172 cast<AtomicSDNode>(Node)->getOrdering(),
16173 cast<AtomicSDNode>(Node)->getSynchScope());
16174 Results.push_back(Swap.getValue(0));
16175 Results.push_back(Swap.getValue(2));
16179 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
16180 SelectionDAG &DAG, unsigned NewOp) {
16182 assert (Node->getValueType(0) == MVT::i64 &&
16183 "Only know how to expand i64 atomics");
16185 SDValue Chain = Node->getOperand(0);
16186 SDValue In1 = Node->getOperand(1);
16187 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
16188 Node->getOperand(2), DAG.getIntPtrConstant(0));
16189 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
16190 Node->getOperand(2), DAG.getIntPtrConstant(1));
16191 SDValue Ops[] = { Chain, In1, In2L, In2H };
16192 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
16194 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
16195 cast<MemSDNode>(Node)->getMemOperand());
16196 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
16197 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
16198 Results.push_back(Result.getValue(2));
16201 /// ReplaceNodeResults - Replace a node with an illegal result type
16202 /// with a new node built out of custom code.
16203 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16204 SmallVectorImpl<SDValue>&Results,
16205 SelectionDAG &DAG) const {
16207 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16208 switch (N->getOpcode()) {
16210 llvm_unreachable("Do not know how to custom type legalize this operation!");
16211 case ISD::SIGN_EXTEND_INREG:
16216 // We don't want to expand or promote these.
16223 case ISD::UDIVREM: {
16224 SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16225 Results.push_back(V);
16228 case ISD::FP_TO_SINT:
16229 case ISD::FP_TO_UINT: {
16230 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16232 if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16235 std::pair<SDValue,SDValue> Vals =
16236 FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16237 SDValue FIST = Vals.first, StackSlot = Vals.second;
16238 if (FIST.getNode()) {
16239 EVT VT = N->getValueType(0);
16240 // Return a load from the stack slot.
16241 if (StackSlot.getNode())
16242 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16243 MachinePointerInfo(),
16244 false, false, false, 0));
16246 Results.push_back(FIST);
16250 case ISD::UINT_TO_FP: {
16251 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16252 if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16253 N->getValueType(0) != MVT::v2f32)
16255 SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16257 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16259 SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16260 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16261 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16262 Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16263 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16264 Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16267 case ISD::FP_ROUND: {
16268 if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16270 SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16271 Results.push_back(V);
16274 case ISD::INTRINSIC_W_CHAIN: {
16275 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16277 default : llvm_unreachable("Do not know how to custom type "
16278 "legalize this intrinsic operation!");
16279 case Intrinsic::x86_rdtsc:
16280 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16282 case Intrinsic::x86_rdtscp:
16283 return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16287 case ISD::READCYCLECOUNTER: {
16288 return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16291 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16292 EVT T = N->getValueType(0);
16293 assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16294 bool Regs64bit = T == MVT::i128;
16295 EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16296 SDValue cpInL, cpInH;
16297 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16298 DAG.getConstant(0, HalfT));
16299 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16300 DAG.getConstant(1, HalfT));
16301 cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16302 Regs64bit ? X86::RAX : X86::EAX,
16304 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16305 Regs64bit ? X86::RDX : X86::EDX,
16306 cpInH, cpInL.getValue(1));
16307 SDValue swapInL, swapInH;
16308 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16309 DAG.getConstant(0, HalfT));
16310 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16311 DAG.getConstant(1, HalfT));
16312 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16313 Regs64bit ? X86::RBX : X86::EBX,
16314 swapInL, cpInH.getValue(1));
16315 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16316 Regs64bit ? X86::RCX : X86::ECX,
16317 swapInH, swapInL.getValue(1));
16318 SDValue Ops[] = { swapInH.getValue(0),
16320 swapInH.getValue(1) };
16321 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16322 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16323 unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16324 X86ISD::LCMPXCHG8_DAG;
16325 SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16326 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16327 Regs64bit ? X86::RAX : X86::EAX,
16328 HalfT, Result.getValue(1));
16329 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16330 Regs64bit ? X86::RDX : X86::EDX,
16331 HalfT, cpOutL.getValue(2));
16332 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16334 SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16335 MVT::i32, cpOutH.getValue(2));
16337 DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16338 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16339 Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16341 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16342 Results.push_back(Success);
16343 Results.push_back(EFLAGS.getValue(1));
16346 case ISD::ATOMIC_LOAD_ADD:
16347 case ISD::ATOMIC_LOAD_AND:
16348 case ISD::ATOMIC_LOAD_NAND:
16349 case ISD::ATOMIC_LOAD_OR:
16350 case ISD::ATOMIC_LOAD_SUB:
16351 case ISD::ATOMIC_LOAD_XOR:
16352 case ISD::ATOMIC_LOAD_MAX:
16353 case ISD::ATOMIC_LOAD_MIN:
16354 case ISD::ATOMIC_LOAD_UMAX:
16355 case ISD::ATOMIC_LOAD_UMIN:
16356 case ISD::ATOMIC_SWAP: {
16358 switch (N->getOpcode()) {
16359 default: llvm_unreachable("Unexpected opcode");
16360 case ISD::ATOMIC_LOAD_ADD:
16361 Opc = X86ISD::ATOMADD64_DAG;
16363 case ISD::ATOMIC_LOAD_AND:
16364 Opc = X86ISD::ATOMAND64_DAG;
16366 case ISD::ATOMIC_LOAD_NAND:
16367 Opc = X86ISD::ATOMNAND64_DAG;
16369 case ISD::ATOMIC_LOAD_OR:
16370 Opc = X86ISD::ATOMOR64_DAG;
16372 case ISD::ATOMIC_LOAD_SUB:
16373 Opc = X86ISD::ATOMSUB64_DAG;
16375 case ISD::ATOMIC_LOAD_XOR:
16376 Opc = X86ISD::ATOMXOR64_DAG;
16378 case ISD::ATOMIC_LOAD_MAX:
16379 Opc = X86ISD::ATOMMAX64_DAG;
16381 case ISD::ATOMIC_LOAD_MIN:
16382 Opc = X86ISD::ATOMMIN64_DAG;
16384 case ISD::ATOMIC_LOAD_UMAX:
16385 Opc = X86ISD::ATOMUMAX64_DAG;
16387 case ISD::ATOMIC_LOAD_UMIN:
16388 Opc = X86ISD::ATOMUMIN64_DAG;
16390 case ISD::ATOMIC_SWAP:
16391 Opc = X86ISD::ATOMSWAP64_DAG;
16394 ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
16397 case ISD::ATOMIC_LOAD: {
16398 ReplaceATOMIC_LOAD(N, Results, DAG);
16401 case ISD::BITCAST: {
16402 assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16403 EVT DstVT = N->getValueType(0);
16404 EVT SrcVT = N->getOperand(0)->getValueType(0);
16406 if (SrcVT != MVT::f64 ||
16407 (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16410 unsigned NumElts = DstVT.getVectorNumElements();
16411 EVT SVT = DstVT.getVectorElementType();
16412 EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16413 SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16414 MVT::v2f64, N->getOperand(0));
16415 SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16417 SmallVector<SDValue, 8> Elts;
16418 for (unsigned i = 0, e = NumElts; i != e; ++i)
16419 Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16420 ToVecInt, DAG.getIntPtrConstant(i)));
16422 Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16427 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16429 default: return nullptr;
16430 case X86ISD::BSF: return "X86ISD::BSF";
16431 case X86ISD::BSR: return "X86ISD::BSR";
16432 case X86ISD::SHLD: return "X86ISD::SHLD";
16433 case X86ISD::SHRD: return "X86ISD::SHRD";
16434 case X86ISD::FAND: return "X86ISD::FAND";
16435 case X86ISD::FANDN: return "X86ISD::FANDN";
16436 case X86ISD::FOR: return "X86ISD::FOR";
16437 case X86ISD::FXOR: return "X86ISD::FXOR";
16438 case X86ISD::FSRL: return "X86ISD::FSRL";
16439 case X86ISD::FILD: return "X86ISD::FILD";
16440 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
16441 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16442 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16443 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16444 case X86ISD::FLD: return "X86ISD::FLD";
16445 case X86ISD::FST: return "X86ISD::FST";
16446 case X86ISD::CALL: return "X86ISD::CALL";
16447 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
16448 case X86ISD::RDTSCP_DAG: return "X86ISD::RDTSCP_DAG";
16449 case X86ISD::BT: return "X86ISD::BT";
16450 case X86ISD::CMP: return "X86ISD::CMP";
16451 case X86ISD::COMI: return "X86ISD::COMI";
16452 case X86ISD::UCOMI: return "X86ISD::UCOMI";
16453 case X86ISD::CMPM: return "X86ISD::CMPM";
16454 case X86ISD::CMPMU: return "X86ISD::CMPMU";
16455 case X86ISD::SETCC: return "X86ISD::SETCC";
16456 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
16457 case X86ISD::FSETCC: return "X86ISD::FSETCC";
16458 case X86ISD::CMOV: return "X86ISD::CMOV";
16459 case X86ISD::BRCOND: return "X86ISD::BRCOND";
16460 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
16461 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
16462 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
16463 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
16464 case X86ISD::Wrapper: return "X86ISD::Wrapper";
16465 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
16466 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
16467 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
16468 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
16469 case X86ISD::PINSRB: return "X86ISD::PINSRB";
16470 case X86ISD::PINSRW: return "X86ISD::PINSRW";
16471 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
16472 case X86ISD::ANDNP: return "X86ISD::ANDNP";
16473 case X86ISD::PSIGN: return "X86ISD::PSIGN";
16474 case X86ISD::BLENDV: return "X86ISD::BLENDV";
16475 case X86ISD::BLENDI: return "X86ISD::BLENDI";
16476 case X86ISD::SUBUS: return "X86ISD::SUBUS";
16477 case X86ISD::HADD: return "X86ISD::HADD";
16478 case X86ISD::HSUB: return "X86ISD::HSUB";
16479 case X86ISD::FHADD: return "X86ISD::FHADD";
16480 case X86ISD::FHSUB: return "X86ISD::FHSUB";
16481 case X86ISD::UMAX: return "X86ISD::UMAX";
16482 case X86ISD::UMIN: return "X86ISD::UMIN";
16483 case X86ISD::SMAX: return "X86ISD::SMAX";
16484 case X86ISD::SMIN: return "X86ISD::SMIN";
16485 case X86ISD::FMAX: return "X86ISD::FMAX";
16486 case X86ISD::FMIN: return "X86ISD::FMIN";
16487 case X86ISD::FMAXC: return "X86ISD::FMAXC";
16488 case X86ISD::FMINC: return "X86ISD::FMINC";
16489 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
16490 case X86ISD::FRCP: return "X86ISD::FRCP";
16491 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
16492 case X86ISD::TLSBASEADDR: return "X86ISD::TLSBASEADDR";
16493 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
16494 case X86ISD::EH_SJLJ_SETJMP: return "X86ISD::EH_SJLJ_SETJMP";
16495 case X86ISD::EH_SJLJ_LONGJMP: return "X86ISD::EH_SJLJ_LONGJMP";
16496 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
16497 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
16498 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
16499 case X86ISD::FNSTSW16r: return "X86ISD::FNSTSW16r";
16500 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
16501 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
16502 case X86ISD::LCMPXCHG16_DAG: return "X86ISD::LCMPXCHG16_DAG";
16503 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
16504 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
16505 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
16506 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
16507 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
16508 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
16509 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
16510 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
16511 case X86ISD::VZEXT: return "X86ISD::VZEXT";
16512 case X86ISD::VSEXT: return "X86ISD::VSEXT";
16513 case X86ISD::VTRUNC: return "X86ISD::VTRUNC";
16514 case X86ISD::VTRUNCM: return "X86ISD::VTRUNCM";
16515 case X86ISD::VINSERT: return "X86ISD::VINSERT";
16516 case X86ISD::VFPEXT: return "X86ISD::VFPEXT";
16517 case X86ISD::VFPROUND: return "X86ISD::VFPROUND";
16518 case X86ISD::VSHLDQ: return "X86ISD::VSHLDQ";
16519 case X86ISD::VSRLDQ: return "X86ISD::VSRLDQ";
16520 case X86ISD::VSHL: return "X86ISD::VSHL";
16521 case X86ISD::VSRL: return "X86ISD::VSRL";
16522 case X86ISD::VSRA: return "X86ISD::VSRA";
16523 case X86ISD::VSHLI: return "X86ISD::VSHLI";
16524 case X86ISD::VSRLI: return "X86ISD::VSRLI";
16525 case X86ISD::VSRAI: return "X86ISD::VSRAI";
16526 case X86ISD::CMPP: return "X86ISD::CMPP";
16527 case X86ISD::PCMPEQ: return "X86ISD::PCMPEQ";
16528 case X86ISD::PCMPGT: return "X86ISD::PCMPGT";
16529 case X86ISD::PCMPEQM: return "X86ISD::PCMPEQM";
16530 case X86ISD::PCMPGTM: return "X86ISD::PCMPGTM";
16531 case X86ISD::ADD: return "X86ISD::ADD";
16532 case X86ISD::SUB: return "X86ISD::SUB";
16533 case X86ISD::ADC: return "X86ISD::ADC";
16534 case X86ISD::SBB: return "X86ISD::SBB";
16535 case X86ISD::SMUL: return "X86ISD::SMUL";
16536 case X86ISD::UMUL: return "X86ISD::UMUL";
16537 case X86ISD::INC: return "X86ISD::INC";
16538 case X86ISD::DEC: return "X86ISD::DEC";
16539 case X86ISD::OR: return "X86ISD::OR";
16540 case X86ISD::XOR: return "X86ISD::XOR";
16541 case X86ISD::AND: return "X86ISD::AND";
16542 case X86ISD::BEXTR: return "X86ISD::BEXTR";
16543 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
16544 case X86ISD::PTEST: return "X86ISD::PTEST";
16545 case X86ISD::TESTP: return "X86ISD::TESTP";
16546 case X86ISD::TESTM: return "X86ISD::TESTM";
16547 case X86ISD::TESTNM: return "X86ISD::TESTNM";
16548 case X86ISD::KORTEST: return "X86ISD::KORTEST";
16549 case X86ISD::PACKSS: return "X86ISD::PACKSS";
16550 case X86ISD::PACKUS: return "X86ISD::PACKUS";
16551 case X86ISD::PALIGNR: return "X86ISD::PALIGNR";
16552 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
16553 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
16554 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
16555 case X86ISD::SHUFP: return "X86ISD::SHUFP";
16556 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
16557 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
16558 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
16559 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
16560 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
16561 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
16562 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
16563 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
16564 case X86ISD::MOVSD: return "X86ISD::MOVSD";
16565 case X86ISD::MOVSS: return "X86ISD::MOVSS";
16566 case X86ISD::UNPCKL: return "X86ISD::UNPCKL";
16567 case X86ISD::UNPCKH: return "X86ISD::UNPCKH";
16568 case X86ISD::VBROADCAST: return "X86ISD::VBROADCAST";
16569 case X86ISD::VBROADCASTM: return "X86ISD::VBROADCASTM";
16570 case X86ISD::VEXTRACT: return "X86ISD::VEXTRACT";
16571 case X86ISD::VPERMILP: return "X86ISD::VPERMILP";
16572 case X86ISD::VPERM2X128: return "X86ISD::VPERM2X128";
16573 case X86ISD::VPERMV: return "X86ISD::VPERMV";
16574 case X86ISD::VPERMV3: return "X86ISD::VPERMV3";
16575 case X86ISD::VPERMIV3: return "X86ISD::VPERMIV3";
16576 case X86ISD::VPERMI: return "X86ISD::VPERMI";
16577 case X86ISD::PMULUDQ: return "X86ISD::PMULUDQ";
16578 case X86ISD::PMULDQ: return "X86ISD::PMULDQ";
16579 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16580 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
16581 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
16582 case X86ISD::MEMBARRIER: return "X86ISD::MEMBARRIER";
16583 case X86ISD::SEG_ALLOCA: return "X86ISD::SEG_ALLOCA";
16584 case X86ISD::WIN_FTOL: return "X86ISD::WIN_FTOL";
16585 case X86ISD::SAHF: return "X86ISD::SAHF";
16586 case X86ISD::RDRAND: return "X86ISD::RDRAND";
16587 case X86ISD::RDSEED: return "X86ISD::RDSEED";
16588 case X86ISD::FMADD: return "X86ISD::FMADD";
16589 case X86ISD::FMSUB: return "X86ISD::FMSUB";
16590 case X86ISD::FNMADD: return "X86ISD::FNMADD";
16591 case X86ISD::FNMSUB: return "X86ISD::FNMSUB";
16592 case X86ISD::FMADDSUB: return "X86ISD::FMADDSUB";
16593 case X86ISD::FMSUBADD: return "X86ISD::FMSUBADD";
16594 case X86ISD::PCMPESTRI: return "X86ISD::PCMPESTRI";
16595 case X86ISD::PCMPISTRI: return "X86ISD::PCMPISTRI";
16596 case X86ISD::XTEST: return "X86ISD::XTEST";
16600 // isLegalAddressingMode - Return true if the addressing mode represented
16601 // by AM is legal for this target, for a load/store of the specified type.
16602 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16604 // X86 supports extremely general addressing modes.
16605 CodeModel::Model M = getTargetMachine().getCodeModel();
16606 Reloc::Model R = getTargetMachine().getRelocationModel();
16608 // X86 allows a sign-extended 32-bit immediate field as a displacement.
16609 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16614 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16616 // If a reference to this global requires an extra load, we can't fold it.
16617 if (isGlobalStubReference(GVFlags))
16620 // If BaseGV requires a register for the PIC base, we cannot also have a
16621 // BaseReg specified.
16622 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16625 // If lower 4G is not available, then we must use rip-relative addressing.
16626 if ((M != CodeModel::Small || R != Reloc::Static) &&
16627 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16631 switch (AM.Scale) {
16637 // These scales always work.
16642 // These scales are formed with basereg+scalereg. Only accept if there is
16647 default: // Other stuff never works.
16654 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16655 unsigned Bits = Ty->getScalarSizeInBits();
16657 // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16658 // particularly cheaper than those without.
16662 // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16663 // variable shifts just as cheap as scalar ones.
16664 if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16667 // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16668 // fully general vector.
16672 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16673 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16675 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16676 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16677 return NumBits1 > NumBits2;
16680 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16681 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16684 if (!isTypeLegal(EVT::getEVT(Ty1)))
16687 assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16689 // Assuming the caller doesn't have a zeroext or signext return parameter,
16690 // truncation all the way down to i1 is valid.
16694 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16695 return isInt<32>(Imm);
16698 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16699 // Can also use sub to handle negated immediates.
16700 return isInt<32>(Imm);
16703 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16704 if (!VT1.isInteger() || !VT2.isInteger())
16706 unsigned NumBits1 = VT1.getSizeInBits();
16707 unsigned NumBits2 = VT2.getSizeInBits();
16708 return NumBits1 > NumBits2;
16711 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16712 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16713 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16716 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16717 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16718 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16721 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16722 EVT VT1 = Val.getValueType();
16723 if (isZExtFree(VT1, VT2))
16726 if (Val.getOpcode() != ISD::LOAD)
16729 if (!VT1.isSimple() || !VT1.isInteger() ||
16730 !VT2.isSimple() || !VT2.isInteger())
16733 switch (VT1.getSimpleVT().SimpleTy) {
16738 // X86 has 8, 16, and 32-bit zero-extending loads.
16746 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16747 if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16750 VT = VT.getScalarType();
16752 if (!VT.isSimple())
16755 switch (VT.getSimpleVT().SimpleTy) {
16766 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16767 // i16 instructions are longer (0x66 prefix) and potentially slower.
16768 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16771 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16772 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16773 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16774 /// are assumed to be legal.
16776 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16778 if (!VT.isSimple())
16781 MVT SVT = VT.getSimpleVT();
16783 // Very little shuffling can be done for 64-bit vectors right now.
16784 if (VT.getSizeInBits() == 64)
16787 // If this is a single-input shuffle with no 128 bit lane crossings we can
16788 // lower it into pshufb.
16789 if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16790 (SVT.is256BitVector() && Subtarget->hasInt256())) {
16791 bool isLegal = true;
16792 for (unsigned I = 0, E = M.size(); I != E; ++I) {
16793 if (M[I] >= (int)SVT.getVectorNumElements() ||
16794 ShuffleCrosses128bitLane(SVT, I, M[I])) {
16803 // FIXME: blends, shifts.
16804 return (SVT.getVectorNumElements() == 2 ||
16805 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16806 isMOVLMask(M, SVT) ||
16807 isSHUFPMask(M, SVT) ||
16808 isPSHUFDMask(M, SVT) ||
16809 isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16810 isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16811 isPALIGNRMask(M, SVT, Subtarget) ||
16812 isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16813 isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16814 isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16815 isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16816 isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16820 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16822 if (!VT.isSimple())
16825 MVT SVT = VT.getSimpleVT();
16826 unsigned NumElts = SVT.getVectorNumElements();
16827 // FIXME: This collection of masks seems suspect.
16830 if (NumElts == 4 && SVT.is128BitVector()) {
16831 return (isMOVLMask(Mask, SVT) ||
16832 isCommutedMOVLMask(Mask, SVT, true) ||
16833 isSHUFPMask(Mask, SVT) ||
16834 isSHUFPMask(Mask, SVT, /* Commuted */ true));
16839 //===----------------------------------------------------------------------===//
16840 // X86 Scheduler Hooks
16841 //===----------------------------------------------------------------------===//
16843 /// Utility function to emit xbegin specifying the start of an RTM region.
16844 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16845 const TargetInstrInfo *TII) {
16846 DebugLoc DL = MI->getDebugLoc();
16848 const BasicBlock *BB = MBB->getBasicBlock();
16849 MachineFunction::iterator I = MBB;
16852 // For the v = xbegin(), we generate
16863 MachineBasicBlock *thisMBB = MBB;
16864 MachineFunction *MF = MBB->getParent();
16865 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16866 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16867 MF->insert(I, mainMBB);
16868 MF->insert(I, sinkMBB);
16870 // Transfer the remainder of BB and its successor edges to sinkMBB.
16871 sinkMBB->splice(sinkMBB->begin(), MBB,
16872 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16873 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16877 // # fallthrough to mainMBB
16878 // # abortion to sinkMBB
16879 BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16880 thisMBB->addSuccessor(mainMBB);
16881 thisMBB->addSuccessor(sinkMBB);
16885 BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16886 mainMBB->addSuccessor(sinkMBB);
16889 // EAX is live into the sinkMBB
16890 sinkMBB->addLiveIn(X86::EAX);
16891 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16892 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16895 MI->eraseFromParent();
16899 // Get CMPXCHG opcode for the specified data type.
16900 static unsigned getCmpXChgOpcode(EVT VT) {
16901 switch (VT.getSimpleVT().SimpleTy) {
16902 case MVT::i8: return X86::LCMPXCHG8;
16903 case MVT::i16: return X86::LCMPXCHG16;
16904 case MVT::i32: return X86::LCMPXCHG32;
16905 case MVT::i64: return X86::LCMPXCHG64;
16909 llvm_unreachable("Invalid operand size!");
16912 // Get LOAD opcode for the specified data type.
16913 static unsigned getLoadOpcode(EVT VT) {
16914 switch (VT.getSimpleVT().SimpleTy) {
16915 case MVT::i8: return X86::MOV8rm;
16916 case MVT::i16: return X86::MOV16rm;
16917 case MVT::i32: return X86::MOV32rm;
16918 case MVT::i64: return X86::MOV64rm;
16922 llvm_unreachable("Invalid operand size!");
16925 // Get opcode of the non-atomic one from the specified atomic instruction.
16926 static unsigned getNonAtomicOpcode(unsigned Opc) {
16928 case X86::ATOMAND8: return X86::AND8rr;
16929 case X86::ATOMAND16: return X86::AND16rr;
16930 case X86::ATOMAND32: return X86::AND32rr;
16931 case X86::ATOMAND64: return X86::AND64rr;
16932 case X86::ATOMOR8: return X86::OR8rr;
16933 case X86::ATOMOR16: return X86::OR16rr;
16934 case X86::ATOMOR32: return X86::OR32rr;
16935 case X86::ATOMOR64: return X86::OR64rr;
16936 case X86::ATOMXOR8: return X86::XOR8rr;
16937 case X86::ATOMXOR16: return X86::XOR16rr;
16938 case X86::ATOMXOR32: return X86::XOR32rr;
16939 case X86::ATOMXOR64: return X86::XOR64rr;
16941 llvm_unreachable("Unhandled atomic-load-op opcode!");
16944 // Get opcode of the non-atomic one from the specified atomic instruction with
16946 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
16947 unsigned &ExtraOpc) {
16949 case X86::ATOMNAND8: ExtraOpc = X86::NOT8r; return X86::AND8rr;
16950 case X86::ATOMNAND16: ExtraOpc = X86::NOT16r; return X86::AND16rr;
16951 case X86::ATOMNAND32: ExtraOpc = X86::NOT32r; return X86::AND32rr;
16952 case X86::ATOMNAND64: ExtraOpc = X86::NOT64r; return X86::AND64rr;
16953 case X86::ATOMMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVL32rr;
16954 case X86::ATOMMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
16955 case X86::ATOMMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
16956 case X86::ATOMMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
16957 case X86::ATOMMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVG32rr;
16958 case X86::ATOMMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
16959 case X86::ATOMMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
16960 case X86::ATOMMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
16961 case X86::ATOMUMAX8: ExtraOpc = X86::CMP8rr; return X86::CMOVB32rr;
16962 case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
16963 case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
16964 case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
16965 case X86::ATOMUMIN8: ExtraOpc = X86::CMP8rr; return X86::CMOVA32rr;
16966 case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
16967 case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
16968 case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
16970 llvm_unreachable("Unhandled atomic-load-op opcode!");
16973 // Get opcode of the non-atomic one from the specified atomic instruction for
16974 // 64-bit data type on 32-bit target.
16975 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
16977 case X86::ATOMAND6432: HiOpc = X86::AND32rr; return X86::AND32rr;
16978 case X86::ATOMOR6432: HiOpc = X86::OR32rr; return X86::OR32rr;
16979 case X86::ATOMXOR6432: HiOpc = X86::XOR32rr; return X86::XOR32rr;
16980 case X86::ATOMADD6432: HiOpc = X86::ADC32rr; return X86::ADD32rr;
16981 case X86::ATOMSUB6432: HiOpc = X86::SBB32rr; return X86::SUB32rr;
16982 case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
16983 case X86::ATOMMAX6432: HiOpc = X86::SETLr; return X86::SETLr;
16984 case X86::ATOMMIN6432: HiOpc = X86::SETGr; return X86::SETGr;
16985 case X86::ATOMUMAX6432: HiOpc = X86::SETBr; return X86::SETBr;
16986 case X86::ATOMUMIN6432: HiOpc = X86::SETAr; return X86::SETAr;
16988 llvm_unreachable("Unhandled atomic-load-op opcode!");
16991 // Get opcode of the non-atomic one from the specified atomic instruction for
16992 // 64-bit data type on 32-bit target with extra opcode.
16993 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
16995 unsigned &ExtraOpc) {
16997 case X86::ATOMNAND6432:
16998 ExtraOpc = X86::NOT32r;
16999 HiOpc = X86::AND32rr;
17000 return X86::AND32rr;
17002 llvm_unreachable("Unhandled atomic-load-op opcode!");
17005 // Get pseudo CMOV opcode from the specified data type.
17006 static unsigned getPseudoCMOVOpc(EVT VT) {
17007 switch (VT.getSimpleVT().SimpleTy) {
17008 case MVT::i8: return X86::CMOV_GR8;
17009 case MVT::i16: return X86::CMOV_GR16;
17010 case MVT::i32: return X86::CMOV_GR32;
17014 llvm_unreachable("Unknown CMOV opcode!");
17017 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
17018 // They will be translated into a spin-loop or compare-exchange loop from
17021 // dst = atomic-fetch-op MI.addr, MI.val
17027 // t1 = LOAD MI.addr
17029 // t4 = phi(t1, t3 / loop)
17030 // t2 = OP MI.val, t4
17032 // LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
17038 MachineBasicBlock *
17039 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
17040 MachineBasicBlock *MBB) const {
17041 MachineFunction *MF = MBB->getParent();
17042 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17043 DebugLoc DL = MI->getDebugLoc();
17045 MachineRegisterInfo &MRI = MF->getRegInfo();
17047 const BasicBlock *BB = MBB->getBasicBlock();
17048 MachineFunction::iterator I = MBB;
17051 assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
17052 "Unexpected number of operands");
17054 assert(MI->hasOneMemOperand() &&
17055 "Expected atomic-load-op to have one memoperand");
17057 // Memory Reference
17058 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17059 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17061 unsigned DstReg, SrcReg;
17062 unsigned MemOpndSlot;
17064 unsigned CurOp = 0;
17066 DstReg = MI->getOperand(CurOp++).getReg();
17067 MemOpndSlot = CurOp;
17068 CurOp += X86::AddrNumOperands;
17069 SrcReg = MI->getOperand(CurOp++).getReg();
17071 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17072 MVT::SimpleValueType VT = *RC->vt_begin();
17073 unsigned t1 = MRI.createVirtualRegister(RC);
17074 unsigned t2 = MRI.createVirtualRegister(RC);
17075 unsigned t3 = MRI.createVirtualRegister(RC);
17076 unsigned t4 = MRI.createVirtualRegister(RC);
17077 unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
17079 unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
17080 unsigned LOADOpc = getLoadOpcode(VT);
17082 // For the atomic load-arith operator, we generate
17085 // t1 = LOAD [MI.addr]
17087 // t4 = phi(t1 / thisMBB, t3 / mainMBB)
17088 // t1 = OP MI.val, EAX
17090 // LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
17096 MachineBasicBlock *thisMBB = MBB;
17097 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17098 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17099 MF->insert(I, mainMBB);
17100 MF->insert(I, sinkMBB);
17102 MachineInstrBuilder MIB;
17104 // Transfer the remainder of BB and its successor edges to sinkMBB.
17105 sinkMBB->splice(sinkMBB->begin(), MBB,
17106 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17107 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17110 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
17111 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17112 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17114 NewMO.setIsKill(false);
17115 MIB.addOperand(NewMO);
17117 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
17118 unsigned flags = (*MMOI)->getFlags();
17119 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
17120 MachineMemOperand *MMO =
17121 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
17122 (*MMOI)->getSize(),
17123 (*MMOI)->getBaseAlignment(),
17124 (*MMOI)->getTBAAInfo(),
17125 (*MMOI)->getRanges());
17126 MIB.addMemOperand(MMO);
17129 thisMBB->addSuccessor(mainMBB);
17132 MachineBasicBlock *origMainMBB = mainMBB;
17135 MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
17136 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
17138 unsigned Opc = MI->getOpcode();
17141 llvm_unreachable("Unhandled atomic-load-op opcode!");
17142 case X86::ATOMAND8:
17143 case X86::ATOMAND16:
17144 case X86::ATOMAND32:
17145 case X86::ATOMAND64:
17147 case X86::ATOMOR16:
17148 case X86::ATOMOR32:
17149 case X86::ATOMOR64:
17150 case X86::ATOMXOR8:
17151 case X86::ATOMXOR16:
17152 case X86::ATOMXOR32:
17153 case X86::ATOMXOR64: {
17154 unsigned ARITHOpc = getNonAtomicOpcode(Opc);
17155 BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
17159 case X86::ATOMNAND8:
17160 case X86::ATOMNAND16:
17161 case X86::ATOMNAND32:
17162 case X86::ATOMNAND64: {
17163 unsigned Tmp = MRI.createVirtualRegister(RC);
17165 unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
17166 BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
17168 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
17171 case X86::ATOMMAX8:
17172 case X86::ATOMMAX16:
17173 case X86::ATOMMAX32:
17174 case X86::ATOMMAX64:
17175 case X86::ATOMMIN8:
17176 case X86::ATOMMIN16:
17177 case X86::ATOMMIN32:
17178 case X86::ATOMMIN64:
17179 case X86::ATOMUMAX8:
17180 case X86::ATOMUMAX16:
17181 case X86::ATOMUMAX32:
17182 case X86::ATOMUMAX64:
17183 case X86::ATOMUMIN8:
17184 case X86::ATOMUMIN16:
17185 case X86::ATOMUMIN32:
17186 case X86::ATOMUMIN64: {
17188 unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
17190 BuildMI(mainMBB, DL, TII->get(CMPOpc))
17194 if (Subtarget->hasCMov()) {
17195 if (VT != MVT::i8) {
17197 BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
17201 // Promote i8 to i32 to use CMOV32
17202 const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
17203 const TargetRegisterClass *RC32 =
17204 TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
17205 unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
17206 unsigned AccReg32 = MRI.createVirtualRegister(RC32);
17207 unsigned Tmp = MRI.createVirtualRegister(RC32);
17209 unsigned Undef = MRI.createVirtualRegister(RC32);
17210 BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
17212 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
17215 .addImm(X86::sub_8bit);
17216 BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
17219 .addImm(X86::sub_8bit);
17221 BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
17225 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
17226 .addReg(Tmp, 0, X86::sub_8bit);
17229 // Use pseudo select and lower them.
17230 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
17231 "Invalid atomic-load-op transformation!");
17232 unsigned SelOpc = getPseudoCMOVOpc(VT);
17233 X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
17234 assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
17235 MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
17236 .addReg(SrcReg).addReg(t4)
17238 mainMBB = EmitLoweredSelect(MIB, mainMBB);
17239 // Replace the original PHI node as mainMBB is changed after CMOV
17241 BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
17242 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
17243 Phi->eraseFromParent();
17249 // Copy PhyReg back from virtual register.
17250 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
17253 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
17254 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17255 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17257 NewMO.setIsKill(false);
17258 MIB.addOperand(NewMO);
17261 MIB.setMemRefs(MMOBegin, MMOEnd);
17263 // Copy PhyReg back to virtual register.
17264 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
17267 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
17269 mainMBB->addSuccessor(origMainMBB);
17270 mainMBB->addSuccessor(sinkMBB);
17273 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17274 TII->get(TargetOpcode::COPY), DstReg)
17277 MI->eraseFromParent();
17281 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
17282 // instructions. They will be translated into a spin-loop or compare-exchange
17286 // dst = atomic-fetch-op MI.addr, MI.val
17292 // t1L = LOAD [MI.addr + 0]
17293 // t1H = LOAD [MI.addr + 4]
17295 // t4L = phi(t1L, t3L / loop)
17296 // t4H = phi(t1H, t3H / loop)
17297 // t2L = OP MI.val.lo, t4L
17298 // t2H = OP MI.val.hi, t4H
17303 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
17311 MachineBasicBlock *
17312 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
17313 MachineBasicBlock *MBB) const {
17314 MachineFunction *MF = MBB->getParent();
17315 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17316 DebugLoc DL = MI->getDebugLoc();
17318 MachineRegisterInfo &MRI = MF->getRegInfo();
17320 const BasicBlock *BB = MBB->getBasicBlock();
17321 MachineFunction::iterator I = MBB;
17324 assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
17325 "Unexpected number of operands");
17327 assert(MI->hasOneMemOperand() &&
17328 "Expected atomic-load-op32 to have one memoperand");
17330 // Memory Reference
17331 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17332 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17334 unsigned DstLoReg, DstHiReg;
17335 unsigned SrcLoReg, SrcHiReg;
17336 unsigned MemOpndSlot;
17338 unsigned CurOp = 0;
17340 DstLoReg = MI->getOperand(CurOp++).getReg();
17341 DstHiReg = MI->getOperand(CurOp++).getReg();
17342 MemOpndSlot = CurOp;
17343 CurOp += X86::AddrNumOperands;
17344 SrcLoReg = MI->getOperand(CurOp++).getReg();
17345 SrcHiReg = MI->getOperand(CurOp++).getReg();
17347 const TargetRegisterClass *RC = &X86::GR32RegClass;
17348 const TargetRegisterClass *RC8 = &X86::GR8RegClass;
17350 unsigned t1L = MRI.createVirtualRegister(RC);
17351 unsigned t1H = MRI.createVirtualRegister(RC);
17352 unsigned t2L = MRI.createVirtualRegister(RC);
17353 unsigned t2H = MRI.createVirtualRegister(RC);
17354 unsigned t3L = MRI.createVirtualRegister(RC);
17355 unsigned t3H = MRI.createVirtualRegister(RC);
17356 unsigned t4L = MRI.createVirtualRegister(RC);
17357 unsigned t4H = MRI.createVirtualRegister(RC);
17359 unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
17360 unsigned LOADOpc = X86::MOV32rm;
17362 // For the atomic load-arith operator, we generate
17365 // t1L = LOAD [MI.addr + 0]
17366 // t1H = LOAD [MI.addr + 4]
17368 // t4L = phi(t1L / thisMBB, t3L / mainMBB)
17369 // t4H = phi(t1H / thisMBB, t3H / mainMBB)
17370 // t2L = OP MI.val.lo, t4L
17371 // t2H = OP MI.val.hi, t4H
17374 // LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
17382 MachineBasicBlock *thisMBB = MBB;
17383 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17384 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17385 MF->insert(I, mainMBB);
17386 MF->insert(I, sinkMBB);
17388 MachineInstrBuilder MIB;
17390 // Transfer the remainder of BB and its successor edges to sinkMBB.
17391 sinkMBB->splice(sinkMBB->begin(), MBB,
17392 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17393 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17397 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
17398 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17399 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17401 NewMO.setIsKill(false);
17402 MIB.addOperand(NewMO);
17404 for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
17405 unsigned flags = (*MMOI)->getFlags();
17406 flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
17407 MachineMemOperand *MMO =
17408 MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
17409 (*MMOI)->getSize(),
17410 (*MMOI)->getBaseAlignment(),
17411 (*MMOI)->getTBAAInfo(),
17412 (*MMOI)->getRanges());
17413 MIB.addMemOperand(MMO);
17415 MachineInstr *LowMI = MIB;
17418 MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
17419 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17420 if (i == X86::AddrDisp) {
17421 MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
17423 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17425 NewMO.setIsKill(false);
17426 MIB.addOperand(NewMO);
17429 MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
17431 thisMBB->addSuccessor(mainMBB);
17434 MachineBasicBlock *origMainMBB = mainMBB;
17437 MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
17438 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
17439 MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
17440 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
17442 unsigned Opc = MI->getOpcode();
17445 llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
17446 case X86::ATOMAND6432:
17447 case X86::ATOMOR6432:
17448 case X86::ATOMXOR6432:
17449 case X86::ATOMADD6432:
17450 case X86::ATOMSUB6432: {
17452 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
17453 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
17455 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
17459 case X86::ATOMNAND6432: {
17460 unsigned HiOpc, NOTOpc;
17461 unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
17462 unsigned TmpL = MRI.createVirtualRegister(RC);
17463 unsigned TmpH = MRI.createVirtualRegister(RC);
17464 BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
17466 BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
17468 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
17469 BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
17472 case X86::ATOMMAX6432:
17473 case X86::ATOMMIN6432:
17474 case X86::ATOMUMAX6432:
17475 case X86::ATOMUMIN6432: {
17477 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
17478 unsigned cL = MRI.createVirtualRegister(RC8);
17479 unsigned cH = MRI.createVirtualRegister(RC8);
17480 unsigned cL32 = MRI.createVirtualRegister(RC);
17481 unsigned cH32 = MRI.createVirtualRegister(RC);
17482 unsigned cc = MRI.createVirtualRegister(RC);
17483 // cl := cmp src_lo, lo
17484 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
17485 .addReg(SrcLoReg).addReg(t4L);
17486 BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
17487 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
17488 // ch := cmp src_hi, hi
17489 BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
17490 .addReg(SrcHiReg).addReg(t4H);
17491 BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
17492 BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
17493 // cc := if (src_hi == hi) ? cl : ch;
17494 if (Subtarget->hasCMov()) {
17495 BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
17496 .addReg(cH32).addReg(cL32);
17498 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
17499 .addReg(cH32).addReg(cL32)
17500 .addImm(X86::COND_E);
17501 mainMBB = EmitLoweredSelect(MIB, mainMBB);
17503 BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
17504 if (Subtarget->hasCMov()) {
17505 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
17506 .addReg(SrcLoReg).addReg(t4L);
17507 BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
17508 .addReg(SrcHiReg).addReg(t4H);
17510 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
17511 .addReg(SrcLoReg).addReg(t4L)
17512 .addImm(X86::COND_NE);
17513 mainMBB = EmitLoweredSelect(MIB, mainMBB);
17514 // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
17515 // 2nd CMOV lowering.
17516 mainMBB->addLiveIn(X86::EFLAGS);
17517 MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
17518 .addReg(SrcHiReg).addReg(t4H)
17519 .addImm(X86::COND_NE);
17520 mainMBB = EmitLoweredSelect(MIB, mainMBB);
17521 // Replace the original PHI node as mainMBB is changed after CMOV
17523 BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
17524 .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
17525 BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
17526 .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
17527 PhiL->eraseFromParent();
17528 PhiH->eraseFromParent();
17532 case X86::ATOMSWAP6432: {
17534 unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
17535 BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
17536 BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
17541 // Copy EDX:EAX back from HiReg:LoReg
17542 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
17543 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
17544 // Copy ECX:EBX from t1H:t1L
17545 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
17546 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
17548 MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
17549 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17550 MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
17552 NewMO.setIsKill(false);
17553 MIB.addOperand(NewMO);
17555 MIB.setMemRefs(MMOBegin, MMOEnd);
17557 // Copy EDX:EAX back to t3H:t3L
17558 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
17559 BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
17561 BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
17563 mainMBB->addSuccessor(origMainMBB);
17564 mainMBB->addSuccessor(sinkMBB);
17567 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17568 TII->get(TargetOpcode::COPY), DstLoReg)
17570 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17571 TII->get(TargetOpcode::COPY), DstHiReg)
17574 MI->eraseFromParent();
17578 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17579 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17580 // in the .td file.
17581 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17582 const TargetInstrInfo *TII) {
17584 switch (MI->getOpcode()) {
17585 default: llvm_unreachable("illegal opcode!");
17586 case X86::PCMPISTRM128REG: Opc = X86::PCMPISTRM128rr; break;
17587 case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17588 case X86::PCMPISTRM128MEM: Opc = X86::PCMPISTRM128rm; break;
17589 case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17590 case X86::PCMPESTRM128REG: Opc = X86::PCMPESTRM128rr; break;
17591 case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17592 case X86::PCMPESTRM128MEM: Opc = X86::PCMPESTRM128rm; break;
17593 case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17596 DebugLoc dl = MI->getDebugLoc();
17597 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17599 unsigned NumArgs = MI->getNumOperands();
17600 for (unsigned i = 1; i < NumArgs; ++i) {
17601 MachineOperand &Op = MI->getOperand(i);
17602 if (!(Op.isReg() && Op.isImplicit()))
17603 MIB.addOperand(Op);
17605 if (MI->hasOneMemOperand())
17606 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17608 BuildMI(*BB, MI, dl,
17609 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17610 .addReg(X86::XMM0);
17612 MI->eraseFromParent();
17616 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17617 // defs in an instruction pattern
17618 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17619 const TargetInstrInfo *TII) {
17621 switch (MI->getOpcode()) {
17622 default: llvm_unreachable("illegal opcode!");
17623 case X86::PCMPISTRIREG: Opc = X86::PCMPISTRIrr; break;
17624 case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17625 case X86::PCMPISTRIMEM: Opc = X86::PCMPISTRIrm; break;
17626 case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17627 case X86::PCMPESTRIREG: Opc = X86::PCMPESTRIrr; break;
17628 case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17629 case X86::PCMPESTRIMEM: Opc = X86::PCMPESTRIrm; break;
17630 case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17633 DebugLoc dl = MI->getDebugLoc();
17634 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17636 unsigned NumArgs = MI->getNumOperands(); // remove the results
17637 for (unsigned i = 1; i < NumArgs; ++i) {
17638 MachineOperand &Op = MI->getOperand(i);
17639 if (!(Op.isReg() && Op.isImplicit()))
17640 MIB.addOperand(Op);
17642 if (MI->hasOneMemOperand())
17643 MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17645 BuildMI(*BB, MI, dl,
17646 TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17649 MI->eraseFromParent();
17653 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17654 const TargetInstrInfo *TII,
17655 const X86Subtarget* Subtarget) {
17656 DebugLoc dl = MI->getDebugLoc();
17658 // Address into RAX/EAX, other two args into ECX, EDX.
17659 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17660 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17661 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17662 for (int i = 0; i < X86::AddrNumOperands; ++i)
17663 MIB.addOperand(MI->getOperand(i));
17665 unsigned ValOps = X86::AddrNumOperands;
17666 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17667 .addReg(MI->getOperand(ValOps).getReg());
17668 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17669 .addReg(MI->getOperand(ValOps+1).getReg());
17671 // The instruction doesn't actually take any operands though.
17672 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17674 MI->eraseFromParent(); // The pseudo is gone now.
17678 MachineBasicBlock *
17679 X86TargetLowering::EmitVAARG64WithCustomInserter(
17681 MachineBasicBlock *MBB) const {
17682 // Emit va_arg instruction on X86-64.
17684 // Operands to this pseudo-instruction:
17685 // 0 ) Output : destination address (reg)
17686 // 1-5) Input : va_list address (addr, i64mem)
17687 // 6 ) ArgSize : Size (in bytes) of vararg type
17688 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17689 // 8 ) Align : Alignment of type
17690 // 9 ) EFLAGS (implicit-def)
17692 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17693 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17695 unsigned DestReg = MI->getOperand(0).getReg();
17696 MachineOperand &Base = MI->getOperand(1);
17697 MachineOperand &Scale = MI->getOperand(2);
17698 MachineOperand &Index = MI->getOperand(3);
17699 MachineOperand &Disp = MI->getOperand(4);
17700 MachineOperand &Segment = MI->getOperand(5);
17701 unsigned ArgSize = MI->getOperand(6).getImm();
17702 unsigned ArgMode = MI->getOperand(7).getImm();
17703 unsigned Align = MI->getOperand(8).getImm();
17705 // Memory Reference
17706 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17707 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17708 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17710 // Machine Information
17711 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17712 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17713 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17714 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17715 DebugLoc DL = MI->getDebugLoc();
17717 // struct va_list {
17720 // i64 overflow_area (address)
17721 // i64 reg_save_area (address)
17723 // sizeof(va_list) = 24
17724 // alignment(va_list) = 8
17726 unsigned TotalNumIntRegs = 6;
17727 unsigned TotalNumXMMRegs = 8;
17728 bool UseGPOffset = (ArgMode == 1);
17729 bool UseFPOffset = (ArgMode == 2);
17730 unsigned MaxOffset = TotalNumIntRegs * 8 +
17731 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17733 /* Align ArgSize to a multiple of 8 */
17734 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17735 bool NeedsAlign = (Align > 8);
17737 MachineBasicBlock *thisMBB = MBB;
17738 MachineBasicBlock *overflowMBB;
17739 MachineBasicBlock *offsetMBB;
17740 MachineBasicBlock *endMBB;
17742 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
17743 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
17744 unsigned OffsetReg = 0;
17746 if (!UseGPOffset && !UseFPOffset) {
17747 // If we only pull from the overflow region, we don't create a branch.
17748 // We don't need to alter control flow.
17749 OffsetDestReg = 0; // unused
17750 OverflowDestReg = DestReg;
17752 offsetMBB = nullptr;
17753 overflowMBB = thisMBB;
17756 // First emit code to check if gp_offset (or fp_offset) is below the bound.
17757 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17758 // If not, pull from overflow_area. (branch to overflowMBB)
17763 // offsetMBB overflowMBB
17768 // Registers for the PHI in endMBB
17769 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17770 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17772 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17773 MachineFunction *MF = MBB->getParent();
17774 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17775 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17776 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17778 MachineFunction::iterator MBBIter = MBB;
17781 // Insert the new basic blocks
17782 MF->insert(MBBIter, offsetMBB);
17783 MF->insert(MBBIter, overflowMBB);
17784 MF->insert(MBBIter, endMBB);
17786 // Transfer the remainder of MBB and its successor edges to endMBB.
17787 endMBB->splice(endMBB->begin(), thisMBB,
17788 std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17789 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17791 // Make offsetMBB and overflowMBB successors of thisMBB
17792 thisMBB->addSuccessor(offsetMBB);
17793 thisMBB->addSuccessor(overflowMBB);
17795 // endMBB is a successor of both offsetMBB and overflowMBB
17796 offsetMBB->addSuccessor(endMBB);
17797 overflowMBB->addSuccessor(endMBB);
17799 // Load the offset value into a register
17800 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17801 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17805 .addDisp(Disp, UseFPOffset ? 4 : 0)
17806 .addOperand(Segment)
17807 .setMemRefs(MMOBegin, MMOEnd);
17809 // Check if there is enough room left to pull this argument.
17810 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17812 .addImm(MaxOffset + 8 - ArgSizeA8);
17814 // Branch to "overflowMBB" if offset >= max
17815 // Fall through to "offsetMBB" otherwise
17816 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17817 .addMBB(overflowMBB);
17820 // In offsetMBB, emit code to use the reg_save_area.
17822 assert(OffsetReg != 0);
17824 // Read the reg_save_area address.
17825 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17826 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17831 .addOperand(Segment)
17832 .setMemRefs(MMOBegin, MMOEnd);
17834 // Zero-extend the offset
17835 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17836 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17839 .addImm(X86::sub_32bit);
17841 // Add the offset to the reg_save_area to get the final address.
17842 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17843 .addReg(OffsetReg64)
17844 .addReg(RegSaveReg);
17846 // Compute the offset for the next argument
17847 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17848 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17850 .addImm(UseFPOffset ? 16 : 8);
17852 // Store it back into the va_list.
17853 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17857 .addDisp(Disp, UseFPOffset ? 4 : 0)
17858 .addOperand(Segment)
17859 .addReg(NextOffsetReg)
17860 .setMemRefs(MMOBegin, MMOEnd);
17863 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17868 // Emit code to use overflow area
17871 // Load the overflow_area address into a register.
17872 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17873 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17878 .addOperand(Segment)
17879 .setMemRefs(MMOBegin, MMOEnd);
17881 // If we need to align it, do so. Otherwise, just copy the address
17882 // to OverflowDestReg.
17884 // Align the overflow address
17885 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17886 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17888 // aligned_addr = (addr + (align-1)) & ~(align-1)
17889 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17890 .addReg(OverflowAddrReg)
17893 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17895 .addImm(~(uint64_t)(Align-1));
17897 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17898 .addReg(OverflowAddrReg);
17901 // Compute the next overflow address after this argument.
17902 // (the overflow address should be kept 8-byte aligned)
17903 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17904 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17905 .addReg(OverflowDestReg)
17906 .addImm(ArgSizeA8);
17908 // Store the new overflow address.
17909 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17914 .addOperand(Segment)
17915 .addReg(NextAddrReg)
17916 .setMemRefs(MMOBegin, MMOEnd);
17918 // If we branched, emit the PHI to the front of endMBB.
17920 BuildMI(*endMBB, endMBB->begin(), DL,
17921 TII->get(X86::PHI), DestReg)
17922 .addReg(OffsetDestReg).addMBB(offsetMBB)
17923 .addReg(OverflowDestReg).addMBB(overflowMBB);
17926 // Erase the pseudo instruction
17927 MI->eraseFromParent();
17932 MachineBasicBlock *
17933 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17935 MachineBasicBlock *MBB) const {
17936 // Emit code to save XMM registers to the stack. The ABI says that the
17937 // number of registers to save is given in %al, so it's theoretically
17938 // possible to do an indirect jump trick to avoid saving all of them,
17939 // however this code takes a simpler approach and just executes all
17940 // of the stores if %al is non-zero. It's less code, and it's probably
17941 // easier on the hardware branch predictor, and stores aren't all that
17942 // expensive anyway.
17944 // Create the new basic blocks. One block contains all the XMM stores,
17945 // and one block is the final destination regardless of whether any
17946 // stores were performed.
17947 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17948 MachineFunction *F = MBB->getParent();
17949 MachineFunction::iterator MBBIter = MBB;
17951 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17952 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17953 F->insert(MBBIter, XMMSaveMBB);
17954 F->insert(MBBIter, EndMBB);
17956 // Transfer the remainder of MBB and its successor edges to EndMBB.
17957 EndMBB->splice(EndMBB->begin(), MBB,
17958 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17959 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17961 // The original block will now fall through to the XMM save block.
17962 MBB->addSuccessor(XMMSaveMBB);
17963 // The XMMSaveMBB will fall through to the end block.
17964 XMMSaveMBB->addSuccessor(EndMBB);
17966 // Now add the instructions.
17967 const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17968 DebugLoc DL = MI->getDebugLoc();
17970 unsigned CountReg = MI->getOperand(0).getReg();
17971 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17972 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17974 if (!Subtarget->isTargetWin64()) {
17975 // If %al is 0, branch around the XMM save block.
17976 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17977 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17978 MBB->addSuccessor(EndMBB);
17981 // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17982 // that was just emitted, but clearly shouldn't be "saved".
17983 assert((MI->getNumOperands() <= 3 ||
17984 !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17985 MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17986 && "Expected last argument to be EFLAGS");
17987 unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17988 // In the XMM save block, save all the XMM argument registers.
17989 for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17990 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17991 MachineMemOperand *MMO =
17992 F->getMachineMemOperand(
17993 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17994 MachineMemOperand::MOStore,
17995 /*Size=*/16, /*Align=*/16);
17996 BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17997 .addFrameIndex(RegSaveFrameIndex)
17998 .addImm(/*Scale=*/1)
17999 .addReg(/*IndexReg=*/0)
18000 .addImm(/*Disp=*/Offset)
18001 .addReg(/*Segment=*/0)
18002 .addReg(MI->getOperand(i).getReg())
18003 .addMemOperand(MMO);
18006 MI->eraseFromParent(); // The pseudo instruction is gone now.
18011 // The EFLAGS operand of SelectItr might be missing a kill marker
18012 // because there were multiple uses of EFLAGS, and ISel didn't know
18013 // which to mark. Figure out whether SelectItr should have had a
18014 // kill marker, and set it if it should. Returns the correct kill
18016 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18017 MachineBasicBlock* BB,
18018 const TargetRegisterInfo* TRI) {
18019 // Scan forward through BB for a use/def of EFLAGS.
18020 MachineBasicBlock::iterator miI(std::next(SelectItr));
18021 for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18022 const MachineInstr& mi = *miI;
18023 if (mi.readsRegister(X86::EFLAGS))
18025 if (mi.definesRegister(X86::EFLAGS))
18026 break; // Should have kill-flag - update below.
18029 // If we hit the end of the block, check whether EFLAGS is live into a
18031 if (miI == BB->end()) {
18032 for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18033 sEnd = BB->succ_end();
18034 sItr != sEnd; ++sItr) {
18035 MachineBasicBlock* succ = *sItr;
18036 if (succ->isLiveIn(X86::EFLAGS))
18041 // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18042 // out. SelectMI should have a kill flag on EFLAGS.
18043 SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18047 MachineBasicBlock *
18048 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18049 MachineBasicBlock *BB) const {
18050 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
18051 DebugLoc DL = MI->getDebugLoc();
18053 // To "insert" a SELECT_CC instruction, we actually have to insert the
18054 // diamond control-flow pattern. The incoming instruction knows the
18055 // destination vreg to set, the condition code register to branch on, the
18056 // true/false values to select between, and a branch opcode to use.
18057 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18058 MachineFunction::iterator It = BB;
18064 // cmpTY ccX, r1, r2
18066 // fallthrough --> copy0MBB
18067 MachineBasicBlock *thisMBB = BB;
18068 MachineFunction *F = BB->getParent();
18069 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18070 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18071 F->insert(It, copy0MBB);
18072 F->insert(It, sinkMBB);
18074 // If the EFLAGS register isn't dead in the terminator, then claim that it's
18075 // live into the sink and copy blocks.
18076 const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
18077 if (!MI->killsRegister(X86::EFLAGS) &&
18078 !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18079 copy0MBB->addLiveIn(X86::EFLAGS);
18080 sinkMBB->addLiveIn(X86::EFLAGS);
18083 // Transfer the remainder of BB and its successor edges to sinkMBB.
18084 sinkMBB->splice(sinkMBB->begin(), BB,
18085 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18086 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18088 // Add the true and fallthrough blocks as its successors.
18089 BB->addSuccessor(copy0MBB);
18090 BB->addSuccessor(sinkMBB);
18092 // Create the conditional branch instruction.
18094 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18095 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18098 // %FalseValue = ...
18099 // # fallthrough to sinkMBB
18100 copy0MBB->addSuccessor(sinkMBB);
18103 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18105 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18106 TII->get(X86::PHI), MI->getOperand(0).getReg())
18107 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18108 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18110 MI->eraseFromParent(); // The pseudo instruction is gone now.
18114 MachineBasicBlock *
18115 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18116 bool Is64Bit) const {
18117 MachineFunction *MF = BB->getParent();
18118 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18119 DebugLoc DL = MI->getDebugLoc();
18120 const BasicBlock *LLVM_BB = BB->getBasicBlock();
18122 assert(MF->shouldSplitStack());
18124 unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18125 unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18128 // ... [Till the alloca]
18129 // If stacklet is not large enough, jump to mallocMBB
18132 // Allocate by subtracting from RSP
18133 // Jump to continueMBB
18136 // Allocate by call to runtime
18140 // [rest of original BB]
18143 MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18144 MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18145 MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18147 MachineRegisterInfo &MRI = MF->getRegInfo();
18148 const TargetRegisterClass *AddrRegClass =
18149 getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18151 unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18152 bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18153 tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18154 SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18155 sizeVReg = MI->getOperand(1).getReg(),
18156 physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18158 MachineFunction::iterator MBBIter = BB;
18161 MF->insert(MBBIter, bumpMBB);
18162 MF->insert(MBBIter, mallocMBB);
18163 MF->insert(MBBIter, continueMBB);
18165 continueMBB->splice(continueMBB->begin(), BB,
18166 std::next(MachineBasicBlock::iterator(MI)), BB->end());
18167 continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18169 // Add code to the main basic block to check if the stack limit has been hit,
18170 // and if so, jump to mallocMBB otherwise to bumpMBB.
18171 BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18172 BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18173 .addReg(tmpSPVReg).addReg(sizeVReg);
18174 BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18175 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18176 .addReg(SPLimitVReg);
18177 BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18179 // bumpMBB simply decreases the stack pointer, since we know the current
18180 // stacklet has enough space.
18181 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18182 .addReg(SPLimitVReg);
18183 BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18184 .addReg(SPLimitVReg);
18185 BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18187 // Calls into a routine in libgcc to allocate more space from the heap.
18188 const uint32_t *RegMask =
18189 MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18191 BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18193 BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18194 .addExternalSymbol("__morestack_allocate_stack_space")
18195 .addRegMask(RegMask)
18196 .addReg(X86::RDI, RegState::Implicit)
18197 .addReg(X86::RAX, RegState::ImplicitDefine);
18199 BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18201 BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18202 BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18203 .addExternalSymbol("__morestack_allocate_stack_space")
18204 .addRegMask(RegMask)
18205 .addReg(X86::EAX, RegState::ImplicitDefine);
18209 BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18212 BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18213 .addReg(Is64Bit ? X86::RAX : X86::EAX);
18214 BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18216 // Set up the CFG correctly.
18217 BB->addSuccessor(bumpMBB);
18218 BB->addSuccessor(mallocMBB);
18219 mallocMBB->addSuccessor(continueMBB);
18220 bumpMBB->addSuccessor(continueMBB);
18222 // Take care of the PHI nodes.
18223 BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18224 MI->getOperand(0).getReg())
18225 .addReg(mallocPtrVReg).addMBB(mallocMBB)
18226 .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18228 // Delete the original pseudo instruction.
18229 MI->eraseFromParent();
18232 return continueMBB;
18235 MachineBasicBlock *
18236 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18237 MachineBasicBlock *BB) const {
18238 const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
18239 DebugLoc DL = MI->getDebugLoc();
18241 assert(!Subtarget->isTargetMacho());
18243 // The lowering is pretty easy: we're just emitting the call to _alloca. The
18244 // non-trivial part is impdef of ESP.
18246 if (Subtarget->isTargetWin64()) {
18247 if (Subtarget->isTargetCygMing()) {
18248 // ___chkstk(Mingw64):
18249 // Clobbers R10, R11, RAX and EFLAGS.
18251 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18252 .addExternalSymbol("___chkstk")
18253 .addReg(X86::RAX, RegState::Implicit)
18254 .addReg(X86::RSP, RegState::Implicit)
18255 .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18256 .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18257 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18259 // __chkstk(MSVCRT): does not update stack pointer.
18260 // Clobbers R10, R11 and EFLAGS.
18261 BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18262 .addExternalSymbol("__chkstk")
18263 .addReg(X86::RAX, RegState::Implicit)
18264 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18265 // RAX has the offset to be subtracted from RSP.
18266 BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18271 const char *StackProbeSymbol =
18272 Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18274 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18275 .addExternalSymbol(StackProbeSymbol)
18276 .addReg(X86::EAX, RegState::Implicit)
18277 .addReg(X86::ESP, RegState::Implicit)
18278 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18279 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18280 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18283 MI->eraseFromParent(); // The pseudo instruction is gone now.
18287 MachineBasicBlock *
18288 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18289 MachineBasicBlock *BB) const {
18290 // This is pretty easy. We're taking the value that we received from
18291 // our load from the relocation, sticking it in either RDI (x86-64)
18292 // or EAX and doing an indirect call. The return value will then
18293 // be in the normal return register.
18294 MachineFunction *F = BB->getParent();
18295 const X86InstrInfo *TII
18296 = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
18297 DebugLoc DL = MI->getDebugLoc();
18299 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18300 assert(MI->getOperand(3).isGlobal() && "This should be a global");
18302 // Get a register mask for the lowered call.
18303 // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18304 // proper register mask.
18305 const uint32_t *RegMask =
18306 F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
18307 if (Subtarget->is64Bit()) {
18308 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18309 TII->get(X86::MOV64rm), X86::RDI)
18311 .addImm(0).addReg(0)
18312 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18313 MI->getOperand(3).getTargetFlags())
18315 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18316 addDirectMem(MIB, X86::RDI);
18317 MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18318 } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18319 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18320 TII->get(X86::MOV32rm), X86::EAX)
18322 .addImm(0).addReg(0)
18323 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18324 MI->getOperand(3).getTargetFlags())
18326 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18327 addDirectMem(MIB, X86::EAX);
18328 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18330 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18331 TII->get(X86::MOV32rm), X86::EAX)
18332 .addReg(TII->getGlobalBaseReg(F))
18333 .addImm(0).addReg(0)
18334 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18335 MI->getOperand(3).getTargetFlags())
18337 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18338 addDirectMem(MIB, X86::EAX);
18339 MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18342 MI->eraseFromParent(); // The pseudo instruction is gone now.
18346 MachineBasicBlock *
18347 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18348 MachineBasicBlock *MBB) const {
18349 DebugLoc DL = MI->getDebugLoc();
18350 MachineFunction *MF = MBB->getParent();
18351 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18352 MachineRegisterInfo &MRI = MF->getRegInfo();
18354 const BasicBlock *BB = MBB->getBasicBlock();
18355 MachineFunction::iterator I = MBB;
18358 // Memory Reference
18359 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18360 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18363 unsigned MemOpndSlot = 0;
18365 unsigned CurOp = 0;
18367 DstReg = MI->getOperand(CurOp++).getReg();
18368 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18369 assert(RC->hasType(MVT::i32) && "Invalid destination!");
18370 unsigned mainDstReg = MRI.createVirtualRegister(RC);
18371 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18373 MemOpndSlot = CurOp;
18375 MVT PVT = getPointerTy();
18376 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18377 "Invalid Pointer Size!");
18379 // For v = setjmp(buf), we generate
18382 // buf[LabelOffset] = restoreMBB
18383 // SjLjSetup restoreMBB
18389 // v = phi(main, restore)
18394 MachineBasicBlock *thisMBB = MBB;
18395 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18396 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18397 MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18398 MF->insert(I, mainMBB);
18399 MF->insert(I, sinkMBB);
18400 MF->push_back(restoreMBB);
18402 MachineInstrBuilder MIB;
18404 // Transfer the remainder of BB and its successor edges to sinkMBB.
18405 sinkMBB->splice(sinkMBB->begin(), MBB,
18406 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18407 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18410 unsigned PtrStoreOpc = 0;
18411 unsigned LabelReg = 0;
18412 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18413 Reloc::Model RM = MF->getTarget().getRelocationModel();
18414 bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18415 (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18417 // Prepare IP either in reg or imm.
18418 if (!UseImmLabel) {
18419 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18420 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18421 LabelReg = MRI.createVirtualRegister(PtrRC);
18422 if (Subtarget->is64Bit()) {
18423 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18427 .addMBB(restoreMBB)
18430 const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18431 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18432 .addReg(XII->getGlobalBaseReg(MF))
18435 .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18439 PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18441 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18442 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18443 if (i == X86::AddrDisp)
18444 MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18446 MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18449 MIB.addReg(LabelReg);
18451 MIB.addMBB(restoreMBB);
18452 MIB.setMemRefs(MMOBegin, MMOEnd);
18454 MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18455 .addMBB(restoreMBB);
18457 const X86RegisterInfo *RegInfo =
18458 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18459 MIB.addRegMask(RegInfo->getNoPreservedMask());
18460 thisMBB->addSuccessor(mainMBB);
18461 thisMBB->addSuccessor(restoreMBB);
18465 BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18466 mainMBB->addSuccessor(sinkMBB);
18469 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18470 TII->get(X86::PHI), DstReg)
18471 .addReg(mainDstReg).addMBB(mainMBB)
18472 .addReg(restoreDstReg).addMBB(restoreMBB);
18475 BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18476 BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18477 restoreMBB->addSuccessor(sinkMBB);
18479 MI->eraseFromParent();
18483 MachineBasicBlock *
18484 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18485 MachineBasicBlock *MBB) const {
18486 DebugLoc DL = MI->getDebugLoc();
18487 MachineFunction *MF = MBB->getParent();
18488 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
18489 MachineRegisterInfo &MRI = MF->getRegInfo();
18491 // Memory Reference
18492 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18493 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18495 MVT PVT = getPointerTy();
18496 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18497 "Invalid Pointer Size!");
18499 const TargetRegisterClass *RC =
18500 (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18501 unsigned Tmp = MRI.createVirtualRegister(RC);
18502 // Since FP is only updated here but NOT referenced, it's treated as GPR.
18503 const X86RegisterInfo *RegInfo =
18504 static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
18505 unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18506 unsigned SP = RegInfo->getStackRegister();
18508 MachineInstrBuilder MIB;
18510 const int64_t LabelOffset = 1 * PVT.getStoreSize();
18511 const int64_t SPOffset = 2 * PVT.getStoreSize();
18513 unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18514 unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18517 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18518 for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18519 MIB.addOperand(MI->getOperand(i));
18520 MIB.setMemRefs(MMOBegin, MMOEnd);
18522 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18523 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18524 if (i == X86::AddrDisp)
18525 MIB.addDisp(MI->getOperand(i), LabelOffset);
18527 MIB.addOperand(MI->getOperand(i));
18529 MIB.setMemRefs(MMOBegin, MMOEnd);
18531 MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18532 for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18533 if (i == X86::AddrDisp)
18534 MIB.addDisp(MI->getOperand(i), SPOffset);
18536 MIB.addOperand(MI->getOperand(i));
18538 MIB.setMemRefs(MMOBegin, MMOEnd);
18540 BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18542 MI->eraseFromParent();
18546 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18547 // accumulator loops. Writing back to the accumulator allows the coalescer
18548 // to remove extra copies in the loop.
18549 MachineBasicBlock *
18550 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18551 MachineBasicBlock *MBB) const {
18552 MachineOperand &AddendOp = MI->getOperand(3);
18554 // Bail out early if the addend isn't a register - we can't switch these.
18555 if (!AddendOp.isReg())
18558 MachineFunction &MF = *MBB->getParent();
18559 MachineRegisterInfo &MRI = MF.getRegInfo();
18561 // Check whether the addend is defined by a PHI:
18562 assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18563 MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18564 if (!AddendDef.isPHI())
18567 // Look for the following pattern:
18569 // %addend = phi [%entry, 0], [%loop, %result]
18571 // %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18575 // %addend = phi [%entry, 0], [%loop, %result]
18577 // %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18579 for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18580 assert(AddendDef.getOperand(i).isReg());
18581 MachineOperand PHISrcOp = AddendDef.getOperand(i);
18582 MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18583 if (&PHISrcInst == MI) {
18584 // Found a matching instruction.
18585 unsigned NewFMAOpc = 0;
18586 switch (MI->getOpcode()) {
18587 case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18588 case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18589 case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18590 case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18591 case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18592 case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18593 case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18594 case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18595 case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18596 case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18597 case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18598 case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18599 case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18600 case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18601 case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18602 case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18603 case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18604 case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18605 case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18606 case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18607 case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18608 case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18609 case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18610 case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18611 default: llvm_unreachable("Unrecognized FMA variant.");
18614 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18615 MachineInstrBuilder MIB =
18616 BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18617 .addOperand(MI->getOperand(0))
18618 .addOperand(MI->getOperand(3))
18619 .addOperand(MI->getOperand(2))
18620 .addOperand(MI->getOperand(1));
18621 MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18622 MI->eraseFromParent();
18629 MachineBasicBlock *
18630 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18631 MachineBasicBlock *BB) const {
18632 switch (MI->getOpcode()) {
18633 default: llvm_unreachable("Unexpected instr type to insert");
18634 case X86::TAILJMPd64:
18635 case X86::TAILJMPr64:
18636 case X86::TAILJMPm64:
18637 llvm_unreachable("TAILJMP64 would not be touched here.");
18638 case X86::TCRETURNdi64:
18639 case X86::TCRETURNri64:
18640 case X86::TCRETURNmi64:
18642 case X86::WIN_ALLOCA:
18643 return EmitLoweredWinAlloca(MI, BB);
18644 case X86::SEG_ALLOCA_32:
18645 return EmitLoweredSegAlloca(MI, BB, false);
18646 case X86::SEG_ALLOCA_64:
18647 return EmitLoweredSegAlloca(MI, BB, true);
18648 case X86::TLSCall_32:
18649 case X86::TLSCall_64:
18650 return EmitLoweredTLSCall(MI, BB);
18651 case X86::CMOV_GR8:
18652 case X86::CMOV_FR32:
18653 case X86::CMOV_FR64:
18654 case X86::CMOV_V4F32:
18655 case X86::CMOV_V2F64:
18656 case X86::CMOV_V2I64:
18657 case X86::CMOV_V8F32:
18658 case X86::CMOV_V4F64:
18659 case X86::CMOV_V4I64:
18660 case X86::CMOV_V16F32:
18661 case X86::CMOV_V8F64:
18662 case X86::CMOV_V8I64:
18663 case X86::CMOV_GR16:
18664 case X86::CMOV_GR32:
18665 case X86::CMOV_RFP32:
18666 case X86::CMOV_RFP64:
18667 case X86::CMOV_RFP80:
18668 return EmitLoweredSelect(MI, BB);
18670 case X86::FP32_TO_INT16_IN_MEM:
18671 case X86::FP32_TO_INT32_IN_MEM:
18672 case X86::FP32_TO_INT64_IN_MEM:
18673 case X86::FP64_TO_INT16_IN_MEM:
18674 case X86::FP64_TO_INT32_IN_MEM:
18675 case X86::FP64_TO_INT64_IN_MEM:
18676 case X86::FP80_TO_INT16_IN_MEM:
18677 case X86::FP80_TO_INT32_IN_MEM:
18678 case X86::FP80_TO_INT64_IN_MEM: {
18679 MachineFunction *F = BB->getParent();
18680 const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18681 DebugLoc DL = MI->getDebugLoc();
18683 // Change the floating point control register to use "round towards zero"
18684 // mode when truncating to an integer value.
18685 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18686 addFrameReference(BuildMI(*BB, MI, DL,
18687 TII->get(X86::FNSTCW16m)), CWFrameIdx);
18689 // Load the old value of the high byte of the control word...
18691 F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18692 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18695 // Set the high part to be round to zero...
18696 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18699 // Reload the modified control word now...
18700 addFrameReference(BuildMI(*BB, MI, DL,
18701 TII->get(X86::FLDCW16m)), CWFrameIdx);
18703 // Restore the memory image of control word to original value
18704 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18707 // Get the X86 opcode to use.
18709 switch (MI->getOpcode()) {
18710 default: llvm_unreachable("illegal opcode!");
18711 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18712 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18713 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18714 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18715 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18716 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18717 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18718 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18719 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18723 MachineOperand &Op = MI->getOperand(0);
18725 AM.BaseType = X86AddressMode::RegBase;
18726 AM.Base.Reg = Op.getReg();
18728 AM.BaseType = X86AddressMode::FrameIndexBase;
18729 AM.Base.FrameIndex = Op.getIndex();
18731 Op = MI->getOperand(1);
18733 AM.Scale = Op.getImm();
18734 Op = MI->getOperand(2);
18736 AM.IndexReg = Op.getImm();
18737 Op = MI->getOperand(3);
18738 if (Op.isGlobal()) {
18739 AM.GV = Op.getGlobal();
18741 AM.Disp = Op.getImm();
18743 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18744 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18746 // Reload the original control word now.
18747 addFrameReference(BuildMI(*BB, MI, DL,
18748 TII->get(X86::FLDCW16m)), CWFrameIdx);
18750 MI->eraseFromParent(); // The pseudo instruction is gone now.
18753 // String/text processing lowering.
18754 case X86::PCMPISTRM128REG:
18755 case X86::VPCMPISTRM128REG:
18756 case X86::PCMPISTRM128MEM:
18757 case X86::VPCMPISTRM128MEM:
18758 case X86::PCMPESTRM128REG:
18759 case X86::VPCMPESTRM128REG:
18760 case X86::PCMPESTRM128MEM:
18761 case X86::VPCMPESTRM128MEM:
18762 assert(Subtarget->hasSSE42() &&
18763 "Target must have SSE4.2 or AVX features enabled");
18764 return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18766 // String/text processing lowering.
18767 case X86::PCMPISTRIREG:
18768 case X86::VPCMPISTRIREG:
18769 case X86::PCMPISTRIMEM:
18770 case X86::VPCMPISTRIMEM:
18771 case X86::PCMPESTRIREG:
18772 case X86::VPCMPESTRIREG:
18773 case X86::PCMPESTRIMEM:
18774 case X86::VPCMPESTRIMEM:
18775 assert(Subtarget->hasSSE42() &&
18776 "Target must have SSE4.2 or AVX features enabled");
18777 return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18779 // Thread synchronization.
18781 return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18785 return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18787 // Atomic Lowering.
18788 case X86::ATOMAND8:
18789 case X86::ATOMAND16:
18790 case X86::ATOMAND32:
18791 case X86::ATOMAND64:
18794 case X86::ATOMOR16:
18795 case X86::ATOMOR32:
18796 case X86::ATOMOR64:
18798 case X86::ATOMXOR16:
18799 case X86::ATOMXOR8:
18800 case X86::ATOMXOR32:
18801 case X86::ATOMXOR64:
18803 case X86::ATOMNAND8:
18804 case X86::ATOMNAND16:
18805 case X86::ATOMNAND32:
18806 case X86::ATOMNAND64:
18808 case X86::ATOMMAX8:
18809 case X86::ATOMMAX16:
18810 case X86::ATOMMAX32:
18811 case X86::ATOMMAX64:
18813 case X86::ATOMMIN8:
18814 case X86::ATOMMIN16:
18815 case X86::ATOMMIN32:
18816 case X86::ATOMMIN64:
18818 case X86::ATOMUMAX8:
18819 case X86::ATOMUMAX16:
18820 case X86::ATOMUMAX32:
18821 case X86::ATOMUMAX64:
18823 case X86::ATOMUMIN8:
18824 case X86::ATOMUMIN16:
18825 case X86::ATOMUMIN32:
18826 case X86::ATOMUMIN64:
18827 return EmitAtomicLoadArith(MI, BB);
18829 // This group does 64-bit operations on a 32-bit host.
18830 case X86::ATOMAND6432:
18831 case X86::ATOMOR6432:
18832 case X86::ATOMXOR6432:
18833 case X86::ATOMNAND6432:
18834 case X86::ATOMADD6432:
18835 case X86::ATOMSUB6432:
18836 case X86::ATOMMAX6432:
18837 case X86::ATOMMIN6432:
18838 case X86::ATOMUMAX6432:
18839 case X86::ATOMUMIN6432:
18840 case X86::ATOMSWAP6432:
18841 return EmitAtomicLoadArith6432(MI, BB);
18843 case X86::VASTART_SAVE_XMM_REGS:
18844 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18846 case X86::VAARG_64:
18847 return EmitVAARG64WithCustomInserter(MI, BB);
18849 case X86::EH_SjLj_SetJmp32:
18850 case X86::EH_SjLj_SetJmp64:
18851 return emitEHSjLjSetJmp(MI, BB);
18853 case X86::EH_SjLj_LongJmp32:
18854 case X86::EH_SjLj_LongJmp64:
18855 return emitEHSjLjLongJmp(MI, BB);
18857 case TargetOpcode::STACKMAP:
18858 case TargetOpcode::PATCHPOINT:
18859 return emitPatchPoint(MI, BB);
18861 case X86::VFMADDPDr213r:
18862 case X86::VFMADDPSr213r:
18863 case X86::VFMADDSDr213r:
18864 case X86::VFMADDSSr213r:
18865 case X86::VFMSUBPDr213r:
18866 case X86::VFMSUBPSr213r:
18867 case X86::VFMSUBSDr213r:
18868 case X86::VFMSUBSSr213r:
18869 case X86::VFNMADDPDr213r:
18870 case X86::VFNMADDPSr213r:
18871 case X86::VFNMADDSDr213r:
18872 case X86::VFNMADDSSr213r:
18873 case X86::VFNMSUBPDr213r:
18874 case X86::VFNMSUBPSr213r:
18875 case X86::VFNMSUBSDr213r:
18876 case X86::VFNMSUBSSr213r:
18877 case X86::VFMADDPDr213rY:
18878 case X86::VFMADDPSr213rY:
18879 case X86::VFMSUBPDr213rY:
18880 case X86::VFMSUBPSr213rY:
18881 case X86::VFNMADDPDr213rY:
18882 case X86::VFNMADDPSr213rY:
18883 case X86::VFNMSUBPDr213rY:
18884 case X86::VFNMSUBPSr213rY:
18885 return emitFMA3Instr(MI, BB);
18889 //===----------------------------------------------------------------------===//
18890 // X86 Optimization Hooks
18891 //===----------------------------------------------------------------------===//
18893 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18896 const SelectionDAG &DAG,
18897 unsigned Depth) const {
18898 unsigned BitWidth = KnownZero.getBitWidth();
18899 unsigned Opc = Op.getOpcode();
18900 assert((Opc >= ISD::BUILTIN_OP_END ||
18901 Opc == ISD::INTRINSIC_WO_CHAIN ||
18902 Opc == ISD::INTRINSIC_W_CHAIN ||
18903 Opc == ISD::INTRINSIC_VOID) &&
18904 "Should use MaskedValueIsZero if you don't know whether Op"
18905 " is a target node!");
18907 KnownZero = KnownOne = APInt(BitWidth, 0); // Don't know anything.
18921 // These nodes' second result is a boolean.
18922 if (Op.getResNo() == 0)
18925 case X86ISD::SETCC:
18926 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18928 case ISD::INTRINSIC_WO_CHAIN: {
18929 unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18930 unsigned NumLoBits = 0;
18933 case Intrinsic::x86_sse_movmsk_ps:
18934 case Intrinsic::x86_avx_movmsk_ps_256:
18935 case Intrinsic::x86_sse2_movmsk_pd:
18936 case Intrinsic::x86_avx_movmsk_pd_256:
18937 case Intrinsic::x86_mmx_pmovmskb:
18938 case Intrinsic::x86_sse2_pmovmskb_128:
18939 case Intrinsic::x86_avx2_pmovmskb: {
18940 // High bits of movmskp{s|d}, pmovmskb are known zero.
18942 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
18943 case Intrinsic::x86_sse_movmsk_ps: NumLoBits = 4; break;
18944 case Intrinsic::x86_avx_movmsk_ps_256: NumLoBits = 8; break;
18945 case Intrinsic::x86_sse2_movmsk_pd: NumLoBits = 2; break;
18946 case Intrinsic::x86_avx_movmsk_pd_256: NumLoBits = 4; break;
18947 case Intrinsic::x86_mmx_pmovmskb: NumLoBits = 8; break;
18948 case Intrinsic::x86_sse2_pmovmskb_128: NumLoBits = 16; break;
18949 case Intrinsic::x86_avx2_pmovmskb: NumLoBits = 32; break;
18951 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18960 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18962 const SelectionDAG &,
18963 unsigned Depth) const {
18964 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18965 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18966 return Op.getValueType().getScalarType().getSizeInBits();
18972 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18973 /// node is a GlobalAddress + offset.
18974 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18975 const GlobalValue* &GA,
18976 int64_t &Offset) const {
18977 if (N->getOpcode() == X86ISD::Wrapper) {
18978 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18979 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18980 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18984 return TargetLowering::isGAPlusOffset(N, GA, Offset);
18987 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18988 /// same as extracting the high 128-bit part of 256-bit vector and then
18989 /// inserting the result into the low part of a new 256-bit vector
18990 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18991 EVT VT = SVOp->getValueType(0);
18992 unsigned NumElems = VT.getVectorNumElements();
18994 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18995 for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18996 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18997 SVOp->getMaskElt(j) >= 0)
19003 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19004 /// same as extracting the low 128-bit part of 256-bit vector and then
19005 /// inserting the result into the high part of a new 256-bit vector
19006 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19007 EVT VT = SVOp->getValueType(0);
19008 unsigned NumElems = VT.getVectorNumElements();
19010 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19011 for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19012 if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19013 SVOp->getMaskElt(j) >= 0)
19019 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19020 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19021 TargetLowering::DAGCombinerInfo &DCI,
19022 const X86Subtarget* Subtarget) {
19024 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19025 SDValue V1 = SVOp->getOperand(0);
19026 SDValue V2 = SVOp->getOperand(1);
19027 EVT VT = SVOp->getValueType(0);
19028 unsigned NumElems = VT.getVectorNumElements();
19030 if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19031 V2.getOpcode() == ISD::CONCAT_VECTORS) {
19035 // V UNDEF BUILD_VECTOR UNDEF
19037 // CONCAT_VECTOR CONCAT_VECTOR
19040 // RESULT: V + zero extended
19042 if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19043 V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19044 V1.getOperand(1).getOpcode() != ISD::UNDEF)
19047 if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19050 // To match the shuffle mask, the first half of the mask should
19051 // be exactly the first vector, and all the rest a splat with the
19052 // first element of the second one.
19053 for (unsigned i = 0; i != NumElems/2; ++i)
19054 if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19055 !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19058 // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19059 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19060 if (Ld->hasNUsesOfValue(1, 0)) {
19061 SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19062 SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19064 DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19066 Ld->getPointerInfo(),
19067 Ld->getAlignment(),
19068 false/*isVolatile*/, true/*ReadMem*/,
19069 false/*WriteMem*/);
19071 // Make sure the newly-created LOAD is in the same position as Ld in
19072 // terms of dependency. We create a TokenFactor for Ld and ResNode,
19073 // and update uses of Ld's output chain to use the TokenFactor.
19074 if (Ld->hasAnyUseOfValue(1)) {
19075 SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19076 SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19077 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19078 DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19079 SDValue(ResNode.getNode(), 1));
19082 return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19086 // Emit a zeroed vector and insert the desired subvector on its
19088 SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19089 SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19090 return DCI.CombineTo(N, InsV);
19093 //===--------------------------------------------------------------------===//
19094 // Combine some shuffles into subvector extracts and inserts:
19097 // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19098 if (isShuffleHigh128VectorInsertLow(SVOp)) {
19099 SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19100 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19101 return DCI.CombineTo(N, InsV);
19104 // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19105 if (isShuffleLow128VectorInsertHigh(SVOp)) {
19106 SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19107 SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19108 return DCI.CombineTo(N, InsV);
19114 /// \brief Get the PSHUF-style mask from PSHUF node.
19116 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19117 /// PSHUF-style masks that can be reused with such instructions.
19118 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19119 SmallVector<int, 4> Mask;
19121 bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19125 switch (N.getOpcode()) {
19126 case X86ISD::PSHUFD:
19128 case X86ISD::PSHUFLW:
19131 case X86ISD::PSHUFHW:
19132 Mask.erase(Mask.begin(), Mask.begin() + 4);
19133 for (int &M : Mask)
19137 llvm_unreachable("No valid shuffle instruction found!");
19141 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19143 /// We walk up the chain and look for a combinable shuffle, skipping over
19144 /// shuffles that we could hoist this shuffle's transformation past without
19145 /// altering anything.
19146 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19148 TargetLowering::DAGCombinerInfo &DCI) {
19149 assert(N.getOpcode() == X86ISD::PSHUFD &&
19150 "Called with something other than an x86 128-bit half shuffle!");
19153 // Walk up a single-use chain looking for a combinable shuffle.
19154 SDValue V = N.getOperand(0);
19155 for (; V.hasOneUse(); V = V.getOperand(0)) {
19156 switch (V.getOpcode()) {
19158 return false; // Nothing combined!
19161 // Skip bitcasts as we always know the type for the target specific
19165 case X86ISD::PSHUFD:
19166 // Found another dword shuffle.
19169 case X86ISD::PSHUFLW:
19170 // Check that the low words (being shuffled) are the identity in the
19171 // dword shuffle, and the high words are self-contained.
19172 if (Mask[0] != 0 || Mask[1] != 1 ||
19173 !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19178 case X86ISD::PSHUFHW:
19179 // Check that the high words (being shuffled) are the identity in the
19180 // dword shuffle, and the low words are self-contained.
19181 if (Mask[2] != 2 || Mask[3] != 3 ||
19182 !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19187 // Break out of the loop if we break out of the switch.
19191 if (!V.hasOneUse())
19192 // We fell out of the loop without finding a viable combining instruction.
19195 // Record the old value to use in RAUW-ing.
19198 // Merge this node's mask and our incoming mask.
19199 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19200 for (int &M : Mask)
19202 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V.getOperand(0),
19203 getV4X86ShuffleImm8ForMask(Mask, DAG));
19205 // Replace N with its operand as we're going to combine that shuffle away.
19206 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19208 // Replace the combinable shuffle with the combined one, updating all users
19209 // so that we re-evaluate the chain here.
19210 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19214 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19216 /// We walk up the chain, skipping shuffles of the other half and looking
19217 /// through shuffles which switch halves trying to find a shuffle of the same
19218 /// pair of dwords.
19219 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19221 TargetLowering::DAGCombinerInfo &DCI) {
19223 (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19224 "Called with something other than an x86 128-bit half shuffle!");
19226 unsigned CombineOpcode = N.getOpcode();
19228 // Walk up a single-use chain looking for a combinable shuffle.
19229 SDValue V = N.getOperand(0);
19230 for (; V.hasOneUse(); V = V.getOperand(0)) {
19231 switch (V.getOpcode()) {
19233 return false; // Nothing combined!
19236 // Skip bitcasts as we always know the type for the target specific
19240 case X86ISD::PSHUFLW:
19241 case X86ISD::PSHUFHW:
19242 if (V.getOpcode() == CombineOpcode)
19245 // Other-half shuffles are no-ops.
19248 case X86ISD::PSHUFD: {
19249 // We can only handle pshufd if the half we are combining either stays in
19250 // its half, or switches to the other half. Bail if one of these isn't
19252 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19253 int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
19254 if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
19255 (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
19258 // Map the mask through the pshufd and keep walking up the chain.
19259 for (int i = 0; i < 4; ++i)
19260 Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
19262 // Switch halves if the pshufd does.
19264 VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19268 // Break out of the loop if we break out of the switch.
19272 if (!V.hasOneUse())
19273 // We fell out of the loop without finding a viable combining instruction.
19276 // Record the old value to use in RAUW-ing.
19279 // Merge this node's mask and our incoming mask (adjusted to account for all
19280 // the pshufd instructions encountered).
19281 SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19282 for (int &M : Mask)
19284 V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19285 getV4X86ShuffleImm8ForMask(Mask, DAG));
19287 // Replace N with its operand as we're going to combine that shuffle away.
19288 DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19290 // Replace the combinable shuffle with the combined one, updating all users
19291 // so that we re-evaluate the chain here.
19292 DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19296 /// \brief Try to combine x86 target specific shuffles.
19297 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19298 TargetLowering::DAGCombinerInfo &DCI,
19299 const X86Subtarget *Subtarget) {
19301 MVT VT = N.getSimpleValueType();
19302 SmallVector<int, 4> Mask;
19304 switch (N.getOpcode()) {
19305 case X86ISD::PSHUFD:
19306 case X86ISD::PSHUFLW:
19307 case X86ISD::PSHUFHW:
19308 Mask = getPSHUFShuffleMask(N);
19309 assert(Mask.size() == 4);
19315 // Nuke no-op shuffles that show up after combining.
19316 if (isNoopShuffleMask(Mask))
19317 return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19319 // Look for simplifications involving one or two shuffle instructions.
19320 SDValue V = N.getOperand(0);
19321 switch (N.getOpcode()) {
19324 case X86ISD::PSHUFLW:
19325 case X86ISD::PSHUFHW:
19326 assert(VT == MVT::v8i16);
19329 if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19330 return SDValue(); // We combined away this shuffle, so we're done.
19332 // See if this reduces to a PSHUFD which is no more expensive and can
19333 // combine with more operations.
19334 if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
19335 areAdjacentMasksSequential(Mask)) {
19336 int DMask[] = {-1, -1, -1, -1};
19337 int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19338 DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19339 DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19340 V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19341 DCI.AddToWorklist(V.getNode());
19342 V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19343 getV4X86ShuffleImm8ForMask(DMask, DAG));
19344 DCI.AddToWorklist(V.getNode());
19345 return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19350 case X86ISD::PSHUFD:
19351 if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19352 return SDValue(); // We combined away this shuffle.
19360 /// PerformShuffleCombine - Performs several different shuffle combines.
19361 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19362 TargetLowering::DAGCombinerInfo &DCI,
19363 const X86Subtarget *Subtarget) {
19365 SDValue N0 = N->getOperand(0);
19366 SDValue N1 = N->getOperand(1);
19367 EVT VT = N->getValueType(0);
19369 // Canonicalize shuffles that perform 'addsub' on packed float vectors
19370 // according to the rule:
19371 // (shuffle (FADD A, B), (FSUB A, B), Mask) ->
19372 // (shuffle (FSUB A, -B), (FADD A, -B), Mask)
19374 // Where 'Mask' is:
19375 // <0,5,2,7> -- for v4f32 and v4f64 shuffles;
19376 // <0,3> -- for v2f64 shuffles;
19377 // <0,9,2,11,4,13,6,15> -- for v8f32 shuffles.
19379 // This helps pattern-matching more SSE3/AVX ADDSUB instructions
19380 // during ISel stage.
19381 if (N->getOpcode() == ISD::VECTOR_SHUFFLE &&
19382 ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
19383 (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
19384 N0->getOpcode() == ISD::FADD && N1->getOpcode() == ISD::FSUB &&
19385 // Operands to the FADD and FSUB must be the same.
19386 ((N0->getOperand(0) == N1->getOperand(0) &&
19387 N0->getOperand(1) == N1->getOperand(1)) ||
19388 // FADD is commutable. See if by commuting the operands of the FADD
19389 // we would still be able to match the operands of the FSUB dag node.
19390 (N0->getOperand(1) == N1->getOperand(0) &&
19391 N0->getOperand(0) == N1->getOperand(1))) &&
19392 N0->getOperand(0)->getOpcode() != ISD::UNDEF &&
19393 N0->getOperand(1)->getOpcode() != ISD::UNDEF) {
19395 ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
19396 unsigned NumElts = VT.getVectorNumElements();
19397 ArrayRef<int> Mask = SV->getMask();
19398 bool CanFold = true;
19400 for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i)
19401 CanFold = Mask[i] == (int)((i & 1) ? i + NumElts : i);
19404 SDValue Op0 = N1->getOperand(0);
19405 SDValue Op1 = DAG.getNode(ISD::FNEG, dl, VT, N1->getOperand(1));
19406 SDValue Sub = DAG.getNode(ISD::FSUB, dl, VT, Op0, Op1);
19407 SDValue Add = DAG.getNode(ISD::FADD, dl, VT, Op0, Op1);
19408 return DAG.getVectorShuffle(VT, dl, Sub, Add, Mask);
19412 // Don't create instructions with illegal types after legalize types has run.
19413 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19414 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19417 // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19418 if (Subtarget->hasFp256() && VT.is256BitVector() &&
19419 N->getOpcode() == ISD::VECTOR_SHUFFLE)
19420 return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19422 // During Type Legalization, when promoting illegal vector types,
19423 // the backend might introduce new shuffle dag nodes and bitcasts.
19425 // This code performs the following transformation:
19426 // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19427 // (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19429 // We do this only if both the bitcast and the BINOP dag nodes have
19430 // one use. Also, perform this transformation only if the new binary
19431 // operation is legal. This is to avoid introducing dag nodes that
19432 // potentially need to be further expanded (or custom lowered) into a
19433 // less optimal sequence of dag nodes.
19434 if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19435 N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19436 N0.getOpcode() == ISD::BITCAST) {
19437 SDValue BC0 = N0.getOperand(0);
19438 EVT SVT = BC0.getValueType();
19439 unsigned Opcode = BC0.getOpcode();
19440 unsigned NumElts = VT.getVectorNumElements();
19442 if (BC0.hasOneUse() && SVT.isVector() &&
19443 SVT.getVectorNumElements() * 2 == NumElts &&
19444 TLI.isOperationLegal(Opcode, VT)) {
19445 bool CanFold = false;
19457 unsigned SVTNumElts = SVT.getVectorNumElements();
19458 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19459 for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19460 CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19461 for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19462 CanFold = SVOp->getMaskElt(i) < 0;
19465 SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19466 SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19467 SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19468 return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19473 // Only handle 128 wide vector from here on.
19474 if (!VT.is128BitVector())
19477 // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19478 // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19479 // consecutive, non-overlapping, and in the right order.
19480 SmallVector<SDValue, 16> Elts;
19481 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19482 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19484 SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19488 if (isTargetShuffle(N->getOpcode())) {
19490 PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19491 if (Shuffle.getNode())
19498 /// PerformTruncateCombine - Converts truncate operation to
19499 /// a sequence of vector shuffle operations.
19500 /// It is possible when we truncate 256-bit vector to 128-bit vector
19501 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19502 TargetLowering::DAGCombinerInfo &DCI,
19503 const X86Subtarget *Subtarget) {
19507 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19508 /// specific shuffle of a load can be folded into a single element load.
19509 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19510 /// shuffles have been customed lowered so we need to handle those here.
19511 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19512 TargetLowering::DAGCombinerInfo &DCI) {
19513 if (DCI.isBeforeLegalizeOps())
19516 SDValue InVec = N->getOperand(0);
19517 SDValue EltNo = N->getOperand(1);
19519 if (!isa<ConstantSDNode>(EltNo))
19522 EVT VT = InVec.getValueType();
19524 bool HasShuffleIntoBitcast = false;
19525 if (InVec.getOpcode() == ISD::BITCAST) {
19526 // Don't duplicate a load with other uses.
19527 if (!InVec.hasOneUse())
19529 EVT BCVT = InVec.getOperand(0).getValueType();
19530 if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19532 InVec = InVec.getOperand(0);
19533 HasShuffleIntoBitcast = true;
19536 if (!isTargetShuffle(InVec.getOpcode()))
19539 // Don't duplicate a load with other uses.
19540 if (!InVec.hasOneUse())
19543 SmallVector<int, 16> ShuffleMask;
19545 if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19549 // Select the input vector, guarding against out of range extract vector.
19550 unsigned NumElems = VT.getVectorNumElements();
19551 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19552 int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19553 SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19554 : InVec.getOperand(1);
19556 // If inputs to shuffle are the same for both ops, then allow 2 uses
19557 unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19559 if (LdNode.getOpcode() == ISD::BITCAST) {
19560 // Don't duplicate a load with other uses.
19561 if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19564 AllowedUses = 1; // only allow 1 load use if we have a bitcast
19565 LdNode = LdNode.getOperand(0);
19568 if (!ISD::isNormalLoad(LdNode.getNode()))
19571 LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19573 if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19576 if (HasShuffleIntoBitcast) {
19577 // If there's a bitcast before the shuffle, check if the load type and
19578 // alignment is valid.
19579 unsigned Align = LN0->getAlignment();
19580 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19581 unsigned NewAlign = TLI.getDataLayout()->
19582 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19584 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19588 // All checks match so transform back to vector_shuffle so that DAG combiner
19589 // can finish the job
19592 // Create shuffle node taking into account the case that its a unary shuffle
19593 SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19594 Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19595 InVec.getOperand(0), Shuffle,
19597 Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19598 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19602 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19603 /// generation and convert it from being a bunch of shuffles and extracts
19604 /// to a simple store and scalar loads to extract the elements.
19605 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19606 TargetLowering::DAGCombinerInfo &DCI) {
19607 SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19608 if (NewOp.getNode())
19611 SDValue InputVector = N->getOperand(0);
19613 // Detect whether we are trying to convert from mmx to i32 and the bitcast
19614 // from mmx to v2i32 has a single usage.
19615 if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19616 InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19617 InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19618 return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19619 N->getValueType(0),
19620 InputVector.getNode()->getOperand(0));
19622 // Only operate on vectors of 4 elements, where the alternative shuffling
19623 // gets to be more expensive.
19624 if (InputVector.getValueType() != MVT::v4i32)
19627 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19628 // single use which is a sign-extend or zero-extend, and all elements are
19630 SmallVector<SDNode *, 4> Uses;
19631 unsigned ExtractedElements = 0;
19632 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19633 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19634 if (UI.getUse().getResNo() != InputVector.getResNo())
19637 SDNode *Extract = *UI;
19638 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19641 if (Extract->getValueType(0) != MVT::i32)
19643 if (!Extract->hasOneUse())
19645 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19646 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19648 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19651 // Record which element was extracted.
19652 ExtractedElements |=
19653 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19655 Uses.push_back(Extract);
19658 // If not all the elements were used, this may not be worthwhile.
19659 if (ExtractedElements != 15)
19662 // Ok, we've now decided to do the transformation.
19663 SDLoc dl(InputVector);
19665 // Store the value to a temporary stack slot.
19666 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19667 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19668 MachinePointerInfo(), false, false, 0);
19670 // Replace each use (extract) with a load of the appropriate element.
19671 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19672 UE = Uses.end(); UI != UE; ++UI) {
19673 SDNode *Extract = *UI;
19675 // cOMpute the element's address.
19676 SDValue Idx = Extract->getOperand(1);
19678 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19679 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19680 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19681 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19683 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19684 StackPtr, OffsetVal);
19686 // Load the scalar.
19687 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19688 ScalarAddr, MachinePointerInfo(),
19689 false, false, false, 0);
19691 // Replace the exact with the load.
19692 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19695 // The replacement was made in place; don't return anything.
19699 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19700 static std::pair<unsigned, bool>
19701 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19702 SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19703 if (!VT.isVector())
19704 return std::make_pair(0, false);
19706 bool NeedSplit = false;
19707 switch (VT.getSimpleVT().SimpleTy) {
19708 default: return std::make_pair(0, false);
19712 if (!Subtarget->hasAVX2())
19714 if (!Subtarget->hasAVX())
19715 return std::make_pair(0, false);
19720 if (!Subtarget->hasSSE2())
19721 return std::make_pair(0, false);
19724 // SSE2 has only a small subset of the operations.
19725 bool hasUnsigned = Subtarget->hasSSE41() ||
19726 (Subtarget->hasSSE2() && VT == MVT::v16i8);
19727 bool hasSigned = Subtarget->hasSSE41() ||
19728 (Subtarget->hasSSE2() && VT == MVT::v8i16);
19730 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19733 // Check for x CC y ? x : y.
19734 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19735 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19740 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19743 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19746 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19749 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19751 // Check for x CC y ? y : x -- a min/max with reversed arms.
19752 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19753 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19758 Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19761 Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19764 Opc = hasSigned ? X86ISD::SMAX : 0; break;
19767 Opc = hasSigned ? X86ISD::SMIN : 0; break;
19771 return std::make_pair(Opc, NeedSplit);
19775 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19776 const X86Subtarget *Subtarget) {
19778 SDValue Cond = N->getOperand(0);
19779 SDValue LHS = N->getOperand(1);
19780 SDValue RHS = N->getOperand(2);
19782 if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19783 SDValue CondSrc = Cond->getOperand(0);
19784 if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19785 Cond = CondSrc->getOperand(0);
19788 MVT VT = N->getSimpleValueType(0);
19789 MVT EltVT = VT.getVectorElementType();
19790 unsigned NumElems = VT.getVectorNumElements();
19791 // There is no blend with immediate in AVX-512.
19792 if (VT.is512BitVector())
19795 if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19797 if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19800 if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19803 unsigned MaskValue = 0;
19804 if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19807 SmallVector<int, 8> ShuffleMask(NumElems, -1);
19808 for (unsigned i = 0; i < NumElems; ++i) {
19809 // Be sure we emit undef where we can.
19810 if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19811 ShuffleMask[i] = -1;
19813 ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19816 return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19819 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19821 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19822 TargetLowering::DAGCombinerInfo &DCI,
19823 const X86Subtarget *Subtarget) {
19825 SDValue Cond = N->getOperand(0);
19826 // Get the LHS/RHS of the select.
19827 SDValue LHS = N->getOperand(1);
19828 SDValue RHS = N->getOperand(2);
19829 EVT VT = LHS.getValueType();
19830 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19832 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19833 // instructions match the semantics of the common C idiom x<y?x:y but not
19834 // x<=y?x:y, because of how they handle negative zero (which can be
19835 // ignored in unsafe-math mode).
19836 if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19837 VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19838 (Subtarget->hasSSE2() ||
19839 (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19840 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19842 unsigned Opcode = 0;
19843 // Check for x CC y ? x : y.
19844 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19845 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19849 // Converting this to a min would handle NaNs incorrectly, and swapping
19850 // the operands would cause it to handle comparisons between positive
19851 // and negative zero incorrectly.
19852 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19853 if (!DAG.getTarget().Options.UnsafeFPMath &&
19854 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19856 std::swap(LHS, RHS);
19858 Opcode = X86ISD::FMIN;
19861 // Converting this to a min would handle comparisons between positive
19862 // and negative zero incorrectly.
19863 if (!DAG.getTarget().Options.UnsafeFPMath &&
19864 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19866 Opcode = X86ISD::FMIN;
19869 // Converting this to a min would handle both negative zeros and NaNs
19870 // incorrectly, but we can swap the operands to fix both.
19871 std::swap(LHS, RHS);
19875 Opcode = X86ISD::FMIN;
19879 // Converting this to a max would handle comparisons between positive
19880 // and negative zero incorrectly.
19881 if (!DAG.getTarget().Options.UnsafeFPMath &&
19882 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19884 Opcode = X86ISD::FMAX;
19887 // Converting this to a max would handle NaNs incorrectly, and swapping
19888 // the operands would cause it to handle comparisons between positive
19889 // and negative zero incorrectly.
19890 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19891 if (!DAG.getTarget().Options.UnsafeFPMath &&
19892 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19894 std::swap(LHS, RHS);
19896 Opcode = X86ISD::FMAX;
19899 // Converting this to a max would handle both negative zeros and NaNs
19900 // incorrectly, but we can swap the operands to fix both.
19901 std::swap(LHS, RHS);
19905 Opcode = X86ISD::FMAX;
19908 // Check for x CC y ? y : x -- a min/max with reversed arms.
19909 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19910 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19914 // Converting this to a min would handle comparisons between positive
19915 // and negative zero incorrectly, and swapping the operands would
19916 // cause it to handle NaNs incorrectly.
19917 if (!DAG.getTarget().Options.UnsafeFPMath &&
19918 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19919 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19921 std::swap(LHS, RHS);
19923 Opcode = X86ISD::FMIN;
19926 // Converting this to a min would handle NaNs incorrectly.
19927 if (!DAG.getTarget().Options.UnsafeFPMath &&
19928 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19930 Opcode = X86ISD::FMIN;
19933 // Converting this to a min would handle both negative zeros and NaNs
19934 // incorrectly, but we can swap the operands to fix both.
19935 std::swap(LHS, RHS);
19939 Opcode = X86ISD::FMIN;
19943 // Converting this to a max would handle NaNs incorrectly.
19944 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19946 Opcode = X86ISD::FMAX;
19949 // Converting this to a max would handle comparisons between positive
19950 // and negative zero incorrectly, and swapping the operands would
19951 // cause it to handle NaNs incorrectly.
19952 if (!DAG.getTarget().Options.UnsafeFPMath &&
19953 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19954 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19956 std::swap(LHS, RHS);
19958 Opcode = X86ISD::FMAX;
19961 // Converting this to a max would handle both negative zeros and NaNs
19962 // incorrectly, but we can swap the operands to fix both.
19963 std::swap(LHS, RHS);
19967 Opcode = X86ISD::FMAX;
19973 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19976 EVT CondVT = Cond.getValueType();
19977 if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19978 CondVT.getVectorElementType() == MVT::i1) {
19979 // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19980 // lowering on AVX-512. In this case we convert it to
19981 // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19982 // The same situation for all 128 and 256-bit vectors of i8 and i16
19983 EVT OpVT = LHS.getValueType();
19984 if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19985 (OpVT.getVectorElementType() == MVT::i8 ||
19986 OpVT.getVectorElementType() == MVT::i16)) {
19987 Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19988 DCI.AddToWorklist(Cond.getNode());
19989 return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19992 // If this is a select between two integer constants, try to do some
19994 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19995 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19996 // Don't do this for crazy integer types.
19997 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19998 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19999 // so that TrueC (the true value) is larger than FalseC.
20000 bool NeedsCondInvert = false;
20002 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20003 // Efficiently invertible.
20004 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
20005 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
20006 isa<ConstantSDNode>(Cond.getOperand(1))))) {
20007 NeedsCondInvert = true;
20008 std::swap(TrueC, FalseC);
20011 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
20012 if (FalseC->getAPIntValue() == 0 &&
20013 TrueC->getAPIntValue().isPowerOf2()) {
20014 if (NeedsCondInvert) // Invert the condition if needed.
20015 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20016 DAG.getConstant(1, Cond.getValueType()));
20018 // Zero extend the condition if needed.
20019 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20021 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20022 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20023 DAG.getConstant(ShAmt, MVT::i8));
20026 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20027 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20028 if (NeedsCondInvert) // Invert the condition if needed.
20029 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20030 DAG.getConstant(1, Cond.getValueType()));
20032 // Zero extend the condition if needed.
20033 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20034 FalseC->getValueType(0), Cond);
20035 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20036 SDValue(FalseC, 0));
20039 // Optimize cases that will turn into an LEA instruction. This requires
20040 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20041 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20042 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20043 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20045 bool isFastMultiplier = false;
20047 switch ((unsigned char)Diff) {
20049 case 1: // result = add base, cond
20050 case 2: // result = lea base( , cond*2)
20051 case 3: // result = lea base(cond, cond*2)
20052 case 4: // result = lea base( , cond*4)
20053 case 5: // result = lea base(cond, cond*4)
20054 case 8: // result = lea base( , cond*8)
20055 case 9: // result = lea base(cond, cond*8)
20056 isFastMultiplier = true;
20061 if (isFastMultiplier) {
20062 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20063 if (NeedsCondInvert) // Invert the condition if needed.
20064 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20065 DAG.getConstant(1, Cond.getValueType()));
20067 // Zero extend the condition if needed.
20068 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20070 // Scale the condition by the difference.
20072 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20073 DAG.getConstant(Diff, Cond.getValueType()));
20075 // Add the base if non-zero.
20076 if (FalseC->getAPIntValue() != 0)
20077 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20078 SDValue(FalseC, 0));
20085 // Canonicalize max and min:
20086 // (x > y) ? x : y -> (x >= y) ? x : y
20087 // (x < y) ? x : y -> (x <= y) ? x : y
20088 // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20089 // the need for an extra compare
20090 // against zero. e.g.
20091 // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20093 // testl %edi, %edi
20095 // cmovgl %edi, %eax
20099 // cmovsl %eax, %edi
20100 if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20101 DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20102 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20103 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20108 ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20109 Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20110 Cond.getOperand(0), Cond.getOperand(1), NewCC);
20111 return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20116 // Early exit check
20117 if (!TLI.isTypeLegal(VT))
20120 // Match VSELECTs into subs with unsigned saturation.
20121 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20122 // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20123 ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20124 (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20125 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20127 // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20128 // left side invert the predicate to simplify logic below.
20130 if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20132 CC = ISD::getSetCCInverse(CC, true);
20133 } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20137 if (Other.getNode() && Other->getNumOperands() == 2 &&
20138 DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20139 SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20140 SDValue CondRHS = Cond->getOperand(1);
20142 // Look for a general sub with unsigned saturation first.
20143 // x >= y ? x-y : 0 --> subus x, y
20144 // x > y ? x-y : 0 --> subus x, y
20145 if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20146 Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20147 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20149 // If the RHS is a constant we have to reverse the const canonicalization.
20150 // x > C-1 ? x+-C : 0 --> subus x, C
20151 if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20152 isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
20153 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
20154 if (CondRHS.getConstantOperandVal(0) == -A-1)
20155 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
20156 DAG.getConstant(-A, VT));
20159 // Another special case: If C was a sign bit, the sub has been
20160 // canonicalized into a xor.
20161 // FIXME: Would it be better to use computeKnownBits to determine whether
20162 // it's safe to decanonicalize the xor?
20163 // x s< 0 ? x^C : 0 --> subus x, C
20164 if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20165 ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20166 isSplatVector(OpRHS.getNode())) {
20167 APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
20169 return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20174 // Try to match a min/max vector operation.
20175 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20176 std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20177 unsigned Opc = ret.first;
20178 bool NeedSplit = ret.second;
20180 if (Opc && NeedSplit) {
20181 unsigned NumElems = VT.getVectorNumElements();
20182 // Extract the LHS vectors
20183 SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20184 SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20186 // Extract the RHS vectors
20187 SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20188 SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20190 // Create min/max for each subvector
20191 LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20192 RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20194 // Merge the result
20195 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20197 return DAG.getNode(Opc, DL, VT, LHS, RHS);
20200 // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20201 if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20202 // Check if SETCC has already been promoted
20203 TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20204 // Check that condition value type matches vselect operand type
20207 assert(Cond.getValueType().isVector() &&
20208 "vector select expects a vector selector!");
20210 bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20211 bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20213 if (!TValIsAllOnes && !FValIsAllZeros) {
20214 // Try invert the condition if true value is not all 1s and false value
20216 bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20217 bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20219 if (TValIsAllZeros || FValIsAllOnes) {
20220 SDValue CC = Cond.getOperand(2);
20221 ISD::CondCode NewCC =
20222 ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20223 Cond.getOperand(0).getValueType().isInteger());
20224 Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20225 std::swap(LHS, RHS);
20226 TValIsAllOnes = FValIsAllOnes;
20227 FValIsAllZeros = TValIsAllZeros;
20231 if (TValIsAllOnes || FValIsAllZeros) {
20234 if (TValIsAllOnes && FValIsAllZeros)
20236 else if (TValIsAllOnes)
20237 Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20238 DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20239 else if (FValIsAllZeros)
20240 Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20241 DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20243 return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20247 // Try to fold this VSELECT into a MOVSS/MOVSD
20248 if (N->getOpcode() == ISD::VSELECT &&
20249 Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20250 if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20251 (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20252 bool CanFold = false;
20253 unsigned NumElems = Cond.getNumOperands();
20257 if (isZero(Cond.getOperand(0))) {
20260 // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20261 // fold (vselect <0,-1> -> (movsd A, B)
20262 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20263 CanFold = isAllOnes(Cond.getOperand(i));
20264 } else if (isAllOnes(Cond.getOperand(0))) {
20268 // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20269 // fold (vselect <-1,0> -> (movsd B, A)
20270 for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20271 CanFold = isZero(Cond.getOperand(i));
20275 if (VT == MVT::v4i32 || VT == MVT::v4f32)
20276 return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20277 return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20280 if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20281 // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20282 // (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20283 // (v2i64 (bitcast B)))))
20285 // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20286 // (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20287 // (v2f64 (bitcast B)))))
20289 // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20290 // (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20291 // (v2i64 (bitcast A)))))
20293 // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20294 // (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20295 // (v2f64 (bitcast A)))))
20297 CanFold = (isZero(Cond.getOperand(0)) &&
20298 isZero(Cond.getOperand(1)) &&
20299 isAllOnes(Cond.getOperand(2)) &&
20300 isAllOnes(Cond.getOperand(3)));
20302 if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20303 isAllOnes(Cond.getOperand(1)) &&
20304 isZero(Cond.getOperand(2)) &&
20305 isZero(Cond.getOperand(3))) {
20307 std::swap(LHS, RHS);
20311 EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20312 SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20313 SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20314 SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20316 return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20322 // If we know that this node is legal then we know that it is going to be
20323 // matched by one of the SSE/AVX BLEND instructions. These instructions only
20324 // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20325 // to simplify previous instructions.
20326 if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20327 !DCI.isBeforeLegalize() &&
20328 // We explicitly check against v8i16 and v16i16 because, although
20329 // they're marked as Custom, they might only be legal when Cond is a
20330 // build_vector of constants. This will be taken care in a later
20332 (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20333 VT != MVT::v8i16)) {
20334 unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20336 // Don't optimize vector selects that map to mask-registers.
20340 // Check all uses of that condition operand to check whether it will be
20341 // consumed by non-BLEND instructions, which may depend on all bits are set
20343 for (SDNode::use_iterator I = Cond->use_begin(),
20344 E = Cond->use_end(); I != E; ++I)
20345 if (I->getOpcode() != ISD::VSELECT)
20346 // TODO: Add other opcodes eventually lowered into BLEND.
20349 assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20350 APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20352 APInt KnownZero, KnownOne;
20353 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20354 DCI.isBeforeLegalizeOps());
20355 if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20356 TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20357 DCI.CommitTargetLoweringOpt(TLO);
20360 // We should generate an X86ISD::BLENDI from a vselect if its argument
20361 // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20362 // constants. This specific pattern gets generated when we split a
20363 // selector for a 512 bit vector in a machine without AVX512 (but with
20364 // 256-bit vectors), during legalization:
20366 // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20368 // Iff we find this pattern and the build_vectors are built from
20369 // constants, we translate the vselect into a shuffle_vector that we
20370 // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20371 if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20372 SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20373 if (Shuffle.getNode())
20380 // Check whether a boolean test is testing a boolean value generated by
20381 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20384 // Simplify the following patterns:
20385 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20386 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20387 // to (Op EFLAGS Cond)
20389 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20390 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20391 // to (Op EFLAGS !Cond)
20393 // where Op could be BRCOND or CMOV.
20395 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20396 // Quit if not CMP and SUB with its value result used.
20397 if (Cmp.getOpcode() != X86ISD::CMP &&
20398 (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20401 // Quit if not used as a boolean value.
20402 if (CC != X86::COND_E && CC != X86::COND_NE)
20405 // Check CMP operands. One of them should be 0 or 1 and the other should be
20406 // an SetCC or extended from it.
20407 SDValue Op1 = Cmp.getOperand(0);
20408 SDValue Op2 = Cmp.getOperand(1);
20411 const ConstantSDNode* C = nullptr;
20412 bool needOppositeCond = (CC == X86::COND_E);
20413 bool checkAgainstTrue = false; // Is it a comparison against 1?
20415 if ((C = dyn_cast<ConstantSDNode>(Op1)))
20417 else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20419 else // Quit if all operands are not constants.
20422 if (C->getZExtValue() == 1) {
20423 needOppositeCond = !needOppositeCond;
20424 checkAgainstTrue = true;
20425 } else if (C->getZExtValue() != 0)
20426 // Quit if the constant is neither 0 or 1.
20429 bool truncatedToBoolWithAnd = false;
20430 // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20431 while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20432 SetCC.getOpcode() == ISD::TRUNCATE ||
20433 SetCC.getOpcode() == ISD::AND) {
20434 if (SetCC.getOpcode() == ISD::AND) {
20436 ConstantSDNode *CS;
20437 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20438 CS->getZExtValue() == 1)
20440 if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20441 CS->getZExtValue() == 1)
20445 SetCC = SetCC.getOperand(OpIdx);
20446 truncatedToBoolWithAnd = true;
20448 SetCC = SetCC.getOperand(0);
20451 switch (SetCC.getOpcode()) {
20452 case X86ISD::SETCC_CARRY:
20453 // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20454 // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20455 // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20456 // truncated to i1 using 'and'.
20457 if (checkAgainstTrue && !truncatedToBoolWithAnd)
20459 assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20460 "Invalid use of SETCC_CARRY!");
20462 case X86ISD::SETCC:
20463 // Set the condition code or opposite one if necessary.
20464 CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20465 if (needOppositeCond)
20466 CC = X86::GetOppositeBranchCondition(CC);
20467 return SetCC.getOperand(1);
20468 case X86ISD::CMOV: {
20469 // Check whether false/true value has canonical one, i.e. 0 or 1.
20470 ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20471 ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20472 // Quit if true value is not a constant.
20475 // Quit if false value is not a constant.
20477 SDValue Op = SetCC.getOperand(0);
20478 // Skip 'zext' or 'trunc' node.
20479 if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20480 Op.getOpcode() == ISD::TRUNCATE)
20481 Op = Op.getOperand(0);
20482 // A special case for rdrand/rdseed, where 0 is set if false cond is
20484 if ((Op.getOpcode() != X86ISD::RDRAND &&
20485 Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20488 // Quit if false value is not the constant 0 or 1.
20489 bool FValIsFalse = true;
20490 if (FVal && FVal->getZExtValue() != 0) {
20491 if (FVal->getZExtValue() != 1)
20493 // If FVal is 1, opposite cond is needed.
20494 needOppositeCond = !needOppositeCond;
20495 FValIsFalse = false;
20497 // Quit if TVal is not the constant opposite of FVal.
20498 if (FValIsFalse && TVal->getZExtValue() != 1)
20500 if (!FValIsFalse && TVal->getZExtValue() != 0)
20502 CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20503 if (needOppositeCond)
20504 CC = X86::GetOppositeBranchCondition(CC);
20505 return SetCC.getOperand(3);
20512 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20513 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20514 TargetLowering::DAGCombinerInfo &DCI,
20515 const X86Subtarget *Subtarget) {
20518 // If the flag operand isn't dead, don't touch this CMOV.
20519 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20522 SDValue FalseOp = N->getOperand(0);
20523 SDValue TrueOp = N->getOperand(1);
20524 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20525 SDValue Cond = N->getOperand(3);
20527 if (CC == X86::COND_E || CC == X86::COND_NE) {
20528 switch (Cond.getOpcode()) {
20532 // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20533 if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20534 return (CC == X86::COND_E) ? FalseOp : TrueOp;
20540 Flags = checkBoolTestSetCCCombine(Cond, CC);
20541 if (Flags.getNode() &&
20542 // Extra check as FCMOV only supports a subset of X86 cond.
20543 (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20544 SDValue Ops[] = { FalseOp, TrueOp,
20545 DAG.getConstant(CC, MVT::i8), Flags };
20546 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20549 // If this is a select between two integer constants, try to do some
20550 // optimizations. Note that the operands are ordered the opposite of SELECT
20552 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20553 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20554 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20555 // larger than FalseC (the false value).
20556 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20557 CC = X86::GetOppositeBranchCondition(CC);
20558 std::swap(TrueC, FalseC);
20559 std::swap(TrueOp, FalseOp);
20562 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
20563 // This is efficient for any integer data type (including i8/i16) and
20565 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20566 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20567 DAG.getConstant(CC, MVT::i8), Cond);
20569 // Zero extend the condition if needed.
20570 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20572 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20573 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20574 DAG.getConstant(ShAmt, MVT::i8));
20575 if (N->getNumValues() == 2) // Dead flag value?
20576 return DCI.CombineTo(N, Cond, SDValue());
20580 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
20581 // for any integer data type, including i8/i16.
20582 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20583 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20584 DAG.getConstant(CC, MVT::i8), Cond);
20586 // Zero extend the condition if needed.
20587 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20588 FalseC->getValueType(0), Cond);
20589 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20590 SDValue(FalseC, 0));
20592 if (N->getNumValues() == 2) // Dead flag value?
20593 return DCI.CombineTo(N, Cond, SDValue());
20597 // Optimize cases that will turn into an LEA instruction. This requires
20598 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20599 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20600 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20601 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20603 bool isFastMultiplier = false;
20605 switch ((unsigned char)Diff) {
20607 case 1: // result = add base, cond
20608 case 2: // result = lea base( , cond*2)
20609 case 3: // result = lea base(cond, cond*2)
20610 case 4: // result = lea base( , cond*4)
20611 case 5: // result = lea base(cond, cond*4)
20612 case 8: // result = lea base( , cond*8)
20613 case 9: // result = lea base(cond, cond*8)
20614 isFastMultiplier = true;
20619 if (isFastMultiplier) {
20620 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20621 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20622 DAG.getConstant(CC, MVT::i8), Cond);
20623 // Zero extend the condition if needed.
20624 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20626 // Scale the condition by the difference.
20628 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20629 DAG.getConstant(Diff, Cond.getValueType()));
20631 // Add the base if non-zero.
20632 if (FalseC->getAPIntValue() != 0)
20633 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20634 SDValue(FalseC, 0));
20635 if (N->getNumValues() == 2) // Dead flag value?
20636 return DCI.CombineTo(N, Cond, SDValue());
20643 // Handle these cases:
20644 // (select (x != c), e, c) -> select (x != c), e, x),
20645 // (select (x == c), c, e) -> select (x == c), x, e)
20646 // where the c is an integer constant, and the "select" is the combination
20647 // of CMOV and CMP.
20649 // The rationale for this change is that the conditional-move from a constant
20650 // needs two instructions, however, conditional-move from a register needs
20651 // only one instruction.
20653 // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20654 // some instruction-combining opportunities. This opt needs to be
20655 // postponed as late as possible.
20657 if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20658 // the DCI.xxxx conditions are provided to postpone the optimization as
20659 // late as possible.
20661 ConstantSDNode *CmpAgainst = nullptr;
20662 if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20663 (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20664 !isa<ConstantSDNode>(Cond.getOperand(0))) {
20666 if (CC == X86::COND_NE &&
20667 CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20668 CC = X86::GetOppositeBranchCondition(CC);
20669 std::swap(TrueOp, FalseOp);
20672 if (CC == X86::COND_E &&
20673 CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20674 SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20675 DAG.getConstant(CC, MVT::i8), Cond };
20676 return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20684 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20685 const X86Subtarget *Subtarget) {
20686 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20688 default: return SDValue();
20689 // SSE/AVX/AVX2 blend intrinsics.
20690 case Intrinsic::x86_avx2_pblendvb:
20691 case Intrinsic::x86_avx2_pblendw:
20692 case Intrinsic::x86_avx2_pblendd_128:
20693 case Intrinsic::x86_avx2_pblendd_256:
20694 // Don't try to simplify this intrinsic if we don't have AVX2.
20695 if (!Subtarget->hasAVX2())
20698 case Intrinsic::x86_avx_blend_pd_256:
20699 case Intrinsic::x86_avx_blend_ps_256:
20700 case Intrinsic::x86_avx_blendv_pd_256:
20701 case Intrinsic::x86_avx_blendv_ps_256:
20702 // Don't try to simplify this intrinsic if we don't have AVX.
20703 if (!Subtarget->hasAVX())
20706 case Intrinsic::x86_sse41_pblendw:
20707 case Intrinsic::x86_sse41_blendpd:
20708 case Intrinsic::x86_sse41_blendps:
20709 case Intrinsic::x86_sse41_blendvps:
20710 case Intrinsic::x86_sse41_blendvpd:
20711 case Intrinsic::x86_sse41_pblendvb: {
20712 SDValue Op0 = N->getOperand(1);
20713 SDValue Op1 = N->getOperand(2);
20714 SDValue Mask = N->getOperand(3);
20716 // Don't try to simplify this intrinsic if we don't have SSE4.1.
20717 if (!Subtarget->hasSSE41())
20720 // fold (blend A, A, Mask) -> A
20723 // fold (blend A, B, allZeros) -> A
20724 if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20726 // fold (blend A, B, allOnes) -> B
20727 if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20730 // Simplify the case where the mask is a constant i32 value.
20731 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20732 if (C->isNullValue())
20734 if (C->isAllOnesValue())
20741 // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20742 case Intrinsic::x86_sse2_psrai_w:
20743 case Intrinsic::x86_sse2_psrai_d:
20744 case Intrinsic::x86_avx2_psrai_w:
20745 case Intrinsic::x86_avx2_psrai_d:
20746 case Intrinsic::x86_sse2_psra_w:
20747 case Intrinsic::x86_sse2_psra_d:
20748 case Intrinsic::x86_avx2_psra_w:
20749 case Intrinsic::x86_avx2_psra_d: {
20750 SDValue Op0 = N->getOperand(1);
20751 SDValue Op1 = N->getOperand(2);
20752 EVT VT = Op0.getValueType();
20753 assert(VT.isVector() && "Expected a vector type!");
20755 if (isa<BuildVectorSDNode>(Op1))
20756 Op1 = Op1.getOperand(0);
20758 if (!isa<ConstantSDNode>(Op1))
20761 EVT SVT = VT.getVectorElementType();
20762 unsigned SVTBits = SVT.getSizeInBits();
20764 ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20765 const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20766 uint64_t ShAmt = C.getZExtValue();
20768 // Don't try to convert this shift into a ISD::SRA if the shift
20769 // count is bigger than or equal to the element size.
20770 if (ShAmt >= SVTBits)
20773 // Trivial case: if the shift count is zero, then fold this
20774 // into the first operand.
20778 // Replace this packed shift intrinsic with a target independent
20780 SDValue Splat = DAG.getConstant(C, VT);
20781 return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20786 /// PerformMulCombine - Optimize a single multiply with constant into two
20787 /// in order to implement it with two cheaper instructions, e.g.
20788 /// LEA + SHL, LEA + LEA.
20789 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20790 TargetLowering::DAGCombinerInfo &DCI) {
20791 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20794 EVT VT = N->getValueType(0);
20795 if (VT != MVT::i64)
20798 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20801 uint64_t MulAmt = C->getZExtValue();
20802 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20805 uint64_t MulAmt1 = 0;
20806 uint64_t MulAmt2 = 0;
20807 if ((MulAmt % 9) == 0) {
20809 MulAmt2 = MulAmt / 9;
20810 } else if ((MulAmt % 5) == 0) {
20812 MulAmt2 = MulAmt / 5;
20813 } else if ((MulAmt % 3) == 0) {
20815 MulAmt2 = MulAmt / 3;
20818 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20821 if (isPowerOf2_64(MulAmt2) &&
20822 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20823 // If second multiplifer is pow2, issue it first. We want the multiply by
20824 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20826 std::swap(MulAmt1, MulAmt2);
20829 if (isPowerOf2_64(MulAmt1))
20830 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20831 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20833 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20834 DAG.getConstant(MulAmt1, VT));
20836 if (isPowerOf2_64(MulAmt2))
20837 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20838 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20840 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20841 DAG.getConstant(MulAmt2, VT));
20843 // Do not add new nodes to DAG combiner worklist.
20844 DCI.CombineTo(N, NewMul, false);
20849 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20850 SDValue N0 = N->getOperand(0);
20851 SDValue N1 = N->getOperand(1);
20852 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20853 EVT VT = N0.getValueType();
20855 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20856 // since the result of setcc_c is all zero's or all ones.
20857 if (VT.isInteger() && !VT.isVector() &&
20858 N1C && N0.getOpcode() == ISD::AND &&
20859 N0.getOperand(1).getOpcode() == ISD::Constant) {
20860 SDValue N00 = N0.getOperand(0);
20861 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20862 ((N00.getOpcode() == ISD::ANY_EXTEND ||
20863 N00.getOpcode() == ISD::ZERO_EXTEND) &&
20864 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20865 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20866 APInt ShAmt = N1C->getAPIntValue();
20867 Mask = Mask.shl(ShAmt);
20869 return DAG.getNode(ISD::AND, SDLoc(N), VT,
20870 N00, DAG.getConstant(Mask, VT));
20874 // Hardware support for vector shifts is sparse which makes us scalarize the
20875 // vector operations in many cases. Also, on sandybridge ADD is faster than
20877 // (shl V, 1) -> add V,V
20878 if (isSplatVector(N1.getNode())) {
20879 assert(N0.getValueType().isVector() && "Invalid vector shift type");
20880 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
20881 // We shift all of the values by one. In many cases we do not have
20882 // hardware support for this operation. This is better expressed as an ADD
20884 if (N1C && (1 == N1C->getZExtValue())) {
20885 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20892 /// \brief Returns a vector of 0s if the node in input is a vector logical
20893 /// shift by a constant amount which is known to be bigger than or equal
20894 /// to the vector element size in bits.
20895 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20896 const X86Subtarget *Subtarget) {
20897 EVT VT = N->getValueType(0);
20899 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20900 (!Subtarget->hasInt256() ||
20901 (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20904 SDValue Amt = N->getOperand(1);
20906 if (isSplatVector(Amt.getNode())) {
20907 SDValue SclrAmt = Amt->getOperand(0);
20908 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
20909 APInt ShiftAmt = C->getAPIntValue();
20910 unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20912 // SSE2/AVX2 logical shifts always return a vector of 0s
20913 // if the shift amount is bigger than or equal to
20914 // the element size. The constant shift amount will be
20915 // encoded as a 8-bit immediate.
20916 if (ShiftAmt.trunc(8).uge(MaxAmount))
20917 return getZeroVector(VT, Subtarget, DAG, DL);
20924 /// PerformShiftCombine - Combine shifts.
20925 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20926 TargetLowering::DAGCombinerInfo &DCI,
20927 const X86Subtarget *Subtarget) {
20928 if (N->getOpcode() == ISD::SHL) {
20929 SDValue V = PerformSHLCombine(N, DAG);
20930 if (V.getNode()) return V;
20933 if (N->getOpcode() != ISD::SRA) {
20934 // Try to fold this logical shift into a zero vector.
20935 SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20936 if (V.getNode()) return V;
20942 // CMPEQCombine - Recognize the distinctive (AND (setcc ...) (setcc ..))
20943 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20944 // and friends. Likewise for OR -> CMPNEQSS.
20945 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20946 TargetLowering::DAGCombinerInfo &DCI,
20947 const X86Subtarget *Subtarget) {
20950 // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20951 // we're requiring SSE2 for both.
20952 if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20953 SDValue N0 = N->getOperand(0);
20954 SDValue N1 = N->getOperand(1);
20955 SDValue CMP0 = N0->getOperand(1);
20956 SDValue CMP1 = N1->getOperand(1);
20959 // The SETCCs should both refer to the same CMP.
20960 if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20963 SDValue CMP00 = CMP0->getOperand(0);
20964 SDValue CMP01 = CMP0->getOperand(1);
20965 EVT VT = CMP00.getValueType();
20967 if (VT == MVT::f32 || VT == MVT::f64) {
20968 bool ExpectingFlags = false;
20969 // Check for any users that want flags:
20970 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20971 !ExpectingFlags && UI != UE; ++UI)
20972 switch (UI->getOpcode()) {
20977 ExpectingFlags = true;
20979 case ISD::CopyToReg:
20980 case ISD::SIGN_EXTEND:
20981 case ISD::ZERO_EXTEND:
20982 case ISD::ANY_EXTEND:
20986 if (!ExpectingFlags) {
20987 enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20988 enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20990 if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20991 X86::CondCode tmp = cc0;
20996 if ((cc0 == X86::COND_E && cc1 == X86::COND_NP) ||
20997 (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20998 // FIXME: need symbolic constants for these magic numbers.
20999 // See X86ATTInstPrinter.cpp:printSSECC().
21000 unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21001 if (Subtarget->hasAVX512()) {
21002 SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21003 CMP01, DAG.getConstant(x86cc, MVT::i8));
21004 if (N->getValueType(0) != MVT::i1)
21005 return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21009 SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21010 CMP00.getValueType(), CMP00, CMP01,
21011 DAG.getConstant(x86cc, MVT::i8));
21013 bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21014 MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21016 if (is64BitFP && !Subtarget->is64Bit()) {
21017 // On a 32-bit target, we cannot bitcast the 64-bit float to a
21018 // 64-bit integer, since that's not a legal type. Since
21019 // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21020 // bits, but can do this little dance to extract the lowest 32 bits
21021 // and work with those going forward.
21022 SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21024 SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21026 OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21027 Vector32, DAG.getIntPtrConstant(0));
21031 SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21032 SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21033 DAG.getConstant(1, IntVT));
21034 SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21035 return OneBitOfTruth;
21043 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21044 /// so it can be folded inside ANDNP.
21045 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21046 EVT VT = N->getValueType(0);
21048 // Match direct AllOnes for 128 and 256-bit vectors
21049 if (ISD::isBuildVectorAllOnes(N))
21052 // Look through a bit convert.
21053 if (N->getOpcode() == ISD::BITCAST)
21054 N = N->getOperand(0).getNode();
21056 // Sometimes the operand may come from a insert_subvector building a 256-bit
21058 if (VT.is256BitVector() &&
21059 N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21060 SDValue V1 = N->getOperand(0);
21061 SDValue V2 = N->getOperand(1);
21063 if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21064 V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21065 ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21066 ISD::isBuildVectorAllOnes(V2.getNode()))
21073 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21074 // register. In most cases we actually compare or select YMM-sized registers
21075 // and mixing the two types creates horrible code. This method optimizes
21076 // some of the transition sequences.
21077 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21078 TargetLowering::DAGCombinerInfo &DCI,
21079 const X86Subtarget *Subtarget) {
21080 EVT VT = N->getValueType(0);
21081 if (!VT.is256BitVector())
21084 assert((N->getOpcode() == ISD::ANY_EXTEND ||
21085 N->getOpcode() == ISD::ZERO_EXTEND ||
21086 N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21088 SDValue Narrow = N->getOperand(0);
21089 EVT NarrowVT = Narrow->getValueType(0);
21090 if (!NarrowVT.is128BitVector())
21093 if (Narrow->getOpcode() != ISD::XOR &&
21094 Narrow->getOpcode() != ISD::AND &&
21095 Narrow->getOpcode() != ISD::OR)
21098 SDValue N0 = Narrow->getOperand(0);
21099 SDValue N1 = Narrow->getOperand(1);
21102 // The Left side has to be a trunc.
21103 if (N0.getOpcode() != ISD::TRUNCATE)
21106 // The type of the truncated inputs.
21107 EVT WideVT = N0->getOperand(0)->getValueType(0);
21111 // The right side has to be a 'trunc' or a constant vector.
21112 bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21113 bool RHSConst = (isSplatVector(N1.getNode()) &&
21114 isa<ConstantSDNode>(N1->getOperand(0)));
21115 if (!RHSTrunc && !RHSConst)
21118 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21120 if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21123 // Set N0 and N1 to hold the inputs to the new wide operation.
21124 N0 = N0->getOperand(0);
21126 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21127 N1->getOperand(0));
21128 SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21129 N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21130 } else if (RHSTrunc) {
21131 N1 = N1->getOperand(0);
21134 // Generate the wide operation.
21135 SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21136 unsigned Opcode = N->getOpcode();
21138 case ISD::ANY_EXTEND:
21140 case ISD::ZERO_EXTEND: {
21141 unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21142 APInt Mask = APInt::getAllOnesValue(InBits);
21143 Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21144 return DAG.getNode(ISD::AND, DL, VT,
21145 Op, DAG.getConstant(Mask, VT));
21147 case ISD::SIGN_EXTEND:
21148 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21149 Op, DAG.getValueType(NarrowVT));
21151 llvm_unreachable("Unexpected opcode");
21155 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21156 TargetLowering::DAGCombinerInfo &DCI,
21157 const X86Subtarget *Subtarget) {
21158 EVT VT = N->getValueType(0);
21159 if (DCI.isBeforeLegalizeOps())
21162 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21166 // Create BEXTR instructions
21167 // BEXTR is ((X >> imm) & (2**size-1))
21168 if (VT == MVT::i32 || VT == MVT::i64) {
21169 SDValue N0 = N->getOperand(0);
21170 SDValue N1 = N->getOperand(1);
21173 // Check for BEXTR.
21174 if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21175 (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21176 ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21177 ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21178 if (MaskNode && ShiftNode) {
21179 uint64_t Mask = MaskNode->getZExtValue();
21180 uint64_t Shift = ShiftNode->getZExtValue();
21181 if (isMask_64(Mask)) {
21182 uint64_t MaskSize = CountPopulation_64(Mask);
21183 if (Shift + MaskSize <= VT.getSizeInBits())
21184 return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21185 DAG.getConstant(Shift | (MaskSize << 8), VT));
21193 // Want to form ANDNP nodes:
21194 // 1) In the hopes of then easily combining them with OR and AND nodes
21195 // to form PBLEND/PSIGN.
21196 // 2) To match ANDN packed intrinsics
21197 if (VT != MVT::v2i64 && VT != MVT::v4i64)
21200 SDValue N0 = N->getOperand(0);
21201 SDValue N1 = N->getOperand(1);
21204 // Check LHS for vnot
21205 if (N0.getOpcode() == ISD::XOR &&
21206 //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21207 CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21208 return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21210 // Check RHS for vnot
21211 if (N1.getOpcode() == ISD::XOR &&
21212 //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21213 CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21214 return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21219 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21220 TargetLowering::DAGCombinerInfo &DCI,
21221 const X86Subtarget *Subtarget) {
21222 if (DCI.isBeforeLegalizeOps())
21225 SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21229 SDValue N0 = N->getOperand(0);
21230 SDValue N1 = N->getOperand(1);
21231 EVT VT = N->getValueType(0);
21233 // look for psign/blend
21234 if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21235 if (!Subtarget->hasSSSE3() ||
21236 (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21239 // Canonicalize pandn to RHS
21240 if (N0.getOpcode() == X86ISD::ANDNP)
21242 // or (and (m, y), (pandn m, x))
21243 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21244 SDValue Mask = N1.getOperand(0);
21245 SDValue X = N1.getOperand(1);
21247 if (N0.getOperand(0) == Mask)
21248 Y = N0.getOperand(1);
21249 if (N0.getOperand(1) == Mask)
21250 Y = N0.getOperand(0);
21252 // Check to see if the mask appeared in both the AND and ANDNP and
21256 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21257 // Look through mask bitcast.
21258 if (Mask.getOpcode() == ISD::BITCAST)
21259 Mask = Mask.getOperand(0);
21260 if (X.getOpcode() == ISD::BITCAST)
21261 X = X.getOperand(0);
21262 if (Y.getOpcode() == ISD::BITCAST)
21263 Y = Y.getOperand(0);
21265 EVT MaskVT = Mask.getValueType();
21267 // Validate that the Mask operand is a vector sra node.
21268 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21269 // there is no psrai.b
21270 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21271 unsigned SraAmt = ~0;
21272 if (Mask.getOpcode() == ISD::SRA) {
21273 SDValue Amt = Mask.getOperand(1);
21274 if (isSplatVector(Amt.getNode())) {
21275 SDValue SclrAmt = Amt->getOperand(0);
21276 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
21277 SraAmt = C->getZExtValue();
21279 } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21280 SDValue SraC = Mask.getOperand(1);
21281 SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
21283 if ((SraAmt + 1) != EltBits)
21288 // Now we know we at least have a plendvb with the mask val. See if
21289 // we can form a psignb/w/d.
21290 // psign = x.type == y.type == mask.type && y = sub(0, x);
21291 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21292 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21293 X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21294 assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21295 "Unsupported VT for PSIGN");
21296 Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21297 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21299 // PBLENDVB only available on SSE 4.1
21300 if (!Subtarget->hasSSE41())
21303 EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21305 X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21306 Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21307 Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21308 Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21309 return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21313 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21316 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21317 MachineFunction &MF = DAG.getMachineFunction();
21318 bool OptForSize = MF.getFunction()->getAttributes().
21319 hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21321 // SHLD/SHRD instructions have lower register pressure, but on some
21322 // platforms they have higher latency than the equivalent
21323 // series of shifts/or that would otherwise be generated.
21324 // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21325 // have higher latencies and we are not optimizing for size.
21326 if (!OptForSize && Subtarget->isSHLDSlow())
21329 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21331 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21333 if (!N0.hasOneUse() || !N1.hasOneUse())
21336 SDValue ShAmt0 = N0.getOperand(1);
21337 if (ShAmt0.getValueType() != MVT::i8)
21339 SDValue ShAmt1 = N1.getOperand(1);
21340 if (ShAmt1.getValueType() != MVT::i8)
21342 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21343 ShAmt0 = ShAmt0.getOperand(0);
21344 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21345 ShAmt1 = ShAmt1.getOperand(0);
21348 unsigned Opc = X86ISD::SHLD;
21349 SDValue Op0 = N0.getOperand(0);
21350 SDValue Op1 = N1.getOperand(0);
21351 if (ShAmt0.getOpcode() == ISD::SUB) {
21352 Opc = X86ISD::SHRD;
21353 std::swap(Op0, Op1);
21354 std::swap(ShAmt0, ShAmt1);
21357 unsigned Bits = VT.getSizeInBits();
21358 if (ShAmt1.getOpcode() == ISD::SUB) {
21359 SDValue Sum = ShAmt1.getOperand(0);
21360 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21361 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21362 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21363 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21364 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21365 return DAG.getNode(Opc, DL, VT,
21367 DAG.getNode(ISD::TRUNCATE, DL,
21370 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21371 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21373 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21374 return DAG.getNode(Opc, DL, VT,
21375 N0.getOperand(0), N1.getOperand(0),
21376 DAG.getNode(ISD::TRUNCATE, DL,
21383 // Generate NEG and CMOV for integer abs.
21384 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21385 EVT VT = N->getValueType(0);
21387 // Since X86 does not have CMOV for 8-bit integer, we don't convert
21388 // 8-bit integer abs to NEG and CMOV.
21389 if (VT.isInteger() && VT.getSizeInBits() == 8)
21392 SDValue N0 = N->getOperand(0);
21393 SDValue N1 = N->getOperand(1);
21396 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21397 // and change it to SUB and CMOV.
21398 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21399 N0.getOpcode() == ISD::ADD &&
21400 N0.getOperand(1) == N1 &&
21401 N1.getOpcode() == ISD::SRA &&
21402 N1.getOperand(0) == N0.getOperand(0))
21403 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21404 if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21405 // Generate SUB & CMOV.
21406 SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21407 DAG.getConstant(0, VT), N0.getOperand(0));
21409 SDValue Ops[] = { N0.getOperand(0), Neg,
21410 DAG.getConstant(X86::COND_GE, MVT::i8),
21411 SDValue(Neg.getNode(), 1) };
21412 return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21417 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21418 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21419 TargetLowering::DAGCombinerInfo &DCI,
21420 const X86Subtarget *Subtarget) {
21421 if (DCI.isBeforeLegalizeOps())
21424 if (Subtarget->hasCMov()) {
21425 SDValue RV = performIntegerAbsCombine(N, DAG);
21433 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21434 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21435 TargetLowering::DAGCombinerInfo &DCI,
21436 const X86Subtarget *Subtarget) {
21437 LoadSDNode *Ld = cast<LoadSDNode>(N);
21438 EVT RegVT = Ld->getValueType(0);
21439 EVT MemVT = Ld->getMemoryVT();
21441 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21442 unsigned RegSz = RegVT.getSizeInBits();
21444 // On Sandybridge unaligned 256bit loads are inefficient.
21445 ISD::LoadExtType Ext = Ld->getExtensionType();
21446 unsigned Alignment = Ld->getAlignment();
21447 bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21448 if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21449 !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21450 unsigned NumElems = RegVT.getVectorNumElements();
21454 SDValue Ptr = Ld->getBasePtr();
21455 SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21457 EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21459 SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21460 Ld->getPointerInfo(), Ld->isVolatile(),
21461 Ld->isNonTemporal(), Ld->isInvariant(),
21463 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21464 SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21465 Ld->getPointerInfo(), Ld->isVolatile(),
21466 Ld->isNonTemporal(), Ld->isInvariant(),
21467 std::min(16U, Alignment));
21468 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21470 Load2.getValue(1));
21472 SDValue NewVec = DAG.getUNDEF(RegVT);
21473 NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21474 NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21475 return DCI.CombineTo(N, NewVec, TF, true);
21478 // If this is a vector EXT Load then attempt to optimize it using a
21479 // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
21480 // expansion is still better than scalar code.
21481 // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
21482 // emit a shuffle and a arithmetic shift.
21483 // TODO: It is possible to support ZExt by zeroing the undef values
21484 // during the shuffle phase or after the shuffle.
21485 if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
21486 (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
21487 assert(MemVT != RegVT && "Cannot extend to the same type");
21488 assert(MemVT.isVector() && "Must load a vector from memory");
21490 unsigned NumElems = RegVT.getVectorNumElements();
21491 unsigned MemSz = MemVT.getSizeInBits();
21492 assert(RegSz > MemSz && "Register size must be greater than the mem size");
21494 if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
21497 // All sizes must be a power of two.
21498 if (!isPowerOf2_32(RegSz * MemSz * NumElems))
21501 // Attempt to load the original value using scalar loads.
21502 // Find the largest scalar type that divides the total loaded size.
21503 MVT SclrLoadTy = MVT::i8;
21504 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21505 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21506 MVT Tp = (MVT::SimpleValueType)tp;
21507 if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
21512 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21513 if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
21515 SclrLoadTy = MVT::f64;
21517 // Calculate the number of scalar loads that we need to perform
21518 // in order to load our vector from memory.
21519 unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
21520 if (Ext == ISD::SEXTLOAD && NumLoads > 1)
21523 unsigned loadRegZize = RegSz;
21524 if (Ext == ISD::SEXTLOAD && RegSz == 256)
21527 // Represent our vector as a sequence of elements which are the
21528 // largest scalar that we can load.
21529 EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
21530 loadRegZize/SclrLoadTy.getSizeInBits());
21532 // Represent the data using the same element type that is stored in
21533 // memory. In practice, we ''widen'' MemVT.
21535 EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21536 loadRegZize/MemVT.getScalarType().getSizeInBits());
21538 assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
21539 "Invalid vector type");
21541 // We can't shuffle using an illegal type.
21542 if (!TLI.isTypeLegal(WideVecVT))
21545 SmallVector<SDValue, 8> Chains;
21546 SDValue Ptr = Ld->getBasePtr();
21547 SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
21548 TLI.getPointerTy());
21549 SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
21551 for (unsigned i = 0; i < NumLoads; ++i) {
21552 // Perform a single load.
21553 SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
21554 Ptr, Ld->getPointerInfo(),
21555 Ld->isVolatile(), Ld->isNonTemporal(),
21556 Ld->isInvariant(), Ld->getAlignment());
21557 Chains.push_back(ScalarLoad.getValue(1));
21558 // Create the first element type using SCALAR_TO_VECTOR in order to avoid
21559 // another round of DAGCombining.
21561 Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
21563 Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
21564 ScalarLoad, DAG.getIntPtrConstant(i));
21566 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21569 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21571 // Bitcast the loaded value to a vector of the original element type, in
21572 // the size of the target vector type.
21573 SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
21574 unsigned SizeRatio = RegSz/MemSz;
21576 if (Ext == ISD::SEXTLOAD) {
21577 // If we have SSE4.1 we can directly emit a VSEXT node.
21578 if (Subtarget->hasSSE41()) {
21579 SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
21580 return DCI.CombineTo(N, Sext, TF, true);
21583 // Otherwise we'll shuffle the small elements in the high bits of the
21584 // larger type and perform an arithmetic shift. If the shift is not legal
21585 // it's better to scalarize.
21586 if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
21589 // Redistribute the loaded elements into the different locations.
21590 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21591 for (unsigned i = 0; i != NumElems; ++i)
21592 ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
21594 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21595 DAG.getUNDEF(WideVecVT),
21598 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
21600 // Build the arithmetic shift.
21601 unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
21602 MemVT.getVectorElementType().getSizeInBits();
21603 Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
21604 DAG.getConstant(Amt, RegVT));
21606 return DCI.CombineTo(N, Shuff, TF, true);
21609 // Redistribute the loaded elements into the different locations.
21610 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21611 for (unsigned i = 0; i != NumElems; ++i)
21612 ShuffleVec[i*SizeRatio] = i;
21614 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
21615 DAG.getUNDEF(WideVecVT),
21618 // Bitcast to the requested type.
21619 Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
21620 // Replace the original load with the new sequence
21621 // and return the new chain.
21622 return DCI.CombineTo(N, Shuff, TF, true);
21628 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21629 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21630 const X86Subtarget *Subtarget) {
21631 StoreSDNode *St = cast<StoreSDNode>(N);
21632 EVT VT = St->getValue().getValueType();
21633 EVT StVT = St->getMemoryVT();
21635 SDValue StoredVal = St->getOperand(1);
21636 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21638 // If we are saving a concatenation of two XMM registers, perform two stores.
21639 // On Sandy Bridge, 256-bit memory operations are executed by two
21640 // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21641 // memory operation.
21642 unsigned Alignment = St->getAlignment();
21643 bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21644 if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21645 StVT == VT && !IsAligned) {
21646 unsigned NumElems = VT.getVectorNumElements();
21650 SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21651 SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21653 SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21654 SDValue Ptr0 = St->getBasePtr();
21655 SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21657 SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21658 St->getPointerInfo(), St->isVolatile(),
21659 St->isNonTemporal(), Alignment);
21660 SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21661 St->getPointerInfo(), St->isVolatile(),
21662 St->isNonTemporal(),
21663 std::min(16U, Alignment));
21664 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21667 // Optimize trunc store (of multiple scalars) to shuffle and store.
21668 // First, pack all of the elements in one place. Next, store to memory
21669 // in fewer chunks.
21670 if (St->isTruncatingStore() && VT.isVector()) {
21671 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21672 unsigned NumElems = VT.getVectorNumElements();
21673 assert(StVT != VT && "Cannot truncate to the same type");
21674 unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21675 unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21677 // From, To sizes and ElemCount must be pow of two
21678 if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21679 // We are going to use the original vector elt for storing.
21680 // Accumulated smaller vector elements must be a multiple of the store size.
21681 if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21683 unsigned SizeRatio = FromSz / ToSz;
21685 assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21687 // Create a type on which we perform the shuffle
21688 EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21689 StVT.getScalarType(), NumElems*SizeRatio);
21691 assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21693 SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21694 SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21695 for (unsigned i = 0; i != NumElems; ++i)
21696 ShuffleVec[i] = i * SizeRatio;
21698 // Can't shuffle using an illegal type.
21699 if (!TLI.isTypeLegal(WideVecVT))
21702 SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21703 DAG.getUNDEF(WideVecVT),
21705 // At this point all of the data is stored at the bottom of the
21706 // register. We now need to save it to mem.
21708 // Find the largest store unit
21709 MVT StoreType = MVT::i8;
21710 for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21711 tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21712 MVT Tp = (MVT::SimpleValueType)tp;
21713 if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21717 // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21718 if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21719 (64 <= NumElems * ToSz))
21720 StoreType = MVT::f64;
21722 // Bitcast the original vector into a vector of store-size units
21723 EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21724 StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21725 assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21726 SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21727 SmallVector<SDValue, 8> Chains;
21728 SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21729 TLI.getPointerTy());
21730 SDValue Ptr = St->getBasePtr();
21732 // Perform one or more big stores into memory.
21733 for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21734 SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21735 StoreType, ShuffWide,
21736 DAG.getIntPtrConstant(i));
21737 SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21738 St->getPointerInfo(), St->isVolatile(),
21739 St->isNonTemporal(), St->getAlignment());
21740 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21741 Chains.push_back(Ch);
21744 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21747 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
21748 // the FP state in cases where an emms may be missing.
21749 // A preferable solution to the general problem is to figure out the right
21750 // places to insert EMMS. This qualifies as a quick hack.
21752 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21753 if (VT.getSizeInBits() != 64)
21756 const Function *F = DAG.getMachineFunction().getFunction();
21757 bool NoImplicitFloatOps = F->getAttributes().
21758 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21759 bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21760 && Subtarget->hasSSE2();
21761 if ((VT.isVector() ||
21762 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21763 isa<LoadSDNode>(St->getValue()) &&
21764 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21765 St->getChain().hasOneUse() && !St->isVolatile()) {
21766 SDNode* LdVal = St->getValue().getNode();
21767 LoadSDNode *Ld = nullptr;
21768 int TokenFactorIndex = -1;
21769 SmallVector<SDValue, 8> Ops;
21770 SDNode* ChainVal = St->getChain().getNode();
21771 // Must be a store of a load. We currently handle two cases: the load
21772 // is a direct child, and it's under an intervening TokenFactor. It is
21773 // possible to dig deeper under nested TokenFactors.
21774 if (ChainVal == LdVal)
21775 Ld = cast<LoadSDNode>(St->getChain());
21776 else if (St->getValue().hasOneUse() &&
21777 ChainVal->getOpcode() == ISD::TokenFactor) {
21778 for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21779 if (ChainVal->getOperand(i).getNode() == LdVal) {
21780 TokenFactorIndex = i;
21781 Ld = cast<LoadSDNode>(St->getValue());
21783 Ops.push_back(ChainVal->getOperand(i));
21787 if (!Ld || !ISD::isNormalLoad(Ld))
21790 // If this is not the MMX case, i.e. we are just turning i64 load/store
21791 // into f64 load/store, avoid the transformation if there are multiple
21792 // uses of the loaded value.
21793 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21798 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21799 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21801 if (Subtarget->is64Bit() || F64IsLegal) {
21802 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21803 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21804 Ld->getPointerInfo(), Ld->isVolatile(),
21805 Ld->isNonTemporal(), Ld->isInvariant(),
21806 Ld->getAlignment());
21807 SDValue NewChain = NewLd.getValue(1);
21808 if (TokenFactorIndex != -1) {
21809 Ops.push_back(NewChain);
21810 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21812 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21813 St->getPointerInfo(),
21814 St->isVolatile(), St->isNonTemporal(),
21815 St->getAlignment());
21818 // Otherwise, lower to two pairs of 32-bit loads / stores.
21819 SDValue LoAddr = Ld->getBasePtr();
21820 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21821 DAG.getConstant(4, MVT::i32));
21823 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21824 Ld->getPointerInfo(),
21825 Ld->isVolatile(), Ld->isNonTemporal(),
21826 Ld->isInvariant(), Ld->getAlignment());
21827 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21828 Ld->getPointerInfo().getWithOffset(4),
21829 Ld->isVolatile(), Ld->isNonTemporal(),
21831 MinAlign(Ld->getAlignment(), 4));
21833 SDValue NewChain = LoLd.getValue(1);
21834 if (TokenFactorIndex != -1) {
21835 Ops.push_back(LoLd);
21836 Ops.push_back(HiLd);
21837 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21840 LoAddr = St->getBasePtr();
21841 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21842 DAG.getConstant(4, MVT::i32));
21844 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21845 St->getPointerInfo(),
21846 St->isVolatile(), St->isNonTemporal(),
21847 St->getAlignment());
21848 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21849 St->getPointerInfo().getWithOffset(4),
21851 St->isNonTemporal(),
21852 MinAlign(St->getAlignment(), 4));
21853 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21858 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21859 /// and return the operands for the horizontal operation in LHS and RHS. A
21860 /// horizontal operation performs the binary operation on successive elements
21861 /// of its first operand, then on successive elements of its second operand,
21862 /// returning the resulting values in a vector. For example, if
21863 /// A = < float a0, float a1, float a2, float a3 >
21865 /// B = < float b0, float b1, float b2, float b3 >
21866 /// then the result of doing a horizontal operation on A and B is
21867 /// A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21868 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21869 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21870 /// set to A, RHS to B, and the routine returns 'true'.
21871 /// Note that the binary operation should have the property that if one of the
21872 /// operands is UNDEF then the result is UNDEF.
21873 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21874 // Look for the following pattern: if
21875 // A = < float a0, float a1, float a2, float a3 >
21876 // B = < float b0, float b1, float b2, float b3 >
21878 // LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21879 // RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21880 // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21881 // which is A horizontal-op B.
21883 // At least one of the operands should be a vector shuffle.
21884 if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21885 RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21888 MVT VT = LHS.getSimpleValueType();
21890 assert((VT.is128BitVector() || VT.is256BitVector()) &&
21891 "Unsupported vector type for horizontal add/sub");
21893 // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21894 // operate independently on 128-bit lanes.
21895 unsigned NumElts = VT.getVectorNumElements();
21896 unsigned NumLanes = VT.getSizeInBits()/128;
21897 unsigned NumLaneElts = NumElts / NumLanes;
21898 assert((NumLaneElts % 2 == 0) &&
21899 "Vector type should have an even number of elements in each lane");
21900 unsigned HalfLaneElts = NumLaneElts/2;
21902 // View LHS in the form
21903 // LHS = VECTOR_SHUFFLE A, B, LMask
21904 // If LHS is not a shuffle then pretend it is the shuffle
21905 // LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21906 // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21909 SmallVector<int, 16> LMask(NumElts);
21910 if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21911 if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21912 A = LHS.getOperand(0);
21913 if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21914 B = LHS.getOperand(1);
21915 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21916 std::copy(Mask.begin(), Mask.end(), LMask.begin());
21918 if (LHS.getOpcode() != ISD::UNDEF)
21920 for (unsigned i = 0; i != NumElts; ++i)
21924 // Likewise, view RHS in the form
21925 // RHS = VECTOR_SHUFFLE C, D, RMask
21927 SmallVector<int, 16> RMask(NumElts);
21928 if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21929 if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21930 C = RHS.getOperand(0);
21931 if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21932 D = RHS.getOperand(1);
21933 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21934 std::copy(Mask.begin(), Mask.end(), RMask.begin());
21936 if (RHS.getOpcode() != ISD::UNDEF)
21938 for (unsigned i = 0; i != NumElts; ++i)
21942 // Check that the shuffles are both shuffling the same vectors.
21943 if (!(A == C && B == D) && !(A == D && B == C))
21946 // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21947 if (!A.getNode() && !B.getNode())
21950 // If A and B occur in reverse order in RHS, then "swap" them (which means
21951 // rewriting the mask).
21953 CommuteVectorShuffleMask(RMask, NumElts);
21955 // At this point LHS and RHS are equivalent to
21956 // LHS = VECTOR_SHUFFLE A, B, LMask
21957 // RHS = VECTOR_SHUFFLE A, B, RMask
21958 // Check that the masks correspond to performing a horizontal operation.
21959 for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21960 for (unsigned i = 0; i != NumLaneElts; ++i) {
21961 int LIdx = LMask[i+l], RIdx = RMask[i+l];
21963 // Ignore any UNDEF components.
21964 if (LIdx < 0 || RIdx < 0 ||
21965 (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21966 (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21969 // Check that successive elements are being operated on. If not, this is
21970 // not a horizontal operation.
21971 unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21972 int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21973 if (!(LIdx == Index && RIdx == Index + 1) &&
21974 !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21979 LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21980 RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21984 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21985 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21986 const X86Subtarget *Subtarget) {
21987 EVT VT = N->getValueType(0);
21988 SDValue LHS = N->getOperand(0);
21989 SDValue RHS = N->getOperand(1);
21991 // Try to synthesize horizontal adds from adds of shuffles.
21992 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21993 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21994 isHorizontalBinOp(LHS, RHS, true))
21995 return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21999 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22000 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22001 const X86Subtarget *Subtarget) {
22002 EVT VT = N->getValueType(0);
22003 SDValue LHS = N->getOperand(0);
22004 SDValue RHS = N->getOperand(1);
22006 // Try to synthesize horizontal subs from subs of shuffles.
22007 if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22008 (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22009 isHorizontalBinOp(LHS, RHS, false))
22010 return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22014 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22015 /// X86ISD::FXOR nodes.
22016 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22017 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22018 // F[X]OR(0.0, x) -> x
22019 // F[X]OR(x, 0.0) -> x
22020 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22021 if (C->getValueAPF().isPosZero())
22022 return N->getOperand(1);
22023 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22024 if (C->getValueAPF().isPosZero())
22025 return N->getOperand(0);
22029 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22030 /// X86ISD::FMAX nodes.
22031 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22032 assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22034 // Only perform optimizations if UnsafeMath is used.
22035 if (!DAG.getTarget().Options.UnsafeFPMath)
22038 // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22039 // into FMINC and FMAXC, which are Commutative operations.
22040 unsigned NewOp = 0;
22041 switch (N->getOpcode()) {
22042 default: llvm_unreachable("unknown opcode");
22043 case X86ISD::FMIN: NewOp = X86ISD::FMINC; break;
22044 case X86ISD::FMAX: NewOp = X86ISD::FMAXC; break;
22047 return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22048 N->getOperand(0), N->getOperand(1));
22051 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22052 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22053 // FAND(0.0, x) -> 0.0
22054 // FAND(x, 0.0) -> 0.0
22055 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22056 if (C->getValueAPF().isPosZero())
22057 return N->getOperand(0);
22058 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22059 if (C->getValueAPF().isPosZero())
22060 return N->getOperand(1);
22064 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22065 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22066 // FANDN(x, 0.0) -> 0.0
22067 // FANDN(0.0, x) -> x
22068 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22069 if (C->getValueAPF().isPosZero())
22070 return N->getOperand(1);
22071 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22072 if (C->getValueAPF().isPosZero())
22073 return N->getOperand(1);
22077 static SDValue PerformBTCombine(SDNode *N,
22079 TargetLowering::DAGCombinerInfo &DCI) {
22080 // BT ignores high bits in the bit index operand.
22081 SDValue Op1 = N->getOperand(1);
22082 if (Op1.hasOneUse()) {
22083 unsigned BitWidth = Op1.getValueSizeInBits();
22084 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22085 APInt KnownZero, KnownOne;
22086 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22087 !DCI.isBeforeLegalizeOps());
22088 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22089 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22090 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22091 DCI.CommitTargetLoweringOpt(TLO);
22096 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22097 SDValue Op = N->getOperand(0);
22098 if (Op.getOpcode() == ISD::BITCAST)
22099 Op = Op.getOperand(0);
22100 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22101 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22102 VT.getVectorElementType().getSizeInBits() ==
22103 OpVT.getVectorElementType().getSizeInBits()) {
22104 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22109 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22110 const X86Subtarget *Subtarget) {
22111 EVT VT = N->getValueType(0);
22112 if (!VT.isVector())
22115 SDValue N0 = N->getOperand(0);
22116 SDValue N1 = N->getOperand(1);
22117 EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22120 // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22121 // both SSE and AVX2 since there is no sign-extended shift right
22122 // operation on a vector with 64-bit elements.
22123 //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22124 // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22125 if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22126 N0.getOpcode() == ISD::SIGN_EXTEND)) {
22127 SDValue N00 = N0.getOperand(0);
22129 // EXTLOAD has a better solution on AVX2,
22130 // it may be replaced with X86ISD::VSEXT node.
22131 if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22132 if (!ISD::isNormalLoad(N00.getNode()))
22135 if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22136 SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22138 return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22144 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22145 TargetLowering::DAGCombinerInfo &DCI,
22146 const X86Subtarget *Subtarget) {
22147 if (!DCI.isBeforeLegalizeOps())
22150 if (!Subtarget->hasFp256())
22153 EVT VT = N->getValueType(0);
22154 if (VT.isVector() && VT.getSizeInBits() == 256) {
22155 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22163 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22164 const X86Subtarget* Subtarget) {
22166 EVT VT = N->getValueType(0);
22168 // Let legalize expand this if it isn't a legal type yet.
22169 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22172 EVT ScalarVT = VT.getScalarType();
22173 if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22174 (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22177 SDValue A = N->getOperand(0);
22178 SDValue B = N->getOperand(1);
22179 SDValue C = N->getOperand(2);
22181 bool NegA = (A.getOpcode() == ISD::FNEG);
22182 bool NegB = (B.getOpcode() == ISD::FNEG);
22183 bool NegC = (C.getOpcode() == ISD::FNEG);
22185 // Negative multiplication when NegA xor NegB
22186 bool NegMul = (NegA != NegB);
22188 A = A.getOperand(0);
22190 B = B.getOperand(0);
22192 C = C.getOperand(0);
22196 Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22198 Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22200 return DAG.getNode(Opcode, dl, VT, A, B, C);
22203 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22204 TargetLowering::DAGCombinerInfo &DCI,
22205 const X86Subtarget *Subtarget) {
22206 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
22207 // (and (i32 x86isd::setcc_carry), 1)
22208 // This eliminates the zext. This transformation is necessary because
22209 // ISD::SETCC is always legalized to i8.
22211 SDValue N0 = N->getOperand(0);
22212 EVT VT = N->getValueType(0);
22214 if (N0.getOpcode() == ISD::AND &&
22216 N0.getOperand(0).hasOneUse()) {
22217 SDValue N00 = N0.getOperand(0);
22218 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22219 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22220 if (!C || C->getZExtValue() != 1)
22222 return DAG.getNode(ISD::AND, dl, VT,
22223 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22224 N00.getOperand(0), N00.getOperand(1)),
22225 DAG.getConstant(1, VT));
22229 if (N0.getOpcode() == ISD::TRUNCATE &&
22231 N0.getOperand(0).hasOneUse()) {
22232 SDValue N00 = N0.getOperand(0);
22233 if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22234 return DAG.getNode(ISD::AND, dl, VT,
22235 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22236 N00.getOperand(0), N00.getOperand(1)),
22237 DAG.getConstant(1, VT));
22240 if (VT.is256BitVector()) {
22241 SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22249 // Optimize x == -y --> x+y == 0
22250 // x != -y --> x+y != 0
22251 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22252 const X86Subtarget* Subtarget) {
22253 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22254 SDValue LHS = N->getOperand(0);
22255 SDValue RHS = N->getOperand(1);
22256 EVT VT = N->getValueType(0);
22259 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22260 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22261 if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22262 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22263 LHS.getValueType(), RHS, LHS.getOperand(1));
22264 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22265 addV, DAG.getConstant(0, addV.getValueType()), CC);
22267 if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22268 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22269 if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22270 SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22271 RHS.getValueType(), LHS, RHS.getOperand(1));
22272 return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22273 addV, DAG.getConstant(0, addV.getValueType()), CC);
22276 if (VT.getScalarType() == MVT::i1) {
22277 bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22278 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22279 bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22280 if (!IsSEXT0 && !IsVZero0)
22282 bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22283 (RHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
22284 bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22286 if (!IsSEXT1 && !IsVZero1)
22289 if (IsSEXT0 && IsVZero1) {
22290 assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22291 if (CC == ISD::SETEQ)
22292 return DAG.getNOT(DL, LHS.getOperand(0), VT);
22293 return LHS.getOperand(0);
22295 if (IsSEXT1 && IsVZero0) {
22296 assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22297 if (CC == ISD::SETEQ)
22298 return DAG.getNOT(DL, RHS.getOperand(0), VT);
22299 return RHS.getOperand(0);
22306 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22307 const X86Subtarget *Subtarget) {
22309 MVT VT = N->getOperand(1)->getSimpleValueType(0);
22310 assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22311 "X86insertps is only defined for v4x32");
22313 SDValue Ld = N->getOperand(1);
22314 if (MayFoldLoad(Ld)) {
22315 // Extract the countS bits from the immediate so we can get the proper
22316 // address when narrowing the vector load to a specific element.
22317 // When the second source op is a memory address, interps doesn't use
22318 // countS and just gets an f32 from that address.
22319 unsigned DestIndex =
22320 cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22321 Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22325 // Create this as a scalar to vector to match the instruction pattern.
22326 SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22327 // countS bits are ignored when loading from memory on insertps, which
22328 // means we don't need to explicitly set them to 0.
22329 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22330 LoadScalarToVector, N->getOperand(2));
22333 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22334 // as "sbb reg,reg", since it can be extended without zext and produces
22335 // an all-ones bit which is more useful than 0/1 in some cases.
22336 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22339 return DAG.getNode(ISD::AND, DL, VT,
22340 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22341 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22342 DAG.getConstant(1, VT));
22343 assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22344 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22345 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22346 DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22349 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22350 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22351 TargetLowering::DAGCombinerInfo &DCI,
22352 const X86Subtarget *Subtarget) {
22354 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22355 SDValue EFLAGS = N->getOperand(1);
22357 if (CC == X86::COND_A) {
22358 // Try to convert COND_A into COND_B in an attempt to facilitate
22359 // materializing "setb reg".
22361 // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22362 // cannot take an immediate as its first operand.
22364 if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22365 EFLAGS.getValueType().isInteger() &&
22366 !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22367 SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22368 EFLAGS.getNode()->getVTList(),
22369 EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22370 SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22371 return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22375 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22376 // a zext and produces an all-ones bit which is more useful than 0/1 in some
22378 if (CC == X86::COND_B)
22379 return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22383 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22384 if (Flags.getNode()) {
22385 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22386 return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22392 // Optimize branch condition evaluation.
22394 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22395 TargetLowering::DAGCombinerInfo &DCI,
22396 const X86Subtarget *Subtarget) {
22398 SDValue Chain = N->getOperand(0);
22399 SDValue Dest = N->getOperand(1);
22400 SDValue EFLAGS = N->getOperand(3);
22401 X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22405 Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22406 if (Flags.getNode()) {
22407 SDValue Cond = DAG.getConstant(CC, MVT::i8);
22408 return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22415 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22416 const X86TargetLowering *XTLI) {
22417 SDValue Op0 = N->getOperand(0);
22418 EVT InVT = Op0->getValueType(0);
22420 // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22421 if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22423 MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22424 SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22425 return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22428 // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22429 // a 32-bit target where SSE doesn't support i64->FP operations.
22430 if (Op0.getOpcode() == ISD::LOAD) {
22431 LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22432 EVT VT = Ld->getValueType(0);
22433 if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22434 ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22435 !XTLI->getSubtarget()->is64Bit() &&
22437 SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22438 Ld->getChain(), Op0, DAG);
22439 DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22446 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22447 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22448 X86TargetLowering::DAGCombinerInfo &DCI) {
22449 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22450 // the result is either zero or one (depending on the input carry bit).
22451 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22452 if (X86::isZeroNode(N->getOperand(0)) &&
22453 X86::isZeroNode(N->getOperand(1)) &&
22454 // We don't have a good way to replace an EFLAGS use, so only do this when
22456 SDValue(N, 1).use_empty()) {
22458 EVT VT = N->getValueType(0);
22459 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22460 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22461 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22462 DAG.getConstant(X86::COND_B,MVT::i8),
22464 DAG.getConstant(1, VT));
22465 return DCI.CombineTo(N, Res1, CarryOut);
22471 // fold (add Y, (sete X, 0)) -> adc 0, Y
22472 // (add Y, (setne X, 0)) -> sbb -1, Y
22473 // (sub (sete X, 0), Y) -> sbb 0, Y
22474 // (sub (setne X, 0), Y) -> adc -1, Y
22475 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22478 // Look through ZExts.
22479 SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22480 if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22483 SDValue SetCC = Ext.getOperand(0);
22484 if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22487 X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22488 if (CC != X86::COND_E && CC != X86::COND_NE)
22491 SDValue Cmp = SetCC.getOperand(1);
22492 if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22493 !X86::isZeroNode(Cmp.getOperand(1)) ||
22494 !Cmp.getOperand(0).getValueType().isInteger())
22497 SDValue CmpOp0 = Cmp.getOperand(0);
22498 SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22499 DAG.getConstant(1, CmpOp0.getValueType()));
22501 SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22502 if (CC == X86::COND_NE)
22503 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22504 DL, OtherVal.getValueType(), OtherVal,
22505 DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22506 return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22507 DL, OtherVal.getValueType(), OtherVal,
22508 DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22511 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22512 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22513 const X86Subtarget *Subtarget) {
22514 EVT VT = N->getValueType(0);
22515 SDValue Op0 = N->getOperand(0);
22516 SDValue Op1 = N->getOperand(1);
22518 // Try to synthesize horizontal adds from adds of shuffles.
22519 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22520 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22521 isHorizontalBinOp(Op0, Op1, true))
22522 return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22524 return OptimizeConditionalInDecrement(N, DAG);
22527 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22528 const X86Subtarget *Subtarget) {
22529 SDValue Op0 = N->getOperand(0);
22530 SDValue Op1 = N->getOperand(1);
22532 // X86 can't encode an immediate LHS of a sub. See if we can push the
22533 // negation into a preceding instruction.
22534 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22535 // If the RHS of the sub is a XOR with one use and a constant, invert the
22536 // immediate. Then add one to the LHS of the sub so we can turn
22537 // X-Y -> X+~Y+1, saving one register.
22538 if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22539 isa<ConstantSDNode>(Op1.getOperand(1))) {
22540 APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22541 EVT VT = Op0.getValueType();
22542 SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22544 DAG.getConstant(~XorC, VT));
22545 return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22546 DAG.getConstant(C->getAPIntValue()+1, VT));
22550 // Try to synthesize horizontal adds from adds of shuffles.
22551 EVT VT = N->getValueType(0);
22552 if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22553 (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22554 isHorizontalBinOp(Op0, Op1, true))
22555 return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22557 return OptimizeConditionalInDecrement(N, DAG);
22560 /// performVZEXTCombine - Performs build vector combines
22561 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22562 TargetLowering::DAGCombinerInfo &DCI,
22563 const X86Subtarget *Subtarget) {
22564 // (vzext (bitcast (vzext (x)) -> (vzext x)
22565 SDValue In = N->getOperand(0);
22566 while (In.getOpcode() == ISD::BITCAST)
22567 In = In.getOperand(0);
22569 if (In.getOpcode() != X86ISD::VZEXT)
22572 return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22576 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22577 DAGCombinerInfo &DCI) const {
22578 SelectionDAG &DAG = DCI.DAG;
22579 switch (N->getOpcode()) {
22581 case ISD::EXTRACT_VECTOR_ELT:
22582 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22584 case ISD::SELECT: return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22585 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22586 case ISD::ADD: return PerformAddCombine(N, DAG, Subtarget);
22587 case ISD::SUB: return PerformSubCombine(N, DAG, Subtarget);
22588 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
22589 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
22592 case ISD::SRL: return PerformShiftCombine(N, DAG, DCI, Subtarget);
22593 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
22594 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
22595 case ISD::XOR: return PerformXorCombine(N, DAG, DCI, Subtarget);
22596 case ISD::LOAD: return PerformLOADCombine(N, DAG, DCI, Subtarget);
22597 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
22598 case ISD::SINT_TO_FP: return PerformSINT_TO_FPCombine(N, DAG, this);
22599 case ISD::FADD: return PerformFADDCombine(N, DAG, Subtarget);
22600 case ISD::FSUB: return PerformFSUBCombine(N, DAG, Subtarget);
22602 case X86ISD::FOR: return PerformFORCombine(N, DAG);
22604 case X86ISD::FMAX: return PerformFMinFMaxCombine(N, DAG);
22605 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
22606 case X86ISD::FANDN: return PerformFANDNCombine(N, DAG);
22607 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
22608 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
22609 case ISD::ANY_EXTEND:
22610 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG, DCI, Subtarget);
22611 case ISD::SIGN_EXTEND: return PerformSExtCombine(N, DAG, DCI, Subtarget);
22612 case ISD::SIGN_EXTEND_INREG:
22613 return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22614 case ISD::TRUNCATE: return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22615 case ISD::SETCC: return PerformISDSETCCCombine(N, DAG, Subtarget);
22616 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22617 case X86ISD::BRCOND: return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22618 case X86ISD::VZEXT: return performVZEXTCombine(N, DAG, DCI, Subtarget);
22619 case X86ISD::SHUFP: // Handle all target specific shuffles
22620 case X86ISD::PALIGNR:
22621 case X86ISD::UNPCKH:
22622 case X86ISD::UNPCKL:
22623 case X86ISD::MOVHLPS:
22624 case X86ISD::MOVLHPS:
22625 case X86ISD::PSHUFD:
22626 case X86ISD::PSHUFHW:
22627 case X86ISD::PSHUFLW:
22628 case X86ISD::MOVSS:
22629 case X86ISD::MOVSD:
22630 case X86ISD::VPERMILP:
22631 case X86ISD::VPERM2X128:
22632 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22633 case ISD::FMA: return PerformFMACombine(N, DAG, Subtarget);
22634 case ISD::INTRINSIC_WO_CHAIN:
22635 return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22636 case X86ISD::INSERTPS:
22637 return PerformINSERTPSCombine(N, DAG, Subtarget);
22638 case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22644 /// isTypeDesirableForOp - Return true if the target has native support for
22645 /// the specified value type and it is 'desirable' to use the type for the
22646 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22647 /// instruction encodings are longer and some i16 instructions are slow.
22648 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22649 if (!isTypeLegal(VT))
22651 if (VT != MVT::i16)
22658 case ISD::SIGN_EXTEND:
22659 case ISD::ZERO_EXTEND:
22660 case ISD::ANY_EXTEND:
22673 /// IsDesirableToPromoteOp - This method query the target whether it is
22674 /// beneficial for dag combiner to promote the specified node. If true, it
22675 /// should return the desired promotion type by reference.
22676 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22677 EVT VT = Op.getValueType();
22678 if (VT != MVT::i16)
22681 bool Promote = false;
22682 bool Commute = false;
22683 switch (Op.getOpcode()) {
22686 LoadSDNode *LD = cast<LoadSDNode>(Op);
22687 // If the non-extending load has a single use and it's not live out, then it
22688 // might be folded.
22689 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22690 Op.hasOneUse()*/) {
22691 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22692 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22693 // The only case where we'd want to promote LOAD (rather then it being
22694 // promoted as an operand is when it's only use is liveout.
22695 if (UI->getOpcode() != ISD::CopyToReg)
22702 case ISD::SIGN_EXTEND:
22703 case ISD::ZERO_EXTEND:
22704 case ISD::ANY_EXTEND:
22709 SDValue N0 = Op.getOperand(0);
22710 // Look out for (store (shl (load), x)).
22711 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22724 SDValue N0 = Op.getOperand(0);
22725 SDValue N1 = Op.getOperand(1);
22726 if (!Commute && MayFoldLoad(N1))
22728 // Avoid disabling potential load folding opportunities.
22729 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22731 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22741 //===----------------------------------------------------------------------===//
22742 // X86 Inline Assembly Support
22743 //===----------------------------------------------------------------------===//
22746 // Helper to match a string separated by whitespace.
22747 bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22748 s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22750 for (unsigned i = 0, e = args.size(); i != e; ++i) {
22751 StringRef piece(*args[i]);
22752 if (!s.startswith(piece)) // Check if the piece matches.
22755 s = s.substr(piece.size());
22756 StringRef::size_type pos = s.find_first_not_of(" \t");
22757 if (pos == 0) // We matched a prefix.
22765 const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22768 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22770 if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22771 if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22772 std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22773 std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22775 if (AsmPieces.size() == 3)
22777 else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22784 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22785 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22787 std::string AsmStr = IA->getAsmString();
22789 IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22790 if (!Ty || Ty->getBitWidth() % 16 != 0)
22793 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22794 SmallVector<StringRef, 4> AsmPieces;
22795 SplitString(AsmStr, AsmPieces, ";\n");
22797 switch (AsmPieces.size()) {
22798 default: return false;
22800 // FIXME: this should verify that we are targeting a 486 or better. If not,
22801 // we will turn this bswap into something that will be lowered to logical
22802 // ops instead of emitting the bswap asm. For now, we don't support 486 or
22803 // lower so don't worry about this.
22805 if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22806 matchAsm(AsmPieces[0], "bswapl", "$0") ||
22807 matchAsm(AsmPieces[0], "bswapq", "$0") ||
22808 matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22809 matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22810 matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22811 // No need to check constraints, nothing other than the equivalent of
22812 // "=r,0" would be valid here.
22813 return IntrinsicLowering::LowerToByteSwap(CI);
22816 // rorw $$8, ${0:w} --> llvm.bswap.i16
22817 if (CI->getType()->isIntegerTy(16) &&
22818 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22819 (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22820 matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22822 const std::string &ConstraintsStr = IA->getConstraintString();
22823 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22824 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22825 if (clobbersFlagRegisters(AsmPieces))
22826 return IntrinsicLowering::LowerToByteSwap(CI);
22830 if (CI->getType()->isIntegerTy(32) &&
22831 IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22832 matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22833 matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22834 matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22836 const std::string &ConstraintsStr = IA->getConstraintString();
22837 SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22838 array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22839 if (clobbersFlagRegisters(AsmPieces))
22840 return IntrinsicLowering::LowerToByteSwap(CI);
22843 if (CI->getType()->isIntegerTy(64)) {
22844 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22845 if (Constraints.size() >= 2 &&
22846 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22847 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22848 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
22849 if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22850 matchAsm(AsmPieces[1], "bswap", "%edx") &&
22851 matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22852 return IntrinsicLowering::LowerToByteSwap(CI);
22860 /// getConstraintType - Given a constraint letter, return the type of
22861 /// constraint it is for this target.
22862 X86TargetLowering::ConstraintType
22863 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22864 if (Constraint.size() == 1) {
22865 switch (Constraint[0]) {
22876 return C_RegisterClass;
22900 return TargetLowering::getConstraintType(Constraint);
22903 /// Examine constraint type and operand type and determine a weight value.
22904 /// This object must already have been set up with the operand type
22905 /// and the current alternative constraint selected.
22906 TargetLowering::ConstraintWeight
22907 X86TargetLowering::getSingleConstraintMatchWeight(
22908 AsmOperandInfo &info, const char *constraint) const {
22909 ConstraintWeight weight = CW_Invalid;
22910 Value *CallOperandVal = info.CallOperandVal;
22911 // If we don't have a value, we can't do a match,
22912 // but allow it at the lowest weight.
22913 if (!CallOperandVal)
22915 Type *type = CallOperandVal->getType();
22916 // Look at the constraint type.
22917 switch (*constraint) {
22919 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22930 if (CallOperandVal->getType()->isIntegerTy())
22931 weight = CW_SpecificReg;
22936 if (type->isFloatingPointTy())
22937 weight = CW_SpecificReg;
22940 if (type->isX86_MMXTy() && Subtarget->hasMMX())
22941 weight = CW_SpecificReg;
22945 if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22946 ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22947 weight = CW_Register;
22950 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22951 if (C->getZExtValue() <= 31)
22952 weight = CW_Constant;
22956 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22957 if (C->getZExtValue() <= 63)
22958 weight = CW_Constant;
22962 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22963 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22964 weight = CW_Constant;
22968 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22969 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22970 weight = CW_Constant;
22974 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22975 if (C->getZExtValue() <= 3)
22976 weight = CW_Constant;
22980 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22981 if (C->getZExtValue() <= 0xff)
22982 weight = CW_Constant;
22987 if (dyn_cast<ConstantFP>(CallOperandVal)) {
22988 weight = CW_Constant;
22992 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22993 if ((C->getSExtValue() >= -0x80000000LL) &&
22994 (C->getSExtValue() <= 0x7fffffffLL))
22995 weight = CW_Constant;
22999 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23000 if (C->getZExtValue() <= 0xffffffff)
23001 weight = CW_Constant;
23008 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23009 /// with another that has more specific requirements based on the type of the
23010 /// corresponding operand.
23011 const char *X86TargetLowering::
23012 LowerXConstraint(EVT ConstraintVT) const {
23013 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23014 // 'f' like normal targets.
23015 if (ConstraintVT.isFloatingPoint()) {
23016 if (Subtarget->hasSSE2())
23018 if (Subtarget->hasSSE1())
23022 return TargetLowering::LowerXConstraint(ConstraintVT);
23025 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23026 /// vector. If it is invalid, don't add anything to Ops.
23027 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23028 std::string &Constraint,
23029 std::vector<SDValue>&Ops,
23030 SelectionDAG &DAG) const {
23033 // Only support length 1 constraints for now.
23034 if (Constraint.length() > 1) return;
23036 char ConstraintLetter = Constraint[0];
23037 switch (ConstraintLetter) {
23040 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23041 if (C->getZExtValue() <= 31) {
23042 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23048 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23049 if (C->getZExtValue() <= 63) {
23050 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23056 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23057 if (isInt<8>(C->getSExtValue())) {
23058 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23064 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23065 if (C->getZExtValue() <= 255) {
23066 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23072 // 32-bit signed value
23073 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23074 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23075 C->getSExtValue())) {
23076 // Widen to 64 bits here to get it sign extended.
23077 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23080 // FIXME gcc accepts some relocatable values here too, but only in certain
23081 // memory models; it's complicated.
23086 // 32-bit unsigned value
23087 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23088 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23089 C->getZExtValue())) {
23090 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23094 // FIXME gcc accepts some relocatable values here too, but only in certain
23095 // memory models; it's complicated.
23099 // Literal immediates are always ok.
23100 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23101 // Widen to 64 bits here to get it sign extended.
23102 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23106 // In any sort of PIC mode addresses need to be computed at runtime by
23107 // adding in a register or some sort of table lookup. These can't
23108 // be used as immediates.
23109 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23112 // If we are in non-pic codegen mode, we allow the address of a global (with
23113 // an optional displacement) to be used with 'i'.
23114 GlobalAddressSDNode *GA = nullptr;
23115 int64_t Offset = 0;
23117 // Match either (GA), (GA+C), (GA+C1+C2), etc.
23119 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23120 Offset += GA->getOffset();
23122 } else if (Op.getOpcode() == ISD::ADD) {
23123 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23124 Offset += C->getZExtValue();
23125 Op = Op.getOperand(0);
23128 } else if (Op.getOpcode() == ISD::SUB) {
23129 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23130 Offset += -C->getZExtValue();
23131 Op = Op.getOperand(0);
23136 // Otherwise, this isn't something we can handle, reject it.
23140 const GlobalValue *GV = GA->getGlobal();
23141 // If we require an extra load to get this address, as in PIC mode, we
23142 // can't accept it.
23143 if (isGlobalStubReference(
23144 Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23147 Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23148 GA->getValueType(0), Offset);
23153 if (Result.getNode()) {
23154 Ops.push_back(Result);
23157 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23160 std::pair<unsigned, const TargetRegisterClass*>
23161 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23163 // First, see if this is a constraint that directly corresponds to an LLVM
23165 if (Constraint.size() == 1) {
23166 // GCC Constraint Letters
23167 switch (Constraint[0]) {
23169 // TODO: Slight differences here in allocation order and leaving
23170 // RIP in the class. Do they matter any more here than they do
23171 // in the normal allocation?
23172 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23173 if (Subtarget->is64Bit()) {
23174 if (VT == MVT::i32 || VT == MVT::f32)
23175 return std::make_pair(0U, &X86::GR32RegClass);
23176 if (VT == MVT::i16)
23177 return std::make_pair(0U, &X86::GR16RegClass);
23178 if (VT == MVT::i8 || VT == MVT::i1)
23179 return std::make_pair(0U, &X86::GR8RegClass);
23180 if (VT == MVT::i64 || VT == MVT::f64)
23181 return std::make_pair(0U, &X86::GR64RegClass);
23184 // 32-bit fallthrough
23185 case 'Q': // Q_REGS
23186 if (VT == MVT::i32 || VT == MVT::f32)
23187 return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23188 if (VT == MVT::i16)
23189 return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23190 if (VT == MVT::i8 || VT == MVT::i1)
23191 return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23192 if (VT == MVT::i64)
23193 return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23195 case 'r': // GENERAL_REGS
23196 case 'l': // INDEX_REGS
23197 if (VT == MVT::i8 || VT == MVT::i1)
23198 return std::make_pair(0U, &X86::GR8RegClass);
23199 if (VT == MVT::i16)
23200 return std::make_pair(0U, &X86::GR16RegClass);
23201 if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23202 return std::make_pair(0U, &X86::GR32RegClass);
23203 return std::make_pair(0U, &X86::GR64RegClass);
23204 case 'R': // LEGACY_REGS
23205 if (VT == MVT::i8 || VT == MVT::i1)
23206 return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23207 if (VT == MVT::i16)
23208 return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23209 if (VT == MVT::i32 || !Subtarget->is64Bit())
23210 return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23211 return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23212 case 'f': // FP Stack registers.
23213 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23214 // value to the correct fpstack register class.
23215 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23216 return std::make_pair(0U, &X86::RFP32RegClass);
23217 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23218 return std::make_pair(0U, &X86::RFP64RegClass);
23219 return std::make_pair(0U, &X86::RFP80RegClass);
23220 case 'y': // MMX_REGS if MMX allowed.
23221 if (!Subtarget->hasMMX()) break;
23222 return std::make_pair(0U, &X86::VR64RegClass);
23223 case 'Y': // SSE_REGS if SSE2 allowed
23224 if (!Subtarget->hasSSE2()) break;
23226 case 'x': // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23227 if (!Subtarget->hasSSE1()) break;
23229 switch (VT.SimpleTy) {
23231 // Scalar SSE types.
23234 return std::make_pair(0U, &X86::FR32RegClass);
23237 return std::make_pair(0U, &X86::FR64RegClass);
23245 return std::make_pair(0U, &X86::VR128RegClass);
23253 return std::make_pair(0U, &X86::VR256RegClass);
23258 return std::make_pair(0U, &X86::VR512RegClass);
23264 // Use the default implementation in TargetLowering to convert the register
23265 // constraint into a member of a register class.
23266 std::pair<unsigned, const TargetRegisterClass*> Res;
23267 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23269 // Not found as a standard register?
23271 // Map st(0) -> st(7) -> ST0
23272 if (Constraint.size() == 7 && Constraint[0] == '{' &&
23273 tolower(Constraint[1]) == 's' &&
23274 tolower(Constraint[2]) == 't' &&
23275 Constraint[3] == '(' &&
23276 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23277 Constraint[5] == ')' &&
23278 Constraint[6] == '}') {
23280 Res.first = X86::ST0+Constraint[4]-'0';
23281 Res.second = &X86::RFP80RegClass;
23285 // GCC allows "st(0)" to be called just plain "st".
23286 if (StringRef("{st}").equals_lower(Constraint)) {
23287 Res.first = X86::ST0;
23288 Res.second = &X86::RFP80RegClass;
23293 if (StringRef("{flags}").equals_lower(Constraint)) {
23294 Res.first = X86::EFLAGS;
23295 Res.second = &X86::CCRRegClass;
23299 // 'A' means EAX + EDX.
23300 if (Constraint == "A") {
23301 Res.first = X86::EAX;
23302 Res.second = &X86::GR32_ADRegClass;
23308 // Otherwise, check to see if this is a register class of the wrong value
23309 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23310 // turn into {ax},{dx}.
23311 if (Res.second->hasType(VT))
23312 return Res; // Correct type already, nothing to do.
23314 // All of the single-register GCC register classes map their values onto
23315 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
23316 // really want an 8-bit or 32-bit register, map to the appropriate register
23317 // class and return the appropriate register.
23318 if (Res.second == &X86::GR16RegClass) {
23319 if (VT == MVT::i8 || VT == MVT::i1) {
23320 unsigned DestReg = 0;
23321 switch (Res.first) {
23323 case X86::AX: DestReg = X86::AL; break;
23324 case X86::DX: DestReg = X86::DL; break;
23325 case X86::CX: DestReg = X86::CL; break;
23326 case X86::BX: DestReg = X86::BL; break;
23329 Res.first = DestReg;
23330 Res.second = &X86::GR8RegClass;
23332 } else if (VT == MVT::i32 || VT == MVT::f32) {
23333 unsigned DestReg = 0;
23334 switch (Res.first) {
23336 case X86::AX: DestReg = X86::EAX; break;
23337 case X86::DX: DestReg = X86::EDX; break;
23338 case X86::CX: DestReg = X86::ECX; break;
23339 case X86::BX: DestReg = X86::EBX; break;
23340 case X86::SI: DestReg = X86::ESI; break;
23341 case X86::DI: DestReg = X86::EDI; break;
23342 case X86::BP: DestReg = X86::EBP; break;
23343 case X86::SP: DestReg = X86::ESP; break;
23346 Res.first = DestReg;
23347 Res.second = &X86::GR32RegClass;
23349 } else if (VT == MVT::i64 || VT == MVT::f64) {
23350 unsigned DestReg = 0;
23351 switch (Res.first) {
23353 case X86::AX: DestReg = X86::RAX; break;
23354 case X86::DX: DestReg = X86::RDX; break;
23355 case X86::CX: DestReg = X86::RCX; break;
23356 case X86::BX: DestReg = X86::RBX; break;
23357 case X86::SI: DestReg = X86::RSI; break;
23358 case X86::DI: DestReg = X86::RDI; break;
23359 case X86::BP: DestReg = X86::RBP; break;
23360 case X86::SP: DestReg = X86::RSP; break;
23363 Res.first = DestReg;
23364 Res.second = &X86::GR64RegClass;
23367 } else if (Res.second == &X86::FR32RegClass ||
23368 Res.second == &X86::FR64RegClass ||
23369 Res.second == &X86::VR128RegClass ||
23370 Res.second == &X86::VR256RegClass ||
23371 Res.second == &X86::FR32XRegClass ||
23372 Res.second == &X86::FR64XRegClass ||
23373 Res.second == &X86::VR128XRegClass ||
23374 Res.second == &X86::VR256XRegClass ||
23375 Res.second == &X86::VR512RegClass) {
23376 // Handle references to XMM physical registers that got mapped into the
23377 // wrong class. This can happen with constraints like {xmm0} where the
23378 // target independent register mapper will just pick the first match it can
23379 // find, ignoring the required type.
23381 if (VT == MVT::f32 || VT == MVT::i32)
23382 Res.second = &X86::FR32RegClass;
23383 else if (VT == MVT::f64 || VT == MVT::i64)
23384 Res.second = &X86::FR64RegClass;
23385 else if (X86::VR128RegClass.hasType(VT))
23386 Res.second = &X86::VR128RegClass;
23387 else if (X86::VR256RegClass.hasType(VT))
23388 Res.second = &X86::VR256RegClass;
23389 else if (X86::VR512RegClass.hasType(VT))
23390 Res.second = &X86::VR512RegClass;
23396 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23398 // Scaling factors are not free at all.
23399 // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23400 // will take 2 allocations in the out of order engine instead of 1
23401 // for plain addressing mode, i.e. inst (reg1).
23403 // vaddps (%rsi,%drx), %ymm0, %ymm1
23404 // Requires two allocations (one for the load, one for the computation)
23406 // vaddps (%rsi), %ymm0, %ymm1
23407 // Requires just 1 allocation, i.e., freeing allocations for other operations
23408 // and having less micro operations to execute.
23410 // For some X86 architectures, this is even worse because for instance for
23411 // stores, the complex addressing mode forces the instruction to use the
23412 // "load" ports instead of the dedicated "store" port.
23413 // E.g., on Haswell:
23414 // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23415 // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
23416 if (isLegalAddressingMode(AM, Ty))
23417 // Scale represents reg2 * scale, thus account for 1
23418 // as soon as we use a second register.
23419 return AM.Scale != 0;
23423 bool X86TargetLowering::isTargetFTOL() const {
23424 return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();